<?php

namespace App\Http\Livewire;

use App\Models\Company;
use App\Models\Contract;
use App\Models\HistoryContractsUser;
use App\Models\JobPosition;
use App\Models\User;
use App\Traits\OrderByTable;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Luecano\NumeroALetras\NumeroALetras;

use Livewire\WithPagination;

class Company_ContractsUsersCreateController 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, $duration_contract;
    public $sel_contract_name, $sel_contract_type, $sel_contract_sub_type, $sel_contract_description;
    public $company_name, $company_plan_name, $company_plan_id, $company_signature;
    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 $energy_cost, $maintenance_technology_resources_cost, $phone_cost, $others_cost, $no_salary_cost;
    public $signature_full_name, $signature_position, $signature_document_type, $signature_document_number;
    public $name_administrative_company;

    public $breadcrumb_show = true;

    private $pagination = 10;

    protected $paginationTheme = 'bootstrap';

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

    public function mount($id)
    {
        $user = User::find($id);
        UserAuthPermission('Company_contracts_users_create');
        if ($user->status == 'INACTIVO'){
            return redirect()->route('contratos-empleados');
        }

        $this->user_id = $user->id;

        //lista de contratos del empleado
        $contracts_user = HistoryContractsUser::where('user_id', $this->user_id)->get();

        // si alguno de los contratos esta activo redireccionar a la vista de contratos
        foreach ($contracts_user as $contract_user){
            if ($contract_user->status == 'Aprobado' || $contract_user->status == 'Pendiente'){
                return redirect()->route('contratos-empleados')->with('error', 'El empleado ya tiene un contrato activo');
            }
        }
        $this->first_name = $user->first_name;
        $this->last_name = $user->last_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->company_signature = Company::find($this->company_id )->signature;
    }

    public function render()
    {
        if (strlen($this->search) > 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 . '%')
                                        ->orWhere('contracts.description', 'like', '%' . $this->search . '%');
                                })
                                ->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 . '%')
                                        ->orWhere('contracts.description', 'like', '%' . $this->search . '%');
                                    })
                                    ->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);
        }
        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);
            }

        $this->count_reg = $contracts_company->count();
        return view('livewire.company.contracts.create.component',compact('contracts_company'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function resetUI()
    {
        $this->start_date = '';
        $this->end_date = '';
        $this->start_date_work = '';
        $this->end_date_work = '';
        $this->work_day = '';
        $this->place_hired = '';
        $this->place_work = '';
        $this->energy_cost = '';
        $this->maintenance_technology_resources_cost = '';
        $this->phone_cost = '';
        $this->other_cost = '';
        $this->no_salary_cost = '';
        $this->search = '';
        $this->status ='';
        $this->selected_user_id = 0;
        $this->resetValidation();
        $this->resetPage();
    }
    public function resetUIModal()
    {
        $this->start_date = '';
        $this->end_date = '';
        $this->start_date_work = '';
        $this->end_date_work = '';
        $this->selected_contract_id = 0;
        $this->selected_contract_name = '';
        $this->selected_contract_description = '';
        $this->selected_contract_type = '';
        $this->selected_contract_sub_type = '';
        $this->resetValidation();
    }

    public function openSelContract($contract_id)
    {
        $contract = Contract::find($contract_id);
        if (EmployeeOtherCompany($this->user_id, true)[0] == NULL)
        {
            $this->emit('item-error', EmployeeOtherCompany($this->user_id, true)[1]);
            return false;
        }
        if (ContractNotCompany($contract->id, $this->company_id, $this->company_plan_id, true)[0] == NULL)
        {
            $this->emit('item-error', ContractNotCompany($contract->id, $this->company_id, $this->company_plan_id,  true)[1]);
            return false;
        }
        /*
        if ($this->company_signature == NULL)
        {
            $this->emit('item-error', 'La firma de la empresa no ha sido registrada');
            return false;
        }
        */
        $this->selected_contract_id = $contract->id;
        $this->sel_contract_name = $contract->name;
        $this->sel_contract_description = $contract->description;
        $this->sel_contract_type = $contract->type;
        $this->sel_contract_sub_type = $contract->sub_type;
        $this->resetValidation();
        $this->emit('show-modal','Abrir modal crear Contrato');
    }

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

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

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

        //lista de contratos del empleado
        $contracts_user = HistoryContractsUser::where('user_id', $this->user_id)->get();

        // si alguno de los contratos esta activo redireccionar a la vista de contratos
        foreach ($contracts_user as $contract_user){
            if ($contract_user->status == 'Aprobado' || $contract_user->status == 'Pendiente'){
                return redirect()->route('contratos-empleados');
            }
        }
        $formatter = new NumeroALetras();
        $rules =[
            'start_date' => 'required|date',
            'start_date_work' => 'required|date',
            'place_hired' => 'required',
            'place_work' => 'required',
        ];
        $messages = [
            'start_date.required' => 'El campo fecha inicio es obligatorio',
            'start_date.date' => 'El campo fecha inicio debe ser una fecha valida',
            'start_date_work.required' => 'El campo fecha inicio de trabajo es obligatorio',
            'start_date_work.date' => 'El campo fecha inicio de trabajo debe ser una fecha valida',
            'place_hired.required' => 'El campo Lugar donde desempeñara el cargo es obligatorio',
            'place_work.required' => 'El campo Lugar donde trabajara es obligatorio',
        ];
        if ($this->sel_contract_type == 2)
        {
            $rules['end_date'] = 'required|date|after:start_date';
            $rules['end_date_work'] = 'required|date|after:start_date_work';
            $messages['end_date.required'] = 'El campo fecha finalización es obligatorio';
            $messages['end_date.date'] = 'El campo fecha finalización debe ser una fecha valida';
            $messages['end_date.after'] = 'La fecha finalización debe ser mayor a la fecha inicio';
            $messages['end_date_work.required'] = 'El campo fecha finalización es obligatorio';
            $messages['end_date_work.date'] = 'El campo fecha finalización debe ser una fecha valida';
            $messages['end_date_work.after'] = 'La fecha finalización debe ser mayor a la fecha inicio';
        }
        if ($this->sel_contract_type != 1)
        {
            $rules['work_day'] ='required';
            $messages['work_day.required'] = 'El campo Jornada laboral es obligatorio';
        }
        $this->validate($rules, $messages);

        $user=User::find($this->user_id);
        //$user->birth_date = Carbon::parse($user->birth_date)->day . ' de ' . Carbon::parse($user->birth_date)->monthName . ' de ' . Carbon::parse($user->birth_date)->year;
        $company = Company::find($this->company_id);
        $profile_employee = Company::find($this->company_id)->users()->wherePivot('user_id', $this->user_id)->get()->first();

        if ($profile_employee->pivot->job_position_id == null ||
            $profile_employee->pivot->salary_type == null ||
            $profile_employee->pivot->salary == null ||
            $profile_employee->pivot->payment_method == null)
        {
            $this->emit('item-error', 'Por favor complete el perfil del empleado para continuar con la creación del contrato');
            return false;
            //return redirect()->route('contratos-empleados', $this->user_id)->with('error', 'Por favor complete el perfil del empleado');
        }
        if ($profile_employee->pivot->job_position_id != null) {
            $user_job_position = JobPosition::find($profile_employee->pivot->job_position_id)->name;
        } else {
            $user_job_position = '';
        }
        if (!empty($profile_employee->pivot->payment_method)){
            $profile_employee->pivot->payment_method = DataTypePaymentMethod($profile_employee->pivot->payment_method);
        }
        $fecha_hoy = Carbon::parse(Carbon::now())->day . ' del mes de ' . Carbon::parse(Carbon::now())->monthName . ' del año ' . Carbon::parse(Carbon::now())->year;

        //dd($profile_employee->pivot->payment_method);
        $this->duration_contract = Carbon::parse($this->start_date)->diffInMonths(Carbon::parse($this->end_date)).' Meses';
        $params = ["{Nombre}","{Apellido}","{Fecha_Nacimiento}","{Lugar_Nacimiento}","{Tipo_documento}","{Tipo_documento_abreviado}",
                    "{Numero_documento}","{Expedicion_documento}","{Nacionalidad}","{Telefono}","{Direccion}","{Ciudad_residencia}","{Departamento_residencia}",
                    "{Empresa}","{NIT}","{Email_empresa}","{Telefono_empresa}","{Direccion_empresa}","{Ciudad_empresa}","{Departamento_empresa}",
                    "{Representante_legal}","{Tipo_doc_representante_legal}","{Tipo_doc_rep_legal_abbreviacion}","{Doc_representante_legal}",
                    "{Exp_doc_representante_legal}",
                    "{Cargo}","{Sueldo_mensual}","{Sueldo_mensual_letras}","{Forma_pago}","{Fecha_firma}","{Lugar_donde_ha_sido_contratado}",
                    "{Lugar_donde_realizara_labores}","{Fecha_inicio_labores}","{Fecha_fin_labores}","{Fecha_inicio_contrato}",
                    "{Fecha_finalizacion_contrato}","{Duracion_contrato}",
                    "{Costo_energia}","{Costo_mantenimiento_recursos_tecnologicos}","{Costo_telefonia}","{Otros_gastos}","{Conceptos_no_salariales}"];
        $start_date_es = Carbon::parse($this->start_date)->day . ' de ' . Carbon::parse($this->start_date)->monthName . ' de ' . Carbon::parse($this->start_date)->year;
        $end_date_es = Carbon::parse($this->end_date)->day . ' de ' . Carbon::parse($this->end_date)->monthName . ' de ' . Carbon::parse($this->end_date)->year;

        if ($this->start_date_work != null){
            $start_date_work_es = Carbon::parse($this->start_date_work)->day . ' de ' . Carbon::parse($this->start_date_work)->monthName . ' de ' . Carbon::parse($this->start_date_work)->year;
        } else {
            $start_date_work_es = '';
        }
        if ($this->end_date_work != null){
            $end_date_work_es = Carbon::parse($this->end_date_work)->day . ' de ' . Carbon::parse($this->end_date_work)->monthName . ' de ' . Carbon::parse($this->end_date_work)->year;
        } else {
            $end_date_work_es = '';
        }
        //$salary_type = DataTypeSalary($profile_employee->pivot->salary_type);

        $salary = '$'.number_format($profile_employee->pivot->salary, 2, '.', ',');

        $salary_letras = mb_strtolower($formatter->toMoney($profile_employee->pivot->salary, 2, 'pesos', 'centavos'));


        $energy_cost = '$'.$this->energy_cost;
        $this->energy_cost = (float) str_replace(',', '', $this->energy_cost); //remover el formato de miles y centavos
        $energy_cost .= ' ('.mb_strtolower($formatter->toMoney($this->energy_cost, 2, 'pesos', 'centavos')).')';


        $maintenance_technology_resources_cost = '$'.$this->maintenance_technology_resources_cost;
        $this->maintenance_technology_resources_cost = (float) str_replace(',', '', $this->maintenance_technology_resources_cost); //remover el formato de miles y centavos
        $maintenance_technology_resources_cost .= '('.mb_strtolower($formatter->toMoney($this->maintenance_technology_resources_cost, 2, 'pesos', 'centavos')).')';

        $phone_cost = '$'.$this->phone_cost;
        $this->phone_cost = (float) str_replace(',', '', $this->phone_cost); //remover el formato de miles y centavos
        $phone_cost .= '('.mb_strtolower($formatter->toMoney($this->phone_cost, 2, 'pesos', 'centavos')).')';

        $others_cost = '$'.$this->others_cost;
        $this->others_cost = (float) str_replace(',', '', $this->others_cost); //remover el formato de miles y centavos
        $others_cost .= '('.mb_strtolower($formatter->toMoney($this->others_cost, 2, 'pesos', 'centavos')).')';

        $data_user=[$user->first_name, $user->last_name, $user->birth_place, $user->birth_date_es, $user->document_type_name, $user->document_type_name_abbreviation,
        $user->document, $user->document_expedition, $user->nationality, $user->phone, $user->address, $user->city_residence_name, $user->state_residence_name,
        $company->name, $company->nit, $company->email, $company->phone, $company->address, $company->city_name, $company->state_name,
        $company->legal_representative, $company->document_type_representative_name, $company->document_type_representative_name_abbreviation, $company->document_representative,
        $company->document_expedition_representative,
        $user_job_position, $salary, $salary_letras, $profile_employee->pivot->payment_method, $fecha_hoy, $this->place_hired,
        $this->place_work, $start_date_work_es, $end_date_work_es, $start_date_es, $end_date_es, $this->duration_contract,
        $energy_cost, $maintenance_technology_resources_cost, $phone_cost, $others_cost, $this->no_salary_cost];

        $contract=Contract::select('contracts.content')
            ->where('contracts.id',$this->selected_contract_id)
            ->first();

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

        //dd($new_content);
        if ($new_content != null){
            debug($new_content);
            //$new_content = mb_convert_encoding($new_content, 'UTF-8', 'UTF-8');
            $historyContractUser=HistoryContractsUser::create([
                'user_id' => $this->user_id,
                'contract_id' => $this->selected_contract_id,
                'company_id' => $this->company_id,
                'job_position' => $user_job_position,
                'salary_type' => $profile_employee->pivot->salary_type,
                'base_salary' => $profile_employee->pivot->base_salary,
                'performance_factor ' => $profile_employee->pivot->performance_factor,
                'salary' => $profile_employee->pivot->salary,
                'content_contract' => $new_content,
                'start_date' => $this->start_date,
                'end_date' => $this->end_date,
                '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,
                'energy_cost' => $this->energy_cost,
                'maintenance_technology_resources_cost' => $this->maintenance_technology_resources_cost,
                'phone_cost' => $this->phone_cost,
                'others_cost' => $this->others_cost,
                'no_salary_cost' => $this->no_salary_cost,
                'status' => '0',
                'created_by' => Auth::user()->id,
            ]);
        }
        if ($historyContractUser){
            return redirect()->route('contratos-empleados.historial',[$this->user_id]);
        }

    }

    public function addSymbol($number){
        $number = '$'.$number;
        return $number;
    }

    public function openAddConcept(){
        $this->emit('show-modal-concept','Abrir modal para agregar concepto');
    }
}
