<?php

namespace App\Http\Livewire;

use App\Models\WorkExperience;
use Livewire\Component;
use Livewire\WithFileUploads;
use App\Traits\OrderByTable;

class CV_WorkExperiencesController extends Component
{

    use OrderByTable;
    use WithFileUploads;

    public $selected_WE_id, $company, $type_company, $direction, $customFileName, $work_experienc;
    public $phone, $date_entry, $date_retirement, $is_currently_working_here, $document_upload, $document_upload_view, $department;
    public $title_position, $responsibilities;
    public $activeButtonSaveUpdate;

    public function mount($user_sel_id, $activeButtonSaveUpdate)
    {
        $this->user_sel_id = $user_sel_id;
        $this->componentName = 'Experiencia Laboral';
        $this->activeButtonSaveUpdate = $activeButtonSaveUpdate;
    }

    public function resetUI()
    {
        $this->company = '';
        $this->type_company = '';
        $this->title_position = '';
        $this->department = '';
        $this->direction = '';
        $this->phone = '';
        $this->date_entry = '';
        $this->date_retirement= '';
        $this->currently_working = '';
        $this->document_upload = '';
        $this->document_upload_view = '';
        $this->is_currently_working_here = '';
        $this->responsibilities ='';
        $this->resetValidation();
    }

    public function render()
    {
        $work_experiences = WorkExperience::where('user_id',$this->user_sel_id)->get();
        return view('livewire.cv-employee.detail.partials.work-experiences.component', compact('work_experiences'));
    }

    public function openAddWE()
    {
        if (EmployeeOtherCompany($this->user_sel_id, true)[0] == NULL)
        {
            $this->emit('item-error-WE', EmployeeOtherCompany($this->user_sel_id, true)[1]);
            return false;
        }
        $this->selected_WE_id = 0;
        $this->emit('show-modal-WE','Abrir Modal');
    }


    public function StoreWE()
    {
        if (EmployeeOtherCompany($this->user_sel_id, true)[0] == NULL)
        {
            $this->emit('item-error-WE', EmployeeOtherCompany($this->user_sel_id, true)[1]);
            return false;
        }
        $rules = [
            'company' => 'required|max:99',
            'type_company' => 'required|not_in:Seleccionar',
            'department' => 'required|max:99',
            'title_position' => 'required|max:99',
            'direction' => 'required|min:3',
            'phone' => 'required|min:7|max:15',
            'date_entry' => 'required|date',
            'date_retirement' =>  ['required_if:is_currently_working_here,0', 'date','after_or_equal:date_entry'],
            'responsibilities' => 'required|min:3',
            'is_currently_working_here' => 'required|not_in:Seleccionar',
        ];


        $messages = [
            'company.required' => 'El campo es obligatorio',
            'company.max' => 'El campo debe tener máximo 99 caracteres',
            'type_company.required' => 'El campo es obligatorio',
            'type_company.not_in' => 'Selecciona un tipo de empresa diferente a Seleccionar',
            'department.required' => 'El campo es obligatorio',
            'department.max' => 'El campo debe tener máximo 99 caracteres',
            'title_position.required' => 'El campo es obligatorio',
            'title_position.max' => 'El campo debe tener máximo 99 caracteres',
            'direction.required' => 'El campo es obligatorio',
            'direction.max' => 'El campo debe tener máximo 99 caracteres',
            'phone.required' => 'Ingresa el número de documento',
            'phone.min' => 'El Teléfono debe tener como mínimo 7 caracteres',
            'phone.max' => 'El Teléfono debe tener máximo 15 caracteres',
            'date_entry.required' => 'El campo es obligatorio',
            'date_entry.date_format' => 'El formato de fecha es incorrecto',
            'date_retirement.required' => 'El campo es obligatorio',
            'date_retirement.date_format' => 'El formato de fecha es incorrecto',
            'date_retirement.after_or_equal' => 'La fecha debe ser mayor o igual a la fecha de entrada',
            'responsibilities.required' => 'El campo es obligatorio',
            'responsibilities.min' => 'El campo debe tener mínimo 3 caracteres',
            'is_currently_working_here.required' => 'El campo es obligatorio',
            'is_currently_working_here.not_in' => 'Selecciona una opción diferente a Seleccionar',
        ];

        $this->validate($rules, $messages);
        $work_experiences = WorkExperience::create([
            'user_id' => $this->user_sel_id,
            'company' => $this->company,
            'type_company' => $this->type_company,
            'department' => $this->department,
            'title_position' => $this->title_position,
            'direction' => $this->direction,
            'phone' => $this->phone,
            'date_entry' => $this->date_entry,
            'date_retirement' => $this->date_retirement,
            'responsibilities' => $this->responsibilities,
            'is_currently_working_here' => $this->is_currently_working_here,
        ]);

        if($this->document_upload)
        {
            $customFileName = uniqid(time(), false).'.'.$this->document_upload->extension();
            $this->document_upload->storeAs('public/users/'.$this->user_sel_id.'/work_experiences', $customFileName);
            $work_experiences->document_upload = $customFileName;
            $work_experiences->save();
        }
        $this->resetUI();
        $this->emit('item-added-WE', 'Experiencia Laboral registrada');
    }


