<?php

namespace App\Http\Livewire;

use App\Models\Company;
use App\Models\Contract;
use App\Models\PublicHealthEntity;
use App\Models\User;
use App\Traits\OrderByTable;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
use Livewire\WithPagination;

class Company_EmployeeDetailController extends Component
{
    use WithPagination;
    use OrderByTable;

    public $search, $company_id, $selected_user_id, $pageTitle, $componentName, $user_id, $search_modal, $count_reg_modal, $status_contract, $type_contract, $sub_type_contract;
    public $selectedCompany;
    public $company_name, $company_plan_name, $company_plan_id;
    public $first_name, $last_name, $document, $phone, $email, $status, $password, $image, $selected_id, $fileLoaded;
    public $company_employee_update_time, $employee_update_time, $initial_date_cv, $max_days_update_cv, $close_update_cv;
    public $title_position, $salary, $payment_method, $start_date_work, $end_date_work, $place_hired, $place_work, $work_day, $eps_id, $expiration_contract, $contract_modality;
    public $breadcrumb_show = true;
    private $pagination = 10;
    private $pagination_modal = 5;

    protected $paginationTheme = 'bootstrap';

    public function updatingSearch(){
        $this->emit('show-modal', 'modal-contract');
    }

    public function mount($id)
    {
        UsersIdExists($id);
        UserAuthPermission('Company_employee_index');
        EmployeeOtherCompany($id); //Verifica que el empleado pertenezca a la empresa
        $this->company_id = Company::find(Auth::user()->CompanyId())->id;
        $company = Company::find($this->company_id);
        $this->pageTitle = 'Perfil';
        $this->componentName = 'Empleado';
        $this->company_name = $company->name;
        $this->company_plan_name = $company->plan->name;
        $this->company_plan_id = $company->plan->id;
        $this->user_id = $id;
        $user = User::find($this->user_id);
        $this->first_name = $user->first_name;
        $this->last_name = $user->last_name;
        $this->company_employee_update_time = $company->company_employee_update_time;
        $company_user = Company::find($this->company_id)->users()->wherePivot('user_id', $this->user_id)->get()->first();


            switch(getDifferenceDateWithDays($company_user->pivot->initial_date_cv, $company->company_employee_update_time)['status']){
                case '0':
                    $this->employee_update_time = getDifferenceDateWithDays($company_user->pivot->initial_date_cv, $company->company_employee_update_time)['difference'];
                    $this->max_days_update_cv = 1; // booleano usado para activar/desactivar el botón de reiniciar días de actualización de hoja de vida
                $this->close_update_cv = 0; // booleano usado para activar/desactivar el botón de cerrar tiempo de actualización de hoja de vida
                    break;
                case '1':
                    $this->employee_update_time = getDifferenceDateWithDays($company_user->pivot->initial_date_cv, $company->company_employee_update_time)['difference'];
                    $this->max_days_update_cv = 1;
                    $this->close_update_cv = 1;
                    break;
                case '2':
                    $this->employee_update_time = getDifferenceDateWithDays($company_user->pivot->initial_date_cv, $company->company_employee_update_time)['difference'];
                    $this->max_days_update_cv = 0;
                    $this->close_update_cv = 1;
                    break;
            }

    }

