<?php

namespace App\Http\Livewire;

use App\Models\Company;
use App\Models\JobPosition;
use App\Models\Setting;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;

class Company_EmployeeProfileController extends Component
{
    public $search, $company_id, $pageTitle, $componentName, $user_id;
    public $selectedCompany;
    public $company_name, $company_plan_name, $company_plan_id, $minimum_salary, $transportation_allowance, $transportation_allowance_calculate, $total_monthly;
    public $first_name, $last_name, $document;
    public $job_position_id, $base_salary, $salary, $payment_method, $start_date_work, $end_date_work, $place_hired, $place_work, $work_day, $eps_id, $expiration_contract, $contract_modality;
    public $job_position_name, $job_position_salary, $salary_type, $salary_type_name;
    public $arl_option, $_value;
    public $days_worked, $basic, $total_basic_salary,$eps_value, $pension_value, $prima_value, $severance_value, $int_severance_value, $vacations_value, $sena_value, $icbf_value, $family_compensation_fund_value;
    public $sena_check, $icbf_check, $family_compensation_fund_check, $eps_check, $opt_eps_check;
    public $base_salary_calculate, $basic_calculate, $salary_integral_calculate, $performance_factor_calculate, $salary_integral, $performance_factor;
    public $main_functions, $special_functions, $qualities;
    public $breadcrumb_show;

    public function mount($id=null, $breadcrumb_show=true)
    {
        if ($id == null) {
            return redirect()->route('dashboard');
        }

        UserAuthPermission('Company_employee_profile_index');
        $user = User::find($id);
        $this->user_id = $user->id;
        $this->first_name = $user->first_name;
        $this->last_name = $user->last_name;
        if ($user->status == 'INACTIVO'){
            return redirect()->route('contratos-usuarios');
        }
        $this->company_id = Company::find(Auth::user()->CompanyId())->id;
        $this->pageTitle = 'Perfil empleado';
        $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;
        $company = Company::find($this->company_id)->users()->wherePivot('user_id', $this->user_id)->get()->first();
        $this->job_position_id = $company->pivot->job_position_id;
        $this->salary_type = $company->pivot->salary_type;
        $this->base_salary = number_format($company->pivot->base_salary, 2, '.', ',');
        $this->performance_factor = number_format($company->pivot->performance_factor, 2, '.', ',');
        $this->salary = number_format($company->pivot->salary, 2, '.', ',');
        $this->payment_method = $company->pivot->payment_method;
        $this->breadcrumb_show = $breadcrumb_show;

    }

