<?php

namespace App\Http\Livewire;

use App\Models\Company;
use App\Models\HistoryContractsUser;
use App\Models\UserContractEvent;
use App\Models\JobPosition;
use App\Models\Plan;
use App\Models\User;
use App\Traits\OrderByTable;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
use Livewire\WithFileUploads;
use Livewire\WithPagination;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Facades\Excel;
use Maatwebsite\Excel\Validators\ValidationException;
use Luecano\NumeroALetras\NumeroALetras;

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

    public $componentName, $pageTitle, $search, $count_reg;
    public $company_id,  $company_name, $company_plan_name;
    public $first_name, $last_name, $role_name, $selected_id;
    public $event_id, $name, $date, $description, $created_by, $updated_by, $days_before_to_notify;
    public $contract_user_id, $contract_id, $contract_name, $contract_type, $contract_sub_type, $contract_description, $contract_start_date, $contract_end_date, $contract_created_at;

    private $pagination = 25;

    protected $paginationTheme = 'bootstrap';

    public $breadcrumb_show = true;

    public function mount($id=null){
        if ($id == null) {
            return redirect()->route('dashboard');
        }
        UserAuthPermission('Company_contracts_users_events_index');
        $contract_user = HistoryContractsUser::find($id);

        if ($contract_user != NULL) {
            $this->history_contract_id = $contract_user->id;
            $contract_id = $contract_user->contract_id;

            $this->sel_contract_content = $contract_user->content_contract;
            $this->selected_user_id= $contract_user->user_id;
            $user = User::find($this->selected_user_id);
            if ($user->status == 'INACTIVO'){
                return redirect()->route('contratos-empleados')->with('error', 'El usuario se encuentra Inactivo');
            }

            $this->selected_contract_id = $id;
            $this->user_id = $user->id;
            $this->first_name = $user->first_name;
            $this->last_name = $user->last_name;
            $this->role_name = $user->roles->first()->name;

            $this->pageTitle = 'Contrato';
            $this->componentName = 'Calendario de Eventos';

            $info_contract_user = HistoryContractsUser::select('contracts.*', 'history_contracts_users.id as id_contract_user',
                'history_contracts_users.signature_company', 'history_contracts_users.signature_employee',
                'history_contracts_users.status as status_contract', 'history_contracts_users.active_signature_employee',
                'history_contracts_users.start_date', 'history_contracts_users.end_date', 'history_contracts_users.created_at',
                'history_contracts_users.updated_at', 'history_contracts_users.content_contract',
                'history_contracts_users.reason_termination', 'history_contracts_users.user_termination', 'history_contracts_users.date_termination')
                ->join('contracts', 'contracts.id', '=', 'history_contracts_users.contract_id')
                ->join('users', 'users.id', '=', 'history_contracts_users.user_id')
                ->join('companies', 'companies.id', '=' , 'history_contracts_users.company_id')
                ->where('history_contracts_users.id', $id)
                ->first();
            $this->contract_user_id = $id;
            $this->contract_name = $info_contract_user->name;
            $this->contract_type = $info_contract_user->type;
            $this->contract_sub_type = $info_contract_user->sub_type;
            $this->contract_description = $info_contract_user->description;
            $this->contract_start_date = $info_contract_user->start_date;
            $this->contract_end_date = $info_contract_user->end_date;
            $this->contract_created_at = $info_contract_user->created_at;

            $company = Company::find(Auth::user()->CompanyId());
            $this->company_id = $company->id;

            $this->company_name = $company->name;
            $this->company_plan_name = $company->plan->name;
            $this->company_plan_id = $company->plan->id;

        }


    }

    public function resetUI(){
        $this->selected_id = 0;
        $this->search = '';
        $this->event_id = '';
        $this->name = '';
        $this->description = '';
        $this->date = '';
        $days_before_to_notify = '';
        $this->created_by = '';
        $this->updated_by = '';
        $this->resetValidation();
        $this->resetPage();
    }

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

            $contract_user_events = UserContractEvent::where('history_contract_id', $this->history_contract_id)
                ->where('name', 'like', '%' . $this->search . '%')
                ->orWhere('description', 'like', '%' . $this->search . '%')
                ->orderBy($this->sortBy, $this->sortDirection)
                ->paginate($this->pagination);
        }
        else{
            $contract_user_events = UserContractEvent::where('history_contract_id', $this->history_contract_id)
            ->orderBy($this->sortBy, $this->sortDirection)
                ->paginate($this->pagination);
        }

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

        return view('livewire.company.contracts.history.events.component', [
            'contract_user_events' => $contract_user_events
        ])
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

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

        $this->emit('show-modal', 'addEvent');
        $this->resetSearch();
    }

    public function resetSearch()
    {
        $this->query = '';
        $this->annexes = [];
        $this->highlightIndex = 0;
    }

    public function Store(){
        $useractions = UserAuthPermissionActions('Company_contracts_users_events_create');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $rules = [
            'name' => 'required|min:3',
            'date' => 'required|date|after:' . Carbon::now()->addDays(3)->toDateString()
        ];
        $messages = [
            'name.required' => 'El nombre del evento es requerido',
            'name.min' => 'El nombre del evento debe tener al menos 3 caracteres',
            'date.required' => 'La fecha del evento es requerida',
            'date.date' => 'La fecha del evento no es valida',
            'date.after' => 'La fecha del evento debe ser mayor a 3 dias a partir de hoy'
        ];

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

        $event = UserContractEvent::create([
            'history_contract_id' => $this->history_contract_id,
            'user_id' => $this->user_id,
            'company_id' => $this->company_id,
            'contract_id' => $this->selected_contract_id,
            'name' => $this->name,
            'description' => $this->description,
            'date' => $this->date,
            'days_before_to_notify' => $this->days_before_to_notify,
            'created_by' => Auth::user()->id,
            'updated_by' => Auth::user()->id
        ]);

        $this->resetUI();
        $this->emit('item-added', 'Evento registrado con exito');
    }

    public function Edit(UserContractEvent $event){
        $useractions = UserAuthPermissionActions('Company_contracts_users_events_update');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $this->selected_id = $event->id;
        $this->name = $event->name;
        $this->description = $event->description;
        $this->date = $event->date;
        $this->days_before_to_notify = $event->days_before_to_notify;
        $this->created_by = $event->created_by;
        $this->updated_by = $event->updated_by;

        $this->emit('show-modal', 'editEvent');
    }

    public function Update()
    {
        $useractions = UserAuthPermissionActions('Company_contracts_users_events_update');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $rules = [
            'name' => 'required|min:3',
            'date' => 'required|date|after:' . Carbon::now()->addDays(3)->toDateString()
        ];
        $messages = [
            'name.required' => 'El nombre del evento es requerido',
            'name.min' => 'El nombre del evento debe tener al menos 3 caracteres',
            'date.required' => 'La fecha del evento es requerida',
            'date.date' => 'La fecha del evento no es valida',
            'date.after' => 'La fecha del evento debe ser mayor a 3 dias a partir de hoy'
        ];

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

        $event = UserContractEvent::find($this->selected_id);

        $event->update([
            'name' => $this->name,
            'description' => $this->description,
            'date' => $this->date,
            'days_before_to_notify' => $this->days_before_to_notify,
            'updated_by' => Auth::user()->id
        ]);

        $this->resetUI();
        $this->emit('item-updated', 'Evento actualizado con exito');
    }

    protected $listeners = ['deleteRow' => 'Destroy'];

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

        $event->delete();
        $this->resetUI();
        $this->emit('item-deleted', 'Evento eliminado con exito');
    }

}