    public function render()
    {
        $user_id=$this->user_id;
        return view('livewire.company.employee.detail.component',compact('user_id'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function openContract(User $user)
    {
        $this->user = $user;
        $this->user_id = $user->id;
        $this->first_name = $user->first_name;
        $this->last_name = $user->last_name;
        $this->type_contract = '';
        $this->sub_type_contract = '';
        $this->emit('show-modal', 'modal-contract');
    }

    public function resetUI()
    {
        $this->first_name = '';
        $this->last_name = '';
        $this->document = '';
        $this->phone = '';
        $this->email = '';
        $this->password = '';
        $this->image = '';
        $this->search = '';
        $this->status ='';
        $this->selected_user_id = 0;
        $this->resetValidation();
        $this->resetPage();
    }

    public function ResetUpdateTimeEmployee()
    {
        $company = Company::find($this->company_id);
        $company->users()->updateExistingPivot($this->user_id, ['initial_date_cv' => NULL]);
        $company->company_employee_update_time == 1 ? $d = "1 día" : $d = $company->company_employee_update_time . " días";
        $this->employee_update_time = $d;
        $this->max_days_update_cv = 0;
        $this->close_update_cv = 1;
        $this->emit('item-updated', 'Se ha reiniciado el tiempo de actualización de hoja de vida del empleado');
    }

    public function CloseTimeUpdateEmployee()
    {
        $company = Company::find($this->company_id);
        $company->users()->updateExistingPivot($this->user_id, ['initial_date_cv' => Carbon::now()->subDays($company->company_employee_update_time)]);
        $this->employee_update_time = '0 días';
        $this->max_days_update_cv = 1;
        $this->close_update_cv = 0;
        $this->emit('item-updated', 'Se ha cerrado el tiempo de actualización de hoja de vida del empleado');
    }
    public function openProfile(User $user)
    {
        $useractions = UserAuthPermissionActions('Company_contracts_users_profile_update');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }

        $this->user_id = $user->id;
        $user = User::find($this->user_id);
        $this->first_name = $user->first_name;
        $this->last_name = $user->last_name;
        $company = Company::find($this->company_id)->users()->wherePivot('user_id', $this->user_id)->get()->first();
        $this->title_position = $company->pivot->title_position;
        $this->salary = $company->pivot->salary;
        $this->payment_method = $company->pivot->payment_method;
        $this->start_date_work = $company->pivot->start_date_work;
        $this->end_date_work = $company->pivot->end_date_work;
        $this->place_hired = $company->pivot->place_hired;
        $this->place_work = $company->pivot->place_work;
        $this->work_day = $company->pivot->work_day;
        $this->eps_id = $company->pivot->eps_id;
        $this->expiration_contract = $company->pivot->expiration_contract;
        $this->contract_modality = $company->pivot->contract_modality;
        $this->emit('show-modal-profile', 'profile');
    }

    public function storeProfile(){
        $company = Company::find($this->company_id);
        $rules = [
            'title_position' => 'required|max:99',
            'salary' => 'required',
            'payment_method' => 'required',
            'start_date_work' => 'required|date',
            'end_date_work' => 'required|date|after:start_date_work',
            'place_hired' => 'required|max:99',
            'place_work' => 'required|max:99',
            'work_day' => 'required',
            'eps_id' => 'required',
            'expiration_contract' => 'required|date',
            'contract_modality' => 'required',
        ];
        $messages = [
            'title_position.required' => 'El campo "Cargo u Oficio" es obligatorio',
            'title_position.max' => 'El campo "Cargo u Oficio" no puede tener más de 99 caracteres',
            'salary.required' => 'El campo "Salario" es obligatorio',
            'payment_method.required' => 'El campo "Forma de Pago" es obligatorio',
            'start_date_work.required' => 'El campo "Fecha de Inicio de Labores" es obligatorio',
            'start_date_work.date' => 'El campo "Fecha de Inicio de Labores" debe ser una fecha',
            'end_date_work.required' => 'El campo "Fecha de Fin de Labores" es obligatorio',
            'end_date_work.date' => 'El campo "Fecha de Fin de Labores" debe ser una fecha',
            'end_date_work.after' => 'El campo "Fecha de Fin de Labores" debe ser mayor a la fecha de inicio de labores',
            'place_hired.required' => 'El campo "Lugar donde ha sido contratado" es obligatorio',
            'place_hired.max' => 'El campo "Lugar donde ha sido contratado" no puede tener más de 99 caracteres',
            'place_work.required' => 'El campo "Lugar donde desempeñará labores" es obligatorio',
            'place_work.max' => 'El campo "Lugar donde desempeñará labores" no puede tener más de 99 caracteres',
            'work_day.required' => 'El campo "Jornada laboral" es obligatorio',
            'eps_id.required' => 'El campo "EPS" es obligatorio',
            'expiration_contract.required' => 'El campo "Fecha de vencimiento del Contrato" es obligatorio',
            'expiration_contract.date' => 'El campo "Fecha de vencimiento del Contrato" debe ser una fecha',
            'contract_modality.required' => 'El campo "Modalidad de Contrato" es obligatorio',
        ];

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

        $company->users()->updateExistingPivot($this->user_id, [
            'title_position' => $this->title_position,
            'salary' => (float)str_replace(',', '', $this->salary),
            'payment_method' => $this->payment_method,
            'start_date_work' => $this->start_date_work,
            'end_date_work' => $this->end_date_work,
            'place_hired' => $this->place_hired,
            'place_work' => $this->place_work,
            'work_day' => $this->work_day,
            'eps_id' => $this->eps_id,
            'expiration_contract' => $this->expiration_contract,
            'contract_modality' => $this->contract_modality,
        ]);
        $this->emit('hide-modal-profile', 'Perfil actualizado correctamente');
    }

    function AddContractUser(Contract $contract){
        $useractions = UserAuthPermissionActions('Company_contracts_users_create');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $params=["{Nombre}", "{Apellido}", "{Tipo_documento}","{Documento}","{Edad}","{Cargo}", "{Salario}", "{Empresa}"];
        $user=User::find($this->user_id);
        $data_user=[$user->first_name, $user->last_name, $user->type_document, $user->document, $user->age, "Desarrollador", "6850000", $this->company_name];

        $new_content = str_replace($params, $data_user, $contract->content);

        $historyContractUser=HistoryContractsUsers::create([
            'user_id' => $this->user_id,
            'company_id' => $this->company_id,
            'contract_id' => $contract->id,
            'content' => $new_content,
            'status' => $this->status_contract,

        ]);

        if ($historyContractUser){
            return redirect()->route('historial-contratos-usuarios',[$this->user_id]);
        }

    }
}
