<?php

namespace App\Http\Livewire;

use App\Models\PublicHealthEntity;
use App\Models\TypeWorkPermit;
use Livewire\Component;
use Livewire\WithPagination;
use App\Traits\OrderByTable;
use Illuminate\Support\Facades\DB;

class TypeWorkPermitController extends Component
{
    use WithPagination;
    use OrderByTable;
    public $name, $description, $support_document_required;
    public $search, $selected_id, $pageTitle, $componentName,  $count_reg;
    public $breadcrumb_show = true;

    private $pagination = 10;

    protected $paginationTheme = 'bootstrap';

    public function mount()
    {
        UserAuthPermission('Type_work_permit_index');
        $this->pageTitle = 'Listado';
        $this->componentName = 'Tipo de Permisos Laborales';
    }

    public function render()
    {
        if (strlen($this->search) > 0)
            $types_wp = TypeWorkPermit::where('name', 'like', '%' . $this->search. '%')->orderBy($this->sortBy, $this->sortDirection)->paginate($this->pagination);
        else
            $types_wp = TypeWorkPermit::orderBy($this->sortBy, $this->sortDirection)->paginate($this->pagination);

        $this->count_reg = $types_wp->total();
        return view('livewire.type_work_permit.component',compact('types_wp'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function openAdd()
    {
        $useractions = UserAuthPermissionActions('Type_work_permit_create');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $this->selected_id = 0;
        $this->resetUI();
        $this->emit('show-modal','Abrir Modal');
    }

    public function Store()
    {
        $useractions = UserAuthPermissionActions('Type_work_permit_create');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $rules = [
            'name' => 'required|min:2|unique:type_work_permits,name',
        ];

        $messages = [
            'name.required' => 'El nombre del tipo de permiso laboral es requerido.',
            'name.unique' => 'El nombre del tipo de permiso laboral ya existe.',
            'name.min' => 'El nombre del tipo de permiso laboral debe tener al menos 2 caracteres.',
        ];

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

        TypeWorkPermit::create([
            'name' => $this->name,
            'description' => $this->description,
            'support_document_required' => $this->support_document_required,
        ]);

        $this->emit('item-added', 'Se registró el tipo de permiso laboral correctamente.');
        $this->resetUI();
    }

    public function Edit(TypeWorkPermit $type_work_permit)
    {
        $useractions = UserAuthPermissionActions('Type_work_permit_update');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $this->selected_id = $type_work_permit->id;
        $this->name = $type_work_permit->name;
        $this->description = $type_work_permit->description;
        $this->support_document_required = $type_work_permit->support_document_required;

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

    public function Update()
    {
        $useractions = UserAuthPermissionActions('Type_work_permit_update');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $rules = [
            'name' => "required|min:2|unique:type_work_permits,name,$this->selected_id"
        ];

        $messages = [
            'name.required' => 'El nombre del tipo de permiso laboral es requerido.',
            'name.unique' => 'El nombre del tipo de permiso laboral ya existe.',
            'name.min' => 'El nombre del tipo de permiso laboral debe tener al menos 2 caracteres.',
        ];

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

        $type_work_permit = TypeWorkPermit::find($this->selected_id);
        $type_work_permit->name = $this->name;
        $type_work_permit->description = $this->description;
        $type_work_permit->support_document_required = $this->support_document_required;
        $type_work_permit->save();

        $this->emit('item-updated', 'Se actualizó el tipo de permiso laboral correctamente.');
        $this->resetUI();
    }

    protected $listeners = ['deleteRow' => 'Destroy'];

    public function Destroy($id)
    {
        $useractions = UserAuthPermissionActions('Type_work_permit_delete');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $type_work_permit_users = DB::table('work_permits')->where('type_work_permit_id', $id)->count();
        if ($type_work_permit_users > 0) {
            $this->emit('item-deleted', 'No se puede eliminar el tipo de permiso laboral porque tiene permisos laborales asociados a un empleado.');
            return;
        }


        TypeWorkPermit::find($id)->delete();
        $this->emit('item-deleted', 'Se eliminó el tipo de permiso laboral correctamente.');
    }

    public function resetUI()
    {
        $this->name = '';
        $this->description = '';
        $this->support_document_required = 0;
        $this->search = '';
        $this->selected_id = 0;
        $this->resetErrorBag();
    }
}
