<?php

namespace App\Http\Livewire;

use App\Models\Company;
use App\Models\TypePsychotechnicsTest;
use App\Models\User;
use App\Models\UserPsychotechnicsTest;
use Illuminate\Support\Facades\Auth;
use Livewire\WithPagination;
use Livewire\WithFileUploads;
use Livewire\Component;
use App\Traits\OrderByTable;
use Illuminate\Support\Str as Str;

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

    public $search, $company_id, $pageTitle, $componentName, $user_id, $selected_PST_id;
    public $selectedCompany, $type_psychotechnics_test_id, $type_psychotechnics_test_name, $observations,$document_upload, $document_upload_view;
    public $company_name, $company_plan_name, $company_plan_id;
    public $first_name, $last_name;

    public $breadcrumb_show;

    private $pagination = 10;

    protected $paginationTheme = 'bootstrap';

    public function mount($id=null, $breadcrumb_show=true)
    {
        if ($id == null) {
            return redirect()->route('dashboard');
        }

        UserAuthPermission('Company_employee_psychotechnics_test_index');
        $user = User::find($id);
        $this->user_id = $user->id;
        if ($user->status == 'INACTIVO'){
            return redirect()->route('dashboard');
        }
        EmployeeOtherCompany($this->user_id); //Verifica que el empleado pertenezca a la empresa
        $this->company_id = Company::find(Auth::user()->CompanyId())->id;
        $this->pageTitle = 'Pruebas Psicotécnicas';
        $this->componentName = 'Pruebas Psicotécnicas';

        $this->breadcrumb_show = $breadcrumb_show;

    }

    public function render()
    {
        if (strlen($this->search) > 0)
            $upts = UserPsychotechnicsTest::join('type_psychotechnics_tests', 'user_psychotechnics_tests.type_psychotechnics_test_id', '=', 'type_psychotechnics_tests.id')
                                            ->where('type_psychotechnics_tests.company_id', $this->company_id)
                                            ->where('user_psychotechnics_tests.user_id', $this->user_id)
                                            ->where('type_psychotechnics_tests.name', 'like', '%' . $this->search . '%')
                                            ->select('user_psychotechnics_tests.*', 'type_psychotechnics_tests.name as name')
                                            ->orderBy($this->sortBy, $this->sortDirection)
                                            ->paginate($this->pagination);
        else
            $upts = UserPsychotechnicsTest::join('type_psychotechnics_tests', 'user_psychotechnics_tests.type_psychotechnics_test_id', '=', 'type_psychotechnics_tests.id')
                                            ->where('type_psychotechnics_tests.company_id', $this->company_id)
                                            ->where('user_psychotechnics_tests.user_id', $this->user_id)
                                            ->select('user_psychotechnics_tests.*', 'type_psychotechnics_tests.name as name')
                                            ->orderBy($this->sortBy, $this->sortDirection)
                                            ->paginate($this->pagination);

        $type_psychotechnics_tests = TypePsychotechnicsTest::where('company_id', $this->company_id)->orderBy('name', 'asc')->get();
        return view('livewire.company.employee.detail.psychotechnics-test.component',compact('upts','type_psychotechnics_tests'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function resetUI()
    {
        $this->selected_PST_id = 0;
        $this->type_psychotechnics_test_id = 0;
        $this->observations = '';
        $this->document_upload = '';
        $this->document_upload_view = '';
        $this->resetValidation();
    }

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

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

        $rules = [
            'type_psychotechnics_test_id' => 'required|unique:user_psychotechnics_tests,type_psychotechnics_test_id,NULL,id,user_id,'.$this->user_id.',company_id,'.$this->company_id,
            'observations' => 'required',
            'document_upload' => 'required|file|mimes:pdf,jpg,jpeg,png|max:2048',
        ];

        $messages = [
            'type_psychotechnics_test_id.required' => 'El campo Tipo de Prueba Psicotécnica es obligatorio.',
            'type_psychotechnics_test_id.unique' => 'El Tipo de Prueba Psicotécnica ya existe para este usuario en la empresa.',
            'observations.required' => 'El campo Observaciones es obligatorio.',
            'document_upload.required' => 'El campo Documento es obligatorio.',
            'document_upload.file' => 'El campo Documento debe ser un archivo.',
            'document_upload.mimes' => 'El campo Documento debe ser un archivo de tipo: pdf, jpg, jpeg, png.',
            'document_upload.max' => 'El campo Documento debe tener un tamaño máximo de 2MB.',
        ];

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

        $user_psychotechnics_tests = UserPsychotechnicsTest::create([
            'user_id' => $this->user_id,
            'company_id' => $this->company_id,
            'type_psychotechnics_test_id' => $this->type_psychotechnics_test_id,
            'observations' => $this->observations,
        ]);
        $type_psychotechnics_test_name = Str::slug(TypePsychotechnicsTest::find($this->type_psychotechnics_test_id)->name);
        if ($this->document_upload)
        {
            $customFileName = $type_psychotechnics_test_name.'_'.$this->company_id.'.'.$this->document_upload->extension();
            $this->document_upload->storeAs('public/users/'.$this->user_id.'/psychotechnics_test_supports', $customFileName);
            $user_psychotechnics_tests->document_upload = $customFileName;
            $user_psychotechnics_tests->save();
        }
        $this->resetUI();
        $this->emit('item-added-PST', 'Prueba Psicotécnica agregada correctamente.');
    }

    public function Edit(UserPsychotechnicsTest $user_psychotechnics_tests)
    {
        if (EmployeeOtherCompany($this->user_id, true)[0] == NULL)
        {
            $this->emit('item-error', EmployeeOtherCompany($this->user_id, true)[1]);
            return false;
        }
        $useractions = UserAuthPermissionActions('Company_employee_psychotechnics_test_update');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $this->selected_PST_id = $user_psychotechnics_tests->id;
        $this->type_psychotechnics_test_id = $user_psychotechnics_tests->type_psychotechnics_test_id;
        $this->observations = $user_psychotechnics_tests->observations;
        $this->document_upload_view = $user_psychotechnics_tests->document_upload;
        $this->emit('show-modal-PST', 'Abrir Modal');
    }


    public function ViewPST(UserPsychotechnicsTest $user_psychotechnics_tests){
        if (EmployeeOtherCompany($this->user_id, true)[0] == NULL)
        {
            $this->emit('item-error', EmployeeOtherCompany($this->user_sel_id, true)[1]);
            return false;
        }
        $useractions = UserAuthPermissionActions('Company_employee_psychotechnics_test_index');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $this->selected_PST_id = $user_psychotechnics_tests->id;
        $this->type_psychotechnics_test_name = $user_psychotechnics_tests->type_psychotechnics_test_name;
        $this->observations = $user_psychotechnics_tests->observations;
        $this->document_upload_view = $user_psychotechnics_tests->document_upload;
        $this->emit('show-modal-PST', 'Abrir Modal');
    }
    protected $listeners = ['deleteRowPST' => 'DestroyPST'];

    public function DestroyPST(UserPsychotechnicsTest $user_psychotechnics_tests)
    {
        if (EmployeeOtherCompany($this->user_id, true)[0] == NULL)
        {
            $this->emit('item-error-PST', EmployeeOtherCompany($this->user_id, true)[1]);
            return false;
        }
        $supportDocument = $user_psychotechnics_tests->document_upload;

        if ($supportDocument != null)//si la consulta devuelve el nombre del documento
        {
            if(file_exists('storage/users/'.$this->user_id.'/psychotechnics_test_supports/'. $supportDocument))//verificamos que el archivo exista fisicamente
            {
                unlink('storage/users/'.$this->user_id.'/psychotechnics_test_supports/' . $supportDocument); //eliminamos el archivo
            }
        }

        $user_psychotechnics_tests->delete();
        $this->emit('item-deleted-PST', 'Se eliminó la prueba psicotécnica correctamente.');
    }

}