    public function EditWE(WorkExperience $work_experienc)
    {
        if (EmployeeOtherCompany($this->user_sel_id, true)[0] == NULL)
        {
            $this->emit('item-error-WE', EmployeeOtherCompany($this->user_sel_id, true)[1]);
            return false;
        }
        $this->selected_WE_id = $work_experienc->id;
        $this->company = $work_experienc->company;
        $this->type_company = $work_experienc->type_company;
        $this->department = $work_experienc->department;
        $this->title_position = $work_experienc->title_position;
        $this->direction = $work_experienc->direction;
        $this->phone = $work_experienc->phone;
        $this->date_entry = $work_experienc->date_entry;
        $this->date_retirement = $work_experienc->date_retirement;
        $this->is_currently_working_here = $work_experienc->is_currently_working_here;
        $this->responsibilities = $work_experienc->responsibilities;
        $this->document_upload_view = $work_experienc->document_upload;
        $this->emit('show-modal-WE', 'Abrir Modal');
    }

    public function UpdateWE()
    {
        if (EmployeeOtherCompany($this->user_sel_id, true)[0] == NULL)
        {
            $this->emit('item-error-WE', EmployeeOtherCompany($this->user_sel_id, true)[1]);
            return false;
        }
        $rules = [
            'company' => 'required|max:99',
            'type_company' => 'required|not_in:Seleccionar',
            'department' => 'required|max:99',
            'title_position' => 'required|max:99',
            'direction' => 'required|min:3',
            'phone' => 'required|min:7|max:15',
            'date_entry' => 'required|date',
            'date_retirement' =>  ['required_if:is_currently_working_here,0', 'date','after_or_equal:date_entry'],
            'responsibilities' => 'required|min:3',
            'is_currently_working_here' => 'required|not_in:Seleccionar',
        ];

        $messages = [
            'company.required' => 'El campo es obligatorio',
            'company.max' => 'El campo debe tener máximo 99 caracteres',
            'type_company.required' => 'El campo es obligatorio',
            'type_company.not_in' => 'Selecciona un tipo de empresa diferente a Seleccionar',
            'department.required' => 'El campo es obligatorio',
            'department.max' => 'El campo debe tener máximo 99 caracteres',
            'title_position.required' => 'El campo es obligatorio',
            'title_position.not_in' => 'Selecciona una modalidad diferente a Seleccionar',
            'direction.required' => 'El campo es obligatorio',
            'direction.max' => 'El campo debe tener máximo 99 caracteres',
            'phone.required' => 'Ingresa el número de documento',
            'phone.min' => 'El Teléfono debe tener como mínimo 6 caracteres',
            'phone.max' => 'El Teléfono debe tener máximo 10 caracteres',
            'date_entry.required' => 'El campo es obligatorio',
            'date_entry.date_format' => 'El formato de fecha es incorrecto',
            'date_retirement.required' => 'El campo es obligatorio',
            'date_retirement.date_format' => 'El formato de fecha es incorrecto',
            'date_retirement.after_or_equal' => 'La fecha debe ser mayor o igual a la fecha de entrada',
            'responsibilities.required' => 'El campo es obligatorio',
            'responsibilities.min' => 'El campo debe tener mínimo 3 caracteres',
        ];

        $this->validate($rules, $messages);

        $work_experiences = WorkExperience::find($this->selected_WE_id);

        $work_experiences->update([
            'user_id' => $this->user_sel_id,
            'company' => $this->company,
            'type_company' => $this->type_company,
            'department' => $this->department,
            'title_position' => $this->title_position,
            'direction' => $this->direction,
            'phone' => $this->phone,
            'date_entry' => $this->date_entry,
            'date_retirement' => $this->date_retirement,
            'responsibilities' => $this->responsibilities,
            'is_currently_working_here' => $this->is_currently_working_here,
        ]);


        if($this->document_upload)
        {
            $customFileName = uniqid(time(), false). '.' . $this->document_upload->extension();
            $this->document_upload->storeAs('public/users/'.$this->user_sel_id.'/work_experiences/',$customFileName);
            $supportName = $work_experiences->document_upload; //nombre de la imagen actual guardada en la base de datos

            $work_experiences->document_upload = $customFileName; //asignamos el nuevo nombre de la imagen
            $work_experiences->save();
            //debug($supportName);
            if ($supportName != null)//si la consulta devuelve el nombre de una imagen
            {
                if(file_exists('storage/users/'.$this->user_sel_id.'/work_experiences/'. $supportName))//verificamos que la imagen exista fisicamente
                {
                    unlink('storage/users/'.$this->user_sel_id.'/work_experiences/' . $supportName); //eliminamos la imagen
                }
            }
        }

        $this->resetUI();
        $this->emit('item-added-WE', 'Experiencia Laboral registrada');

    }

    protected $listeners = ['deleteRowWE' => 'DestroyWE'];

    public function DestroyWE(WorkExperience $work_experience)
    {
        if (EmployeeOtherCompany($this->user_sel_id, true)[0] == NULL)
        {
            $this->emit('item-error-WE', EmployeeOtherCompany($this->user_sel_id, true)[1]);
            return false;
        }
        $imageName = $work_experience->document_upload;
        if ($imageName != null)//si la consulta devuelve el nombre de una imagen
        {
            if(file_exists('storage/users/'.$this->user_sel_id.'/work_experiences/'. $imageName))//verificamos que la imagen exista fisicamente
            {
                unlink('storage/users/'.$this->user_sel_id.'/work_experiences/' . $imageName); //eliminamos la imagen
            }
        }
        $work_experience->delete();
        $this->emit('item-deleted-WE', 'Se eliminó la Experiencia Laboral con éxito');
    }
}
