<?php

namespace App\Http\Livewire;

use App\Models\Company;
use App\Models\TypeWorkPermit;
use App\Models\User;
use App\Models\WorkPermit;
use App\Traits\OrderByTable;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Livewire\WithFileUploads;
use Livewire\WithPagination;
use Illuminate\Support\Str as Str;

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

    public $user, $user_id, $company_id, $first_name, $last_name, $search, $count_reg, $selected_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 $breadcrumb_show = true;

    private $pagination = 10;

    protected $paginationTheme = 'bootstrap';

    public function updatingSearch(){
        $this->resetPage();
    }

    public function mount()
    {
        UserAuthPermission('Employee_work_permits_index');
        $user = User::find(auth()->user()->id);
        EmployeeOtherCompany($user->id); //Verifica que el empleado pertenezca a la empresa

        $this->user = $user;
        $this->user_id = $user->id;
        $this->first_name = $user->first_name;
        $this->last_name = $user->last_name;
        $company = Company::find(Auth::user()->CompanyInfo('id'));
        $this->company_id = $company->id;
        $this->pageTitle = 'Lista';
        $this->componentName = 'Permisos laborales';
    }

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

            $work_permits = WorkPermit::select('work_permits.*', 'type_work_permits.name as type_work_permit_name', 'type_work_permits.support_document_required')
                            ->where('user_id', $this->user_id)
                            ->join('type_work_permits', 'type_work_permits.id', '=', 'work_permits.type_work_permit_id')
                            ->where(function($query) {
                                $query->where('work_permits.register_code', 'like', '%' . $this->search . '%')
                                    ->orWhere('type_work_permits.name', 'like', '%' . $this->search . '%');
                            })
                            ->orderBy('work_permits.id', 'desc')
                            ->paginate($this->pagination);
        }
        else{
            $work_permits = WorkPermit::select('work_permits.*', 'type_work_permits.name as type_work_permit_name', 'type_work_permits.support_document_required')
                            ->where('user_id', $this->user_id)
                            ->join('type_work_permits', 'type_work_permits.id', '=', 'work_permits.type_work_permit_id')
                            ->orderBy('work_permits.id', 'desc')
                            ->paginate($this->pagination);
            }
        $type_work_permits = TypeWorkPermit::all();
        $this->count_reg = $work_permits->count();
        return view('livewire.employee.work-permits.component', compact('work_permits', 'type_work_permits'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function resetUI(){
        $this->search = '';
        $this->selected_id = '';
        $this->type_work_permit = '';
        $this->register_code = '';
        $this->solicitation_date = '';
        $this->start_date = '';
        $this->start_time = '';
        $this->end_date = '';
        $this->end_time = '';
        $this->details = '';
        $this->rejected_reason_support_document = '';
        $this->status_support_document = '';
        $this->reviewed_by = '';
        $this->rejected_reason = '';
        $this->support_document = '';
        $this->resetErrorBag();
    }

    public function openAddWorkPermit(){
        $useractions = UserAuthPermissionActions('Employee_work_permits_index');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $work_permits_user_pending_count = WorkPermit::where('user_id', $this->user_id)->where('status', '0')->count();
        if ($work_permits_user_pending_count > 0){
            $this->emit('item-error', 'Ya tiene un permiso laboral pendiente de revisión.');
            return false;
        }
        $this->selected_id = 0;
        $this->resetUI();
        $this->emit('show-modal','Abrir Modal');
    }

    public function Store(){
        $rules=[
            'type_work_permit' => 'required',
            'start_date' => 'required|date|after_or_equal:' . Carbon::now()->addDay(3)->format('Y-m-d').'|before_or_equal:'. Carbon::now()->addDay(30)->format('Y-m-d'),
            'start_time' => 'required',
            'end_date' => 'required|after_or_equal:start_date|',
            'end_time' => 'required',
        ];

        $messages=[
            'type_work_permit.required' => 'El campo tipo de permiso es obligatorio',
            'start_date.required' => 'El campo fecha de salida es obligatorio',
            'start_time.required' => 'El campo hora de salida es obligatorio',
            'start_date.after_or_equal' => 'La fecha de salida debe ser mayor a 3 días de la fecha actual',
            'start_date.before_or_equal' => 'La fecha de salida debe ser menor a 30 días de la fecha actual',
            'end_date.required' => 'El campo fecha de llegada es obligatorio',
            'end_date.after_or_equal' => 'La fecha de llegada debe ser mayor o igual a la fecha de salida',
            'end_time.required' => 'El campo hora de llegada es obligatorio',
        ];

        if ($this->start_date == $this->end_date){
            $rules['end_time'] = 'after:start_time';
            $messages['end_time.after'] = 'La hora de llegada debe ser mayor a la hora de salida';
        }

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

        $register_code = $this->user_id . '-' . Carbon::now()->format('YmdHis');

        WorkPermit::create([
            'user_id' => $this->user_id,
            'company_id' => $this->company_id,
            'type_work_permit_id' => $this->type_work_permit,
            'register_code' => $register_code,
            'solicitation_date' => Carbon::now()->format('Y-m-d' . ' ' . 'H:i:s'),
            'start_date' => $this->start_date.' '.$this->start_time. ':00',
            'end_date' => $this->end_date . ' ' . $this->end_time. ':00',
            'observations' => $this->observations,
        ]);

        foreach (AdminsCompany($this->company_id) as $admin) {
            $message = NotifyMessageCustom(
                $title = 'El Empleado '.$this->first_name.' '.$this->last_name.' ha solicitado un permiso laboral',
                $body = 'Se ha solicitado un permiso laboral para el empleado '.$this->first_name.' '.$this->last_name.', por favor ingrese a la plataforma para revisar.',
                $url = route('permisos-laborales-empleado', Auth::user()->id),
                $button_text = 'Ver Solicitud',
                $via_from = 'Employee',
                $user_to_id = $admin->user_id,
                $user_from_id = Auth::user()->id
            );
        }

        $this->emit('item-added','La solicitud se ha creado correctamente');
        $this->resetUI();
    }

    public function openViewRejectWorkPermit($id){
        $useractions = UserAuthPermissionActions('Employee_work_permits_index');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $work_permits = WorkPermit::find($id);
        $this->selected_id = $id;
        $this->rejected_reason = $work_permits->rejected_reason;

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

    public function openUploadSupportDocument($id){
        $useractions = UserAuthPermissionActions('Employee_work_permits_index');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $work_permits = WorkPermit::find($id);
        $this->selected_id = $id;
        $this->type_work_permit = $work_permits->type_work_permit_id;
        $this->status_support_document = $work_permits->status_support_document;
        $this->support_document_load = $work_permits->support_document;
        $this->rejected_reason_support_document = $work_permits->rejected_reason_support_document;

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

    public function uploadSupportDocument(){
        $rules=[
            'support_document' => 'required|mimes:pdf,jpg,jpeg,png',
        ];

        $messages=[
            'support_document.required' => 'El campo documento es obligatorio',
            'support_document.mimes' => 'El documento debe ser un archivo de tipo PDF, JPG, JPEG o PNG',
        ];

        $this->validate($rules, $messages);
        $id = $this->selected_id;
        $work_permits = WorkPermit::find($id);

        $type_work_permit_name = Str::slug(TypeWorkPermit::find($this->type_work_permit)->name);
        $support_document_file = $work_permits->support_document;

        if ($this->support_document)
        {

            $customFileName = $type_work_permit_name.'_'.$this->user_id.'_'.$id.'_'.Carbon::now()->format('YmdHis').'.'.$this->support_document->extension();
            $this->support_document->storeAs('public/users/'.$this->user_id.'/work_permits', $customFileName);
            $work_permits->support_document = $customFileName;
            $work_permits->save();

            if ($support_document_file != null){
                if(file_exists('storage/users/'.$this->user_id.'/work_permits/'. $support_document_file))//verificamos que la imagen exista físicamente
                {
                    unlink('storage/users/'.$this->user_id.'/work_permits/' . $support_document_file); //eliminamos la imagen
                }
            }

            $work_permits->Update(
                ['status_support_document' => '0',]
            );
            $this->status_support_document = '0';
        }

        $this->emit('hide-modal-support-document','El documento de soporte se ha subido correctamente');
        $this->resetUI();
    }
}
