<?php

namespace App\Http\Livewire;

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


class Company_ContractsUsersHistoryController extends Component
{
    use WithPagination;
    use OrderByTable;

    public $search, $company_id, $selected_user_id, $selected_contract_id, $pageTitle, $componentName, $user_id, $status_contract, $type_contract, $sub_type_contract;
    public $selectedCompany, $start_date, $end_date;
    public $sel_contract_name, $sel_contract_type, $sel_contract_sub_type, $sel_contract_description, $sel_contract_content;
    public $company_name, $company_plan_name, $company_plan_id, $annexes, $annex_name, $annex_content;
    public $first_name, $last_name, $document, $phone, $email, $status, $password, $image, $selected_id, $fileLoaded, $status_employee, $role_name;
    public $title_position, $salary, $payment_method, $start_date_work, $end_date_work, $place_hired, $place_work, $work_day, $eps_id, $expiration_contract, $contract_modality;
    public $ref_reason_termination, $reason_termination, $date_termination, $user_termination;
    public $breadcrumb_show = true;

    private $pagination = 10;

    protected $paginationTheme = 'bootstrap';

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

    public function mount($id=null)
    {
        if ($id == null) {
            return redirect()->route('contratos-usuarios');
        }
        UserAuthPermission('Company_contracts_users_history');
        $user = User::find($id);
        $this->user_id = $user->id;
        $this->first_name = $user->first_name;
        $this->last_name = $user->last_name;
        $this->status_employee = $user->status;
        $this->role_name = $user->roles->first()->name;
        $this->type_contract = '';
        $this->sub_type_contract = '';
        $this->company_id = Company::find(Auth::user()->CompanyId())->id;
        $this->pageTitle = 'Empleado';
        $this->componentName = 'Contrato';
        $this->company_name = Company::find($this->company_id )->name;
        $this->company_plan_name = Company::find($this->company_id )->plan->name;
        $this->company_plan_id = Company::find($this->company_id )->plan->id;
        $this->annexes = AnnexOther::all();
        $this->date_termination = date('Y-m-d');
    }

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

