<?php

namespace App\Http\Livewire;

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

class Company_WorkPermitsController 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 $status_work_permit, $status_support_work_permit, $work_permit_id, $id_work_permit;
    public $breadcrumb_show = true;

    private $pagination = 10;

    protected $paginationTheme = 'bootstrap';

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

    public function mount()
    {
        UserAuthPermission('Company_work_permit_index');
        $this->company_id = Company::find(Auth::user()->CompanyId())->id;
        $this->pageTitle = 'Listado';
        $this->componentName = 'Permisos laborales';
        $this->company_name = Company::find($this->company_id )->name;
        $this->company_plan_name = Company::find($this->company_id )->plan->name;

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

    public function render()
    {

        $users = $this->searchList();
        $this->count_reg = $users->total();

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

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

                $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(
                                    'users.*', 'company_user.job_position_id',
                                    '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('companies.id', Auth::user()->CompanyId())
                            ->where(function ($query) {
                            $query->where('first_name', 'like', '%' . $this->search . '%')
                                    ->orWhere('last_name', 'like', '%' . $this->search . '%')
                                    ->orWhere('document', 'like', '%' . $this->search . '%')
                                    ->orWhere('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
        {
            $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(
                                    'users.*', 'company_user.job_position_id',
                                    '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('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 $users;

    }

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


    public function openWP($id)
    {
        $this->work_permit_id = $id;

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

    public function jobPositionName($id)
    {
        $jobPosition = DB::table('job_positions')
            ->where('id', $id)
            ->get()->first();
        return $jobPosition->name;
    }

}
