<?php

namespace App\Http\Livewire;

use App\Models\Company;
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_TypePsychotechnicsTestController 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_type_psychotechnics_test_index');
        $this->company_id = Company::find(Auth::user()->CompanyId())->id;
        $this->componentName = 'Tipos de pruebas de psicotécnicas';
        $this->pageTitle = 'Listado';
        $this->componentName = 'Tipo de pruebas psico-técnicas';
    }

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

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

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

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

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

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

        $this->emit('item-added', 'Se registró la prueba psico-técnica satisfactoriamente');
        $this->resetUI();
    }

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

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

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

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

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

        $messages = [
            'name.required' => 'El nombre de la prueba es requerido',
            'name.unique' => 'El nombre de la prueba ya existe',
            'name.min' => 'El nombre de la prueba debe tener mínimo 2 caracteres'
        ];

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

        $tptt = TypePsychotechnicsTest::find($this->selected_id);

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

        $tptt->save();

        $this->emit('item-updated', 'Se actualizó la prueba con éxito');
        $this->resetUI();
    }

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

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

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

        $userPyscoTest = DB::table('user_psychotechnics_tests')->where('type_psychotechnics_test_id', $id)->count();
        if ($userPyscoTest > 0) {
            $this->emit('item-deleted', 'No se puede eliminar la prueba porque está asociada a un usuario');
            return;
        }

        TypePsychotechnicsTest::find($id)->delete();
        $this->emit('item-deleted', 'Se eliminó la prueba con éxito');
    }

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