<?php

namespace App\Http\Livewire;

use App\Models\Company;
use App\Models\DocumentType;
use App\Models\TypePsychotechnicsTest;
use Livewire\Component;
use Livewire\WithPagination;
use App\Traits\OrderByTable;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

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

    private $pagination = 10;

    protected $paginationTheme = 'bootstrap';

    public function mount()
    {
        UserAuthPermission('Company_document_type_index');
        $this->company_id = Company::find(Auth::user()->CompanyId())->id;
        $this->componentName = 'Tipos de documentos';
        $this->pageTitle = 'Listado';
        $this->componentName = 'Tipo de documento';
        $this->sortBy('name');
    }

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

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

    public function openAdd()
    {
        $useractions = UserAuthPermissionActions('Company_document_type_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('Company_document_type_create');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $rules = [
            'name' => 'required|min:2|unique:document_types,name,NULL,id,company_id,' . $this->company_id,
        ];

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

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

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

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

    public function Edit(DocumentType $document_type)
    {
        $useractions = UserAuthPermissionActions('Company_document_type_update');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        if (ItemNotCompany($document_type->id, $this->company_id, 'document_types', true) == NULL){
            $this->emit('item-error', ItemNotCompany($document_type->id, $this->company_id, 'document_types', true)[1]);
            return false;
        }

        $this->selected_id = $document_type->id;
        $this->name = $document_type->name;
        $this->description = $document_type->description;

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

    public function Update()
    {
        $useractions = UserAuthPermissionActions('Company_document_type_update');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        if (ItemNotCompany($this->selected_id, $this->company_id, 'document_types', true) == NULL){
            $this->emit('item-error', ItemNotCompany($this->selected_id, $this->company_id, 'document_types', true)[1]);
            return false;
        }

        $rules = [
            'name' => "required|min:2|unique:document_types,name,{$this->selected_id},id,company_id,{$this->company_id}",
        ];

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

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

        $document_type = DocumentType::find($this->selected_id);

        $document_type->name = $this->name;
        $document_type->description = $this->description;

        $document_type->save();

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

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

    public function Destroy($id)
    {
        $useractions = UserAuthPermissionActions('Company_document_type_delete');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }

        if (ItemNotCompany($this->selected_id, $this->company_id, 'document_types', true) == NULL){
            $this->emit('item-error', ItemNotCompany($this->selected_id, $this->company_id, 'document_types', true)[1]);
            return false;
        }

        $userDocumentType = DB::table('user_documents')->where('document_type_id', $id)->count();
        if ($userDocumentType > 0) {
            $this->emit('item-deleted', 'No se puede eliminar el tipo de documento porque está asociado a un usuario.');
            return;
        }

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

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