<?php

namespace App\Http\Livewire;

use App\Models\Company;
use App\Models\Contract;
use App\Models\PublicHealthEntity;
use App\Models\User;
use App\Traits\OrderByTable;
use GuzzleHttp\Psr7\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
use Livewire\WithPagination;

class Company_ContractsUsersController extends Component
{
    use WithPagination;
    use OrderByTable;

    public $search, $company_id, $selected_user_id, $pageTitle, $componentName, $user_id, $search_modal, $count_reg_modal, $status_contract, $type_contract, $sub_type_contract;
    public $selectedCompany;
    public $company_name, $company_plan_name, $company_plan_id;
    public $first_name, $last_name, $document, $phone, $email, $status, $password, $image, $selected_id, $fileLoaded;
    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 $breadcrumb_show=true;
    public $filter_employees = 'all';

    private $pagination = 10;
    private $pagination_modal = 5;

    protected $paginationTheme = 'bootstrap';

    public function updatingSearch(){
        $this->emit('show-modal', 'modal-contract');
    }

    public function mount()
    {

        UserAuthPermission('Company_contracts_users_index');
        $this->company_id = Company::find(Auth::user()->CompanyId())->id;
        $this->pageTitle = 'Contratos';
        $this->componentName = 'Empresa';
        $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;

    }

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