            $contracts_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.created_by',
                            'history_contracts_users.ref_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(function($query){
                    $query->where('contracts.name', 'like', '%' . $this->search . '%')
                        ->orWhere('contracts.description', 'like', '%' . $this->search . '%');
                    })
                    ->where(function ($query) {
                        if ($this->type_contract != null) {
                            $query->where('contracts.type', $this->type_contract);
                        }
                    })
                    ->where(function ($query) {
                        if ($this->sub_type_contract != null) {
                            $query->where('contracts.sub_type', $this->sub_type_contract);
                        }
                    })
                ->where('history_contracts_users.company_id', $this->company_id)
                ->where('history_contracts_users.user_id', $this->user_id)
                ->orderBy('history_contracts_users.id', 'desc')
                ->paginate($this->pagination);
        }
        else{
            $contracts_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.created_by',
                                'history_contracts_users.ref_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.company_id', $this->company_id)
                ->where('history_contracts_users.user_id', $this->user_id)
                ->where(function ($query) {
                    if ($this->type_contract != null) {
                        $query->where('contracts.type', $this->type_contract);
                    }
                })
                ->where(function ($query) {
                    if ($this->sub_type_contract != null) {
                        $query->where('contracts.sub_type', $this->sub_type_contract);
                    }
                })
                ->orderBy('history_contracts_users.id', 'desc')
                ->paginate($this->pagination);
            }
        $this->count_reg = $contracts_user->count();
        return view('livewire.company.contracts.history.component',compact('contracts_user'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function resetUI()
    {
        $this->first_name = '';
        $this->last_name = '';
        $this->document = '';
        $this->phone = '';
        $this->email = '';
        $this->password = '';
        $this->image = '';
        $this->search = '';
        $this->status ='';
        $this->selected_user_id = 0;
        $this->selected_contract_id = 0;
        $this->ref_reason_termination = '';
        $this->reason_termination = '';
        $this->resetValidation();
        $this->resetPage();
    }



    public function ActiveSignatureEmployee($contract_id_user)
    {
        UserAuthPermission('Company_contracts_active_employee_signature');
        $contract_user = HistoryContractsUser::find($contract_id_user);
        if(ContractUserOtherCompany($contract_user->id, $this->company_id, true)[0] == NULL){
            $this->emit('item-error', ContractUserOtherCompany($contract_user->id, $this->company_id, true)[1]);
            return false;
        }
        if ($contract_user->active_signature_employee == 0) {
            $contract_user->active_signature_employee = 1;
            $contract_user->save();

            $message = NotifyMessageCustom(
                $title = 'Tienes un Contrato disponible para firmar',
                $body = 'Tienes un Contrato disponible para firmar en la plataforma.',
                $url = route('empleado-contrato-firmar', $contract_user->id),
                $button_text = 'Ver Contrato',
                $via_from = 'Company',
                $user_to_id = $contract_user->user_id,
                $user_from_id = Auth::user()->id
            );
        }
    }

    public function StatusApproveContract($contract_id_user)
    {
        $contract_user = HistoryContractsUser::find($contract_id_user);
        if ($contract_user != NULL) {

            $company_id= $contract_user->company_id;
            //$company_signature = Company::find($company_id )->signature;
            UserAuthPermission('Company_contracts_users_status_approve');

            if (EmployeeOtherCompany($this->user_id, true)[0] == NULL)
            {
                $this->emit('item-error', EmployeeOtherCompany($this->user_id, true)[1]);
                return false;
            }
            if(ContractUserOtherCompany($contract_user->id, $this->company_id, true)[0] == NULL){
                $this->emit('item-error', ContractUserOtherCompany($contract_user->id, $this->company_id, true)[1]);
                return false;
            }
            if ($contract_user->signature_employee == NULL) {
                $this->emit('item-error', 'El contrato no tiene firma del empleado');
                return false;
            }
            if ($contract_user->status == "1") {
                $this->emit('item-error', 'El contrato ya fue aprobado');
                return false;
            }
            if ($contract_user->signature_company == NULL) {
                $this->emit('item-error', 'La empresa no tiene una firma de representante legal registrada');
                return false;
            }
            $contract_user->status = '1';
            $contract_user->save();
            $this->emit('item-updated', 'El contrato fue aprobado correctamente');
        }
        else {
            $this->emit('item-error', 'Contrato no encontrado');
        }
    }

    protected $listeners = ['TerminationContract'];



    public function OpenAddAnnexOthers($contract_id_user)
    {
        $contract_user = HistoryContractsUser::find($contract_id_user);
        if(ContractUserOtherCompany($contract_user->id, $this->company_id, true)[0] == NULL){
            $this->emit('item-error', ContractUserOtherCompany($contract_user->id, $this->company_id, true)[1]);
            return false;
        }
        $this->selected_contract_id = $contract_user->id;
        $this->resetUI();
        $this->emit('show-modal','Abrir Modal');
    }

    public function OpenTerminateContract($contract_id_user){
        $contract_user = HistoryContractsUser::find($contract_id_user);
        if(ContractUserOtherCompany($contract_user->id, $this->company_id, true)[0] == NULL){
            $this->emit('item-error', ContractUserOtherCompany($contract_user->id, $this->company_id, true)[1]);
            return false;
        }
        $this->selected_contract_id = $contract_user->id;
        $this->emit('show-modal-terminate','Abrir Modal');
    }

    public function TerminationContract()
    {
        $contract_user = HistoryContractsUser::find($this->selected_contract_id);

        if(ContractUserOtherCompany($contract_user->id, $this->company_id, true)[0] == NULL){
            $this->emit('item-error', ContractUserOtherCompany($contract_user->id, $this->company_id, true)[1]);
            return false;
        }

        $rules=[
            'ref_reason_termination' => 'required',
            'reason_termination' => 'required',
        ];
        $message=[
            'ref_reason_termination.required' => 'El campo Referencia es obligatorio',
            'reason_termination.required' => 'El campo Motivo es obligatorio',
        ];

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

        $contract_user->Update([
            'status' => '3',
            'ref_reason_termination' => $this->ref_reason_termination,
            'reason_termination' => $this->reason_termination,
            'date_termination' => date('Y-m-d H:i:s'),
            'user_termination' => Auth::user()->id
        ]);

        $message = NotifyMessageCustom(
            $title = 'Tienes un Contrato terminado con incidencia',
            $body = 'Tienes un Contrato terminado con incidencia en la plataforma.',
            $url = route('empleado-contratos'),
            $button_text = 'Ver Contrato',
            $via_from = 'Company',
            $user_to_id = $contract_user->user_id,
            $user_from_id = Auth::user()->id
        );

        $this->emit('hide-modal-terminate','El contrato fue terminado correctamente');
    }

}