    public function render()
    {
        $job_positions = JobPosition::where('company_id', $this->company_id)->orderBy('name', 'asc')->get();
        return view('livewire.company.contracts.employee-profile.component',compact('job_positions'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }
    /*
    public function updatedDaysWorked($value)
    {
        if (!is_null($value)) {
            $this->salary = (float) str_replace(',', '', $this->salary);
            $this->basic = (float) ($this->salary /30) * $this->days_worked;
            $basic_formated = $this->basic;
            $this->basic = number_format($this->basic, 2, '.', ',');
            $transportation_allowance_formated = str_replace(',', '', $this->transportation_allowance);
            $this->total_basic_salary = (float) $basic_formated + $transportation_allowance_formated;
            $this->total_basic_salary = number_format($this->total_basic_salary, 2, '.', ',');
        }
    }

    public function updatedTransportationAllowance($value){
        if (!is_null($value)) {
            $transportation_allowance_formated = str_replace(',', '', $this->transportation_allowance);
            $basic_formated = str_replace(',', '', $this->basic);
            $this->total_basic_salary = (float) $basic_formated + $transportation_allowance_formated;
            $this->total_basic_salary = number_format($this->total_basic_salary, 2, '.', ',');
        }
    }
    */

    public function getBaseSalaryJobPosition()
    {
        if ($this->job_position_id != NULL){
            $job_position = JobPosition::find($this->job_position_id);
            $this->base_salary = number_format($job_position->base_salary, 2, '.', ',');
            $this->main_functions = $job_position->main_functions;
            $this->special_functions = $job_position->special_functions;
            $this->qualities = $job_position->qualities;
        }
    }

    public function calculateSalary()
    {
        if ($this->days_worked == null) {
            $this->emit('item-error', 'Debe ingresar los días trabajados');
            return false;
        }
        if ($this->arl_option == null) {
            $this->emit('item-error', 'Debe seleccionar una opción de ARL');
            return false;
        }
        $settings = Setting::first();
        $this->minimum_salary = number_format($settings->minimum_salary, 2, '.', ',');
        $this->transportation_allowance = number_format($settings->transportation_allowance, 2, '.', ',');
        $this->transportation_allowance_calculate = number_format($settings->transportation_allowance, 2, '.', ',');
        $this->base_salary_calculate = (float) str_replace(',', '', $this->base_salary_calculate);
        $this->basic_calculate = (float) ($this->base_salary_calculate /30) * $this->days_worked;
        $basic_formated = $this->basic_calculate;
        $minimum_salary_formated = str_replace(',', '', $this->minimum_salary);

        if ($basic_formated > (($minimum_salary_formated * 2) + 0.01)) {
            $this->transportation_allowance_calculate = 0;
        }
        $transportation_allowance_formated = str_replace(',', '', $this->transportation_allowance_calculate);
        $this->total_basic_salary = (float) $basic_formated + $transportation_allowance_formated;
        $this->total_monthly = $this->total_basic_salary;

        if ($this->salary_type == '1'){// si el tipo de salario es fijo la opción eps sera obligatoria
            $this->eps_check = true;
        }
        $this->eps_value = $this->eps_check == true ? (float) $this->basic_calculate * 0.085 : 0;
        $this->pension_value = (float) $basic_formated * 0.12;
        $this->arl_value = (float) $basic_formated * $this->arl_option;
        $this->prima_value = (float) $this->total_basic_salary * 0.0833;
        $this->severance_value = (float) $this->total_basic_salary * 0.0833;
        $this->int_severance_value = (float) ($this->severance_value * $this->days_worked * 0.12) / 30;
        $this->vacations_value = (float) $this->basic_calculate * 0.0417;
        debug($this->sena_check);
        $this->sena_value = $this->sena_check == true ? (float) $this->basic_calculate * 0.02 : 0;
        debug($this->sena_value);
        $this->icbf_value = $this->icbf_check == true ? (float) $this->basic_calculate * 0.03 : 0;
        $this->family_compensation_fund_value = (float) $this->basic_calculate * 0.04;

        $this->total_monthly = $this->total_basic_salary + $this->eps_value +$this->pension_value;
        $this->total_monthly += $this->arl_value +$this->prima_value;
        $this->total_monthly += $this->severance_value + $this->int_severance_value;
        $this->total_monthly += $this->vacations_value + $this->sena_value + $this->icbf_value;
        $this->total_monthly += $this->family_compensation_fund_value;

        $this->performance_factor_calculate = 0;
        $this->base_salary_calculate = number_format($this->base_salary_calculate, 2, '.', ',');
        $this->basic_calculate = number_format($this->basic_calculate, 2, '.', ',');
        $this->total_basic_salary = number_format($this->total_basic_salary, 2, '.', ',');

        $this->eps_value = number_format($this->eps_value, 2, '.', ',');
        $this->pension_value = number_format($this->pension_value, 2, '.', ',');
        $this->arl_value = number_format($this->arl_value, 2, '.', ',');
        $this->prima_value = number_format($this->prima_value, 2, '.', ',');
        $this->severance_value = number_format($this->severance_value, 2, '.', ',');
        $this->int_severance_value = number_format($this->int_severance_value, 2, '.', ',');
        $this->vacations_value = number_format($this->vacations_value, 2, '.', ',');
        $this->sena_value = number_format($this->sena_value, 2, '.', ',');
        $this->icbf_value = number_format($this->icbf_value, 2, '.', ',');
        $this->family_compensation_fund_value = number_format($this->family_compensation_fund_value, 2, '.', ',');
        $this->total_monthly = number_format($this->total_monthly, 2, '.', ',');
        $this->emit('item-message', 'Se ha calculado el salario correctamente');
    }

    public function calculateSalaryIntegral()
    {
        if ($this->arl_option == null) {
            $this->emit('item-error', 'Debe seleccionar una opción de ARL');
            return false;
        }
        $settings = Setting::first();
        $this->minimum_salary = number_format($settings->minimum_salary, 2, '.', ',');

        $this->base_salary_calculate = (float) str_replace(',', '', $this->base_salary_calculate);
        debug($this->base_salary_calculate);
        if ($this->base_salary_calculate < ($settings->minimum_salary * 10)) {
            $this->emit('item-error', 'El salario base debe ser de mínimo $'.number_format(($settings->minimum_salary *10), 2, '.', ','));
            $this->base_salary_calculate = number_format($this->base_salary_calculate, 2, '.', ',');
            return false;
        }

        $this->performance_factor_calculate = (float) $this->base_salary_calculate * 0.30;

        $this->salary_integral_calculate = (float) $this->base_salary_calculate + $this->performance_factor_calculate;

        $salary_integral_70 = (float) $this->salary_integral_calculate * 0.70;

        $this->eps_check = true; // si el tipo de salario es integral la opción eps sera obligatoria

        $this->eps_value = $this->eps_check == true ? (float) $salary_integral_70 * 0.085 : 0;
        $this->pension_value = (float) $salary_integral_70 * 0.12;
        $this->arl_value = (float) $salary_integral_70 * $this->arl_option;
        $this->prima_value = 0;
        $this->severance_value = 0;
        $this->int_severance_value = 0;
        $this->vacations_value = (float) ($this->salary_integral_calculate *15) / 30;
        debug($this->sena_check);
        $this->sena_value = $this->sena_check == true ? (float) $this->salary_integral_calculate * 0.02 : 0;
        debug($this->sena_value);
        $this->icbf_value = $this->icbf_check == true ? (float) $this->salary_integral_calculate * 0.03 : 0;
        $this->family_compensation_fund_value = (float) $this->salary_integral_calculate * 0.04;

        $this->total_monthly = $this->salary_integral_calculate + $this->eps_value +$this->pension_value;
        $this->total_monthly += $this->arl_value +$this->prima_value;
        $this->total_monthly += $this->severance_value + $this->int_severance_value;
        $this->total_monthly += $this->vacations_value + $this->sena_value + $this->icbf_value;
        $this->total_monthly += $this->family_compensation_fund_value;

        $this->base_salary_calculate = number_format($this->base_salary_calculate, 2, '.', ',');
        $this->performance_factor_calculate = number_format($this->performance_factor_calculate, 2, '.', ',');
        $this->salary_integral_calculate = number_format($this->salary_integral_calculate, 2, '.', ',');

        $this->eps_value = number_format($this->eps_value, 2, '.', ',');
        $this->pension_value = number_format($this->pension_value, 2, '.', ',');
        $this->arl_value = number_format($this->arl_value, 2, '.', ',');
        $this->prima_value = number_format($this->prima_value, 2, '.', ',');
        $this->severance_value = number_format($this->severance_value, 2, '.', ',');
        $this->int_severance_value = number_format($this->int_severance_value, 2, '.', ',');
        $this->vacations_value = number_format($this->vacations_value, 2, '.', ',');
        $this->sena_value = number_format($this->sena_value, 2, '.', ',');
        $this->icbf_value = number_format($this->icbf_value, 2, '.', ',');
        $this->family_compensation_fund_value = number_format($this->family_compensation_fund_value, 2, '.', ',');
        $this->total_monthly = number_format($this->total_monthly, 2, '.', ',');
        $this->emit('item-message', 'Se ha calculado el salario correctamente');
    }

    public function addValueSalary(){
        $this->base_salary = $this->base_salary_calculate;
        $this->salary = $this->total_monthly;
        $this->performance_factor = $this->performance_factor_calculate;
        $this->emit('item-updated', 'Se ha agregado el salario correctamente');
    }

    public function openCalculateSalary()
    {
        if ($this->job_position_id == null) {
            $this->emit('item-error', 'Seleccione el Cargo u Oficio');
            return false;
        }
        if ($this->salary_type == null) {
            $this->emit('item-error', 'Seleccione el Tipo de Salario');
            return false;
        }
        $settings = Setting::first();
        $this->minimum_salary = number_format($settings->minimum_salary, 2, '.', ',');
        $this->transportation_allowance = number_format($settings->transportation_allowance, 2, '.', ',');
        $job_position = JobPosition::find($this->job_position_id);
        $this->job_position_name = $job_position->name;
        $this->job_position_salary = number_format($job_position->base_salary, 2, '.', ',');
        $this->base_salary_calculate = $this->base_salary;

        if ($this->salary_type == '1') {
            $this->salary_type_name = 'FIJO';
            $this->opt_eps_check = false;//si el tipo de salario es fijo el input check no se muestra
            $this->emit('show-modal-salary', 'modal-calculate-salary');
        }
        if ($this->salary_type == '3') {
            $this->salary_type_name = 'PARCIAL';
            $this->opt_eps_check = true;//si el tipo de salario es parcial el input check se muestra
            $this->emit('show-modal-salary', 'modal-calculate-salary');
        }
        if ($this->salary_type == '2') {
            $this->emit('show-modal-salary-integral', 'modal-calculate-salary-integral');
        }
    }

    public function resetUI()
    {
        $this->resetValidation();
    }

    public function storeProfile(){

        $useractions = UserAuthPermissionActions('Company_employee_profile_update');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $company = Company::find($this->company_id);


        $rules = [
            'job_position_id' => 'required',
            'salary_type' => 'required',
            'payment_method' => 'required',
            'base_salary' => ['required_if:salary_type,2','max:13', 'regex:/^\d{1,3}(?:\,\d\d\d)*(?:.\d{1,2})?$/'],
            'performance_factor' => ['required_if:salary_type,2','max:13', 'regex:/^\d{1,3}(?:\,\d\d\d)*(?:.\d{1,2})?$/'],
            'salary' => 'required|max:13|min:0|not_in:0|regex:/^\d{1,3}(?:\,\d\d\d)*(?:.\d{1,2})?$/',
        ];

        $messages = [
            'job_position_id.required' => 'El campo "Cargo u Oficio" es obligatorio',
            'salary_type.required' => 'El campo "Tipo de Salario" es obligatorio',
            'payment_method.required' => 'El campo "Forma de Pago" es obligatorio',
            'base_salary.required_if' => 'El campo "Salario Base" es obligatorio',
            'base_salary.max' => 'El campo "Salario Base" no puede tener más de 8 dígitos',
            'base_salary.regex' => 'El campo "Salario Base" no tiene el formato correcto',
            'performance_factor.required_if' => 'El campo "Factor de Desempeño" es obligatorio',
            'performance_factor.max' => 'El campo "Factor de Desempeño" no puede tener más de 8 dígitos',
            'performance_factor.regex' => 'El campo "Factor de Desempeño" no tiene el formato correcto',
            'salary.required' => 'El campo "Salario" es obligatorio',
            'salary.max' => 'El campo "Salario" no puede tener más de 8 dígitos',
            'salary.min' => 'El campo "Salario" no puede ser menor a 0',
            'salary.not_in' => 'El campo "Salario" no puede ser 0',
            'salary.regex' => 'El campo "Salario" no tiene el formato correcto',
        ];
        $this->validate($rules, $messages);

        $company->users()->updateExistingPivot($this->user_id, [
            'job_position_id' => $this->job_position_id,
            'salary' => (float)str_replace(',', '', $this->salary),
            'payment_method' => $this->payment_method,
            'salary_type' => $this->salary_type,
            'base_salary' => (float) str_replace(',', '', $this->base_salary),
            'performance_factor' => (float) str_replace(',', '', $this->performance_factor),
            'salary' => (float) str_replace(',', '', $this->salary),
        ]);

        $this->emit('item-updated', 'Perfil actualizado correctamente');
    }


}