                $users= User::select('users.*','companies.name as company_name', 'roles.name as role_name')
                            ->join('company_user', 'users.id', '=', 'company_user.user_id')
                            ->join('companies', 'company_user.company_id', '=', 'companies.id')
                            ->join('model_has_roles', 'users.id', '=', 'model_has_roles.model_id')
                            ->join('roles', 'model_has_roles.role_id', '=', 'roles.id')
                            ->whereHas('roles', function($query) {
                                if ($this->filter_employees == 'contractors') {
                                    $query->where('name', 'Contratista');
                                } else {
                                    $query->whereIn('name', ['Empleado', 'Contratista']);
                                }
                            })
                            ->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 . '%');
                            })
                            ->orderBy($this->sortBy, $this->sortDirection)->paginate($this->pagination);
            }
            else
            {
                $users= User::select('users.*','companies.name as company_name', 'roles.name as role_name')
                            ->join('company_user', 'users.id', '=', 'company_user.user_id')
                            ->join('companies', 'company_user.company_id', '=', 'companies.id')
                            ->join('model_has_roles', 'users.id', '=', 'model_has_roles.model_id')
                            ->join('roles', 'model_has_roles.role_id', '=', 'roles.id')
                            ->whereHas('roles', function($query) {
                                if ($this->filter_employees == 'contractors') {
                                    $query->where('name', 'Contratista');
                                } else {
                                    $query->whereIn('name', ['Empleado', 'Contratista']);
                                }
                            })
                            ->where('companies.id', Auth::user()->CompanyId())
                            ->orderBy($this->sortBy, $this->sortDirection)
                            ->paginate($this->pagination);
            }
            if (strlen($this->search_modal) > 0){
                $contracts_company = Contract::select('contracts.*')
                                    ->join('contract_plans', 'contract_plans.contract_id', '=', 'contracts.id')
                                    ->join('plans', 'contract_plans.plan_id', '=', 'plans.id')
                                    ->where('contract_plans.plan_id', $this->company_plan_id)
                                    ->orderBy('contracts.id', 'desc')
                                    ->where(function ($query) {
                                        $query->where('contracts.name', 'like', '%' . $this->search_modal . '%')
                                            ->orWhere('contracts.description', 'like', '%' . $this->search_modal . '%');
                                    })
                                    ->where(function ($query) {
                                        $query->where('contracts.status', 'Activo');
                                    })
                                    ->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);
                                        }
                                    })
                                    ->union(
                                        Contract::select('contracts.*')
                                        ->join('contract_companies', 'contract_companies.contract_id', '=', 'contracts.id')
                                        ->join('companies', 'contract_companies.company_id', '=', 'companies.id')
                                        ->where('contract_companies.company_id', $this->company_id)
                                        ->where(function ($query) {
                                            $query->where('contracts.name', 'like', '%' . $this->search_modal . '%')
                                            ->orWhere('contracts.description', 'like', '%' . $this->search_modal . '%');
                                        })
                                        ->where(function ($query) {
                                            $query->where('contracts.status', 'Activo');
                                        })
                                        ->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('contracts.id', 'desc')
                                    )
                                    ->paginate($this->pagination_modal);
            }
            else{
                $contracts_company = Contract::select('contracts.*')
                                    ->join('contract_plans', 'contract_plans.contract_id', '=', 'contracts.id')
                                    ->join('plans', 'contract_plans.plan_id', '=', 'plans.id')
                                    ->where('contract_plans.plan_id', $this->company_plan_id)
                                    ->orderBy('contracts.id', 'desc')
                                    ->where(function ($query) {
                                        $query->where('contracts.status', 'Activo');
                                    })
                                    ->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);
                                        }
                                    })
                                    ->union(
                                        Contract::select('contracts.*')
                                        ->join('contract_companies', 'contract_companies.contract_id', '=', 'contracts.id')
                                        ->join('companies', 'contract_companies.company_id', '=', 'companies.id')
                                        ->where('contract_companies.company_id', $this->company_id)
                                        ->where(function ($query) {
                                            $query->where('contracts.status', 'Activo');
                                        })
                                        ->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('contracts.id', 'desc')
                                    )
                                    ->paginate($this->pagination_modal);
            }
        $this->count_reg = $users->total();
        $this->count_reg_modal = $contracts_company->count();
        $epss = PublicHealthEntity::all();
        return view('livewire.company.contracts.component',compact('users', 'epss', 'contracts_company'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function ShowToogleContractors()
    {
        if ($this->filter_employees == 'all') {
            $this->filter_employees = 'contractors';
        } else {
            $this->filter_employees = 'all';
        }
    }

    public function openContract(User $user)
    {
        $this->user = $user;
        $this->user_id = $user->id;
        $this->first_name = $user->first_name;
        $this->last_name = $user->last_name;
        $this->type_contract = '';
        $this->sub_type_contract = '';
        $this->emit('show-modal', 'modal-contract');
    }

    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->resetValidation();
        $this->resetPage();
    }

    public function openProfile(User $user)
    {
        $useractions = UserAuthPermissionActions('Company_contracts_users_profile_update');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }

        $this->user_id = $user->id;
        $user = User::find($this->user_id);
        $this->first_name = $user->first_name;
        $this->last_name = $user->last_name;
        $company = Company::find($this->company_id)->users()->wherePivot('user_id', $this->user_id)->get()->first();
        $this->title_position = $company->pivot->title_position;
        $this->salary = $company->pivot->salary;
        $this->payment_method = $company->pivot->payment_method;
        $this->start_date_work = $company->pivot->start_date_work;
        $this->end_date_work = $company->pivot->end_date_work;
        $this->place_hired = $company->pivot->place_hired;
        $this->place_work = $company->pivot->place_work;
        $this->work_day = $company->pivot->work_day;
        $this->eps_id = $company->pivot->eps_id;
        $this->expiration_contract = $company->pivot->expiration_contract;
        $this->contract_modality = $company->pivot->contract_modality;
        $this->emit('show-modal-profile', 'profile');
    }

    public function storeProfile(){
        $company = Company::find($this->company_id);
        $rules = [
            'title_position' => 'required|max:99',
            'salary' => 'required',
            'payment_method' => 'required',
            'start_date_work' => 'required|date',
            'end_date_work' => 'required|date|after:start_date_work',
            'place_hired' => 'required|max:99',
            'place_work' => 'required|max:99',
            'work_day' => 'required',
            'eps_id' => 'required',
            'expiration_contract' => 'required|date',
            'contract_modality' => 'required',
        ];
        $messages = [
            'title_position.required' => 'El campo "Cargo u Oficio" es obligatorio',
            'title_position.max' => 'El campo "Cargo u Oficio" no puede tener más de 99 caracteres',
            'salary.required' => 'El campo "Salario" es obligatorio',
            'payment_method.required' => 'El campo "Forma de Pago" es obligatorio',
            'start_date_work.required' => 'El campo "Fecha de Inicio de Labores" es obligatorio',
            'start_date_work.date' => 'El campo "Fecha de Inicio de Labores" debe ser una fecha',
            'end_date_work.required' => 'El campo "Fecha de Fin de Labores" es obligatorio',
            'end_date_work.date' => 'El campo "Fecha de Fin de Labores" debe ser una fecha',
            'end_date_work.after' => 'El campo "Fecha de Fin de Labores" debe ser mayor a la fecha de inicio de labores',
            'place_hired.required' => 'El campo "Lugar donde ha sido contratado" es obligatorio',
            'place_hired.max' => 'El campo "Lugar donde ha sido contratado" no puede tener más de 99 caracteres',
            'place_work.required' => 'El campo "Lugar donde desempeñará labores" es obligatorio',
            'place_work.max' => 'El campo "Lugar donde desempeñará labores" no puede tener más de 99 caracteres',
            'work_day.required' => 'El campo "Jornada laboral" es obligatorio',
            'eps_id.required' => 'El campo "EPS" es obligatorio',
            'expiration_contract.required' => 'El campo "Fecha de vencimiento del Contrato" es obligatorio',
            'expiration_contract.date' => 'El campo "Fecha de vencimiento del Contrato" debe ser una fecha',
            'contract_modality.required' => 'El campo "Modalidad de Contrato" es obligatorio',
        ];

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

        $company->users()->updateExistingPivot($this->user_id, [
            'title_position' => $this->title_position,
            'salary' => (float)str_replace(',', '', $this->salary),
            'payment_method' => $this->payment_method,
            'start_date_work' => $this->start_date_work,
            'end_date_work' => $this->end_date_work,
            'place_hired' => $this->place_hired,
            'place_work' => $this->place_work,
            'work_day' => $this->work_day,
            'eps_id' => $this->eps_id,
            'expiration_contract' => $this->expiration_contract,
            'contract_modality' => $this->contract_modality,
        ]);
        $this->emit('hide-modal-profile', 'Perfil actualizado correctamente');
    }

    function AddContractUser(Contract $contract){
        $useractions = UserAuthPermissionActions('Company_contracts_users_create');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $params=["{Nombre}", "{Apellido}", "{Tipo_documento}","{Documento}","{Edad}","{Cargo}", "{Salario}", "{Empresa}"];
        $user=User::find($this->user_id);
        $data_user=[$user->first_name, $user->last_name, $user->type_document, $user->document, $user->age, "Desarrollador", "6850000", $this->company_name];

        $new_content = str_replace($params, $data_user, $contract->content);

        $historyContractUser=HistoryContractsUsers::create([
            'user_id' => $this->user_id,
            'company_id' => $this->company_id,
            'contract_id' => $contract->id,
            'content' => $new_content,
            'status' => $this->status_contract,

        ]);

        if ($historyContractUser){
            return redirect()->route('historial-contratos-usuarios',[$this->user_id]);
        }

    }
}
