<?php

namespace App\Http\Livewire;

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


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

    public $search, $company_id, $pageTitle, $componentName, $user_id, $selected_WP_id;
    public $type_work_permit, $register_code, $solicitation_date, $start_date, $start_time, $end_date, $end_time;
    public $observations, $status, $rejected_reason, $reviewed_by, $support_document, $support_document_load;
    public $status_support_document, $rejected_reason_support_document;
    public $status_work_permit, $status_support_work_permit, $work_permit_id;
    public $company_name, $company_plan_name, $company_plan_id;
    public $first_name, $last_name;

    public $breadcrumb_show;

    private $pagination = 10;

    protected $paginationTheme = 'bootstrap';

    protected $listeners = [
        'reload-list-work-permits' => 'searchList' // emit del componente WorkPermitDetailController para refrescar la lista de permisos laborales
    ];


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

        UserAuthPermission('Company_work_permit_view');
        $user = User::find($id);
        $this->user_id = $user->id;
        $this->first_name = $user->first_name;
        $this->last_name = $user->last_name;
        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 = 'Permisos Laborales';
        $this->componentName = 'Solicitudes';

        $this->breadcrumb_show = $breadcrumb_show;


        $this->sortBy= 'work_permits.created_at';

    }

    public function render()
    {
        $work_permits_users = $this->searchList();
        $this->count_reg = $work_permits_users->total();

        return view('livewire.company.employee.detail.work-permits.component',compact('work_permits_users'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function searchList(){
        if (strlen($this->search) > 0){
            $work_permits_users= User::role('Empleado')
            ->join('work_permits', 'users.id', '=', 'work_permits.user_id')
            ->join('company_user', 'users.id', '=', 'company_user.user_id')
            ->join('companies', 'company_user.company_id', '=', 'companies.id')
            ->join('type_work_permits', 'work_permits.type_work_permit_id', '=', 'type_work_permits.id')
            ->select(
                    'type_work_permits.name as type_work_permit_name', 'type_work_permits.support_document_required',
                    'work_permits.id as work_permit_id',
                    'work_permits.register_code', 'work_permits.solicitation_date', 'work_permits.start_date',
                    'work_permits.end_date', 'work_permits.observations', 'work_permits.status as status_work_permit',
                    'work_permits.support_document', 'work_permits.status_support_document'
                    )
            ->where('work_permits.company_id', Auth::user()->CompanyId())
            ->where('users.id', $this->user_id)
            ->where('companies.id', Auth::user()->CompanyId())
            ->where(function ($query) {
            $query->where('type_work_permits.name', 'like', '%' . $this->search . '%')
                    ->orWhere('work_permits.register_code', 'like', '%' . $this->search . '%');
            })
            ->where(function ($query) {
                if ($this->status_work_permit != null) {
                    $query->where('work_permits.status', $this->status_work_permit);
                }
            })
            ->where(function ($query) {
                if ($this->status_support_work_permit != null) {
                    if ($this->status_support_work_permit == 0) { // si el estado es 0, significa que esta en estado pendiente
                        $query->where('type_work_permits.support_document_required', '1'); // y que el tipo de permiso requiere documento de soporte
                    }
                    $query->where('work_permits.status_support_document', $this->status_support_work_permit);
                }
            })
            ->orderBy($this->sortBy, $this->sortDirection)->paginate($this->pagination);

        }else{
            $work_permits_users= User::role('Empleado')
            ->join('work_permits', 'users.id', '=', 'work_permits.user_id')
            ->join('company_user', 'users.id', '=', 'company_user.user_id')
            ->join('companies', 'company_user.company_id', '=', 'companies.id')
            ->join('type_work_permits', 'work_permits.type_work_permit_id', '=', 'type_work_permits.id')
            ->select(
                    'type_work_permits.name as type_work_permit_name', 'type_work_permits.support_document_required',
                    'work_permits.id as work_permit_id',
                    'work_permits.register_code', 'work_permits.solicitation_date', 'work_permits.start_date',
                    'work_permits.end_date', 'work_permits.observations', 'work_permits.status as status_work_permit',
                    'work_permits.support_document', 'work_permits.status_support_document'
                    )
            ->where('work_permits.company_id', Auth::user()->CompanyId())
            ->where('users.id', $this->user_id)
            ->where('companies.id', Auth::user()->CompanyId())
            ->where(function ($query) {
                if ($this->status_work_permit != null) {
                    $query->where('work_permits.status', $this->status_work_permit);
                }
            })
            ->where(function ($query) {
                if ($this->status_support_work_permit != null) {
                    if ($this->status_support_work_permit == 0) { // si el estado es 0, significa que esta en estado pendiente
                        $query->where('type_work_permits.support_document_required', '1'); // y que el tipo de permiso requiere documento de soporte
                    }
                    $query->where('work_permits.status_support_document', $this->status_support_work_permit);
                }
            })
            ->orderBy($this->sortBy, $this->sortDirection)->paginate($this->pagination);
        }

        return $work_permits_users;
    }
    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 openWP($id)
    {
        $this->work_permit_id = $id;

        $this->emit('OpenWorkPermitModal', $this->work_permit_id);
    }



}
