<?php

namespace App\Http\Livewire;

use App\Models\Company;
use App\Models\JobPosition;
use App\Traits\OrderByTable;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Livewire\WithFileUploads;
use Livewire\WithPagination;

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

    public $search, $company_id, $pageTitle, $componentName, $count_reg;
    public $selected_id, $name, $main_functions, $special_functions, $qualities, $base_salary;
    public $breadcrumb_show = true;

    private $pagination = 10;

    protected $paginationTheme = 'bootstrap';

    public function mount()
    {
        UserAuthPermission('Company_job_positions_index');
        $this->company_id = Company::find(Auth::user()->CompanyId())->id;
        $this->pageTitle = 'Listado';
        $this->componentName = 'Puestos de trabajo';
        $this->company_name = Company::find($this->company_id )->name;
        $this->company_plan_name = Company::find($this->company_id )->plan->name;
        $this->emit('noOpen1');
    }

    public function render()
    {
        if (strlen($this->search) > 0)
            {

                $job_positions = JobPosition::where('name', 'like', '%' . $this->search . '%')
                            ->where('company_id', $this->company_id)
                            ->orderBy($this->sortBy, $this->sortDirection)
                            ->paginate($this->pagination);
            }
            else
            {
                $job_positions = JobPosition::where('company_id', $this->company_id)
                                ->orderBy($this->sortBy, $this->sortDirection)
                                ->paginate($this->pagination);
            }

        $this->count_reg = $job_positions->total();

        return view('livewire.company.job_positions.component',compact('job_positions'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function resetUI()
    {
        $this->search = '';
        $this->name = '';
        $this->main_functions = '';
        $this->special_functions = '';
        $this->qualities = '';
        $this->base_salary = '';
        $this->resetValidation();
        $this->resetPage();
    }

    public function openAdd()
    {
        $useractions = UserAuthPermissionActions('Company_job_positions_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_job_positions_create');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }

        $rules = [
            'name' => 'required|string|max:99|unique:job_positions,name,NULL,id,company_id,'.$this->company_id,
            'main_functions' => 'required',
            'special_functions' => 'required',
            'qualities' => 'required',
            'base_salary' => 'required|max:13|min:0|not_in:0|regex:/^\d{1,3}(?:\,\d\d\d)*(?:.\d{1,2})?$/',
        ];

        $messages = [
            'name.required' => 'El nombre del puesto de trabajo es requerido',
            'name.string' => 'El nombre del puesto de trabajo debe ser una cadena de texto',
            'name.max' => 'El nombre del puesto de trabajo no debe exceder los 99 caracteres',
            'name.unique' => 'El nombre del puesto de trabajo ya existe',
            'main_functions.required' => 'Las funciones principales son requeridas',
            'special_functions.required' => 'Las funciones especiales son requeridas',
            'qualities.required' => 'Las cualidades son requeridas',
            'base_salary.required' => 'El salario base es requerido',
            'base_salary.max' => 'El salario base no debe exceder los 8 dígitos',
            'base_salary.min' => 'El salario base no debe ser menor a 0',
            'base_salary.not_in' => 'El salario base no debe ser 0',
            'base_salary.regex' => 'El salario base debe tener el formato correcto',
        ];

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

        JobPosition::create([
            'company_id' => $this->company_id,
            'name' => $this->name,
            'main_functions' => $this->main_functions,
            'special_functions' => $this->special_functions,
            'qualities' => $this->qualities,
            'base_salary' => (float) str_replace(',', '', $this->base_salary), // quitar punto y coma de data-currency en el input
        ]);

        $this->resetUI();
        $this->emit('item-added', 'Puesto de trabajo registrado correctamente');

    }

    public function Edit(JobPosition $job_position)
    {
        $useractions = UserAuthPermissionActions('Company_job_positions_update');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        if (JobPositionNotCompany($job_position->id, $this->company_id, true) == NULL)
        {
            $this->emit('item-error', JobPositionNotCompany($job_position->id, $this->company_id,  true)[1]);
            return false;
        }
        $this->selected_id = $job_position->id;
        $this->name = $job_position->name;
        $this->main_functions = $job_position->main_functions;
        $this->special_functions = $job_position->special_functions;
        $this->qualities = $job_position->qualities;
        $this->base_salary = number_format($job_position->base_salary, 2, '.', ',');

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

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

        if (JobPositionNotCompany($this->selected_id, $this->company_id, true) == NULL)
        {
            $this->emit('item-error', JobPositionNotCompany($this->selected_id, $this->company_id,  true)[1]);
            return false;
        }
        debug($this->base_salary);
        $this->base_salary = (float) str_replace(',', '', $this->base_salary); // quitar punto y coma de data-currency en el input
        debug($this->base_salary);
        $rules = [
            'name' => 'required|string|max:99|unique:job_positions,name,'.$this->selected_id.',id,company_id,'.$this->company_id,
            'main_functions' => 'required',
            'special_functions' => 'required',
            'qualities' => 'required',
            'base_salary' => 'required|numeric|max:99999999',
        ];

        $messages = [
            'name.required' => 'El nombre del puesto de trabajo es requerido',
            'name.string' => 'El nombre del puesto de trabajo debe ser una cadena de texto',
            'name.max' => 'El nombre del puesto de trabajo no debe exceder los 99 caracteres',
            'name.unique' => 'El nombre del puesto de trabajo ya existe',
            'main_functions.required' => 'Las funciones principales son requeridas',
            'special_functions.required' => 'Las funciones especiales son requeridas',
            'qualities.required' => 'Las cualidades son requeridas',
            'base_salary.required' => 'El salario base es requerido',
            'base_salary.numeric' => 'El salario base debe ser un número',
            'base_salary.max' => 'El salario base no debe exceder los 99.999.999',
        ];

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

        $job_position = JobPosition::find($this->selected_id);
        $job_position->Update([
            'name' => $this->name,
            'main_functions' => $this->main_functions,
            'special_functions' => $this->special_functions,
            'qualities' => $this->qualities,
            'base_salary' => $this->base_salary,
        ]);

        $this->resetUI();
        $this->emit('item-updated', 'Puesto de trabajo actualizado correctamente');
    }
    protected $listeners = [
        'deleteRow' => 'Destroy',
        'resetUI' => 'resetUI'
    ];

    public function Destroy(JobPosition $job_position)
    {
        $useractions = UserAuthPermissionActions('Company_job_positions_delete');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        if (JobPositionNotCompany($this->selected_id, $this->company_id, true) == NULL)
        {
            $this->emit('item-error', JobPositionNotCompany($job_position->id, $this->company_id,  true)[1]);
            return false;
        }
        if ($job_position)
        {
            $job_position->delete();
            $this->resetUI();
            $this->emit('item-deleted', 'Puesto de trabajo eliminado correctamente');
        }
    }

}
