<?php

namespace App\Http\Livewire;

use App\Models\Company;
use App\Models\TypeWorkPermit;
use App\Models\User;
use App\Models\WorkCertificate;
use App\Models\WorkPermit;
use App\Traits\OrderByTable;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Livewire\WithFileUploads;
use Livewire\WithPagination;
use Illuminate\Support\Str as Str;

class Employee_WorkCertificatesController extends Component
{
    use WithFileUploads;
    use WithPagination;
    use OrderByTable;

    public $user, $user_id, $company_id, $first_name, $last_name, $count_reg, $selected_id;
    public $salary_include, $requested_to, $solicitation_date, $reviewed_by, $rejected_reason, $status;

    public $breadcrumb_show = true;

    private $pagination = 10;

    protected $paginationTheme = 'bootstrap';

    public function updatingSearch(){
        $this->resetPage();
    }

    public function mount()
    {
        UserAuthPermission('Employee_work_certificates_index');
        $user = User::find(auth()->user()->id);
        EmployeeOtherCompany($user->id); //Verifica que el empleado pertenezca a la empresa

        $this->user = $user;
        $this->user_id = $user->id;
        $this->first_name = $user->first_name;
        $this->last_name = $user->last_name;
        $company = Company::find(Auth::user()->CompanyInfo('id'));
        $this->company_id = $company->id;
        $this->pageTitle = 'Lista';
        $this->componentName = 'Certificados laborales';
    }

    public function render()
    {

        $work_certificates = WorkCertificate::where('user_id', $this->user_id)
                            ->orderBy('solicitation_date', 'desc')
                            ->paginate($this->pagination);

        $this->count_reg = $work_certificates->count();
        return view('livewire.employee.work-certificates.component', compact('work_certificates'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function resetUI(){
        $this->selected_id = '';
        $this->solicitation_date = '';
        $this->reviewed_by = '';
        $this->resetErrorBag();
    }

    public function openAddWorkCertificate(){
        $useractions = UserAuthPermissionActions('Employee_work_certificates_index');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        //fecha de sistema menos 30 días
        $date_system = Carbon::now()->subDays(30);
        $work_certificates_date_solicitation = WorkCertificate::where('user_id', $this->user_id)
                                            ->where('solicitation_date', '>=', $date_system)
                                            ->orderBy('solicitation_date', 'desc')
                                            ->get();

        //solo se puede solicitar un certificado laboral por cada 30 días
        if ($work_certificates_date_solicitation->count() > 0){
            $this->emit('item-error', 'Solo se puede solicitar un certificado laboral cada 30 días');
            return false;
        }

        $this->selected_id = 0;
        $this->requested_to = '';
        $this->resetUI();
        $this->emit('show-modal','Abrir Modal');
    }

    public function Store(){
        $useractions = UserAuthPermissionActions('Employee_work_certificates_index');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        if ($this->salary_include == null)//al no dar clic en el select el valor es null, por lo cual se debe convertir a 0 que es el valor por defecto
            $this->salary_include = '0';

        WorkCertificate::create([
            'user_id' => $this->user_id,
            'company_id' => $this->company_id,
            'salary_include' => $this->salary_include,
            'requested_to' => $this->requested_to,
            'solicitation_date' => Carbon::now(),
        ]);

        foreach (AdminsCompany($this->company_id) as $admin) {
            $message = NotifyMessageCustom(
                $title = 'El Empleado '.$this->first_name.' '.$this->last_name.' ha solicitado un certificado laboral',
                $body = 'Se ha solicitado un certificado laboral para el empleado '.$this->first_name.' '.$this->last_name.', por favor ingrese a la plataforma para revisar.',
                $url = route('certificados-laborales-empleado', Auth::user()->id),
                $button_text = 'Ver Solicitud',
                $via_from = 'Employee',
                $user_to_id = $admin->user_id,
                $user_from_id = Auth::user()->id,
            );
        }

        $this->emit('item-added','La solicitud se ha creado correctamente');
        $this->resetUI();
    }

    public function openViewRejectWorkCertificate($id){

        $useractions = UserAuthPermissionActions('Employee_work_certificates_index');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $work_certificate = WorkCertificate::find($id);
        $this->selected_id = $id;
        $this->rejected_reason = $work_certificate->rejected_reason;


        $this->emit('show-modal-reject','Abrir Modal');
    }



}
