<?php

namespace App\Http\Livewire;

use App\Imports\EmployeesImport;
use App\Models\AnnexOther;
use App\Models\AnnexOthersContractUser;
use App\Models\Company;
use App\Models\HistoryContractsUser;
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_AnnexContractUserController extends Component
{
    use WithPagination;
    use OrderByTable;
    use WithFileUploads;

    public $componentName, $pageTitle, $search_modal;
    public $company_id,  $company_name, $company_plan_name;
    public $signature_company, $signature_employee;
    public $first_name, $last_name;
    public $signature_full_name, $signature_position, $signature_document_type, $signature_document_number, $signature_validate;
    public $annex_id, $annex_name, $annex_description, $annex_content, $annex_content_edit, $annexes, $query, $highlightIndex;
    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_annex_add');
        $contract_user = HistoryContractsUser::find($id);

        if ($contract_user != NULL) {

            $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->pageTitle = 'Anexo Otrosí';
            $this->componentName = 'Contrato';

            $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;

            $this->signature_full_name = $company->legal_representative;
            $this->signature_position = 'Representante Legal';
            $this->signature_document_type = $company->document_type_representative;
            $this->signature_document_number = $company->document_representative;
            $this->signature_company = $contract_user->signature_company;
            $this->signature_company_saved = $contract_user->signature_company;

        }


    }

    public function resetUI(){
        $this->search = '';
        $this->annex_id = '';
        $this->annex_name = '';
        $this->annex_description = '';
        $this->annex_content = '';
        $this->resetValidation();
        $this->resetPage();
    }

    public function render()
    {
        return view('livewire.company.contracts.history.annex-others.component')
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function openAddAnnex(){
        $this->annex_id = '';
        $this->annex_name = '';
        $this->annex_description = '';
        $this->annex_content = '';
        $this->annex_content_edit = '';
        $this->emit('show-modal', 'addAnnex');
        $this->resetSearch();
    }

    public function resetSearch()
    {
        $this->query = '';
        $this->annexes = [];
        $this->highlightIndex = 0;
    }
    /*
    public function incrementHighlight()
    {
        if ($this->highlightIndex === count($this->annexes) - 1) {
            $this->highlightIndex = 0;
            return;
        }
        $this->highlightIndex++;
    }

    public function decrementHighlight()
    {
        if ($this->highlightIndex === 0) {
            $this->highlightIndex = count($this->annexes) - 1;
            return;
        }
        $this->highlightIndex--;
    }
    */
    public function updatedQuery()
    {
        $this->annexes = AnnexOther::where('name', 'like', '%' . $this->query . '%')
                            ->orWhere('description', 'like', '%' . $this->query . '%')
                            ->get();
    }

    public function selectAnnex($id)
    {
        if ($id != null) {
            $annex = AnnexOther::find($id);
            $this->annex_id = $annex->id;
            $this->annex_name = $annex->name;
            $this->annex_description = $annex->description;
            $formatter = new NumeroALetras();
            $user=User::find($this->user_id);
            $company = Company::find($this->company_id);
            $contract_user = HistoryContractsUser::find($this->contract_user_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) {
                $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;
            $duration_contract = Carbon::parse($contract_user->start_date)->diffInMonths(Carbon::parse($contract_user->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}",
                    "{Nombre_encargado_firma}","{Cargo_encargado_firma}","{Tipo_doc_encargado_firma}","{Numero_doc_encargado_firma}",
                    "{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($contract_user->start_date)->day . ' de ' . Carbon::parse($contract_user->start_date)->monthName . ' de ' . Carbon::parse($contract_user->start_date)->year;
            if ($contract_user->end_date != null) {
                $end_date_es = Carbon::parse($contract_user->end_date)->day . ' de ' . Carbon::parse($contract_user->end_date)->monthName . ' de ' . Carbon::parse($contract_user->end_date)->year;
            } else {
                $end_date_es = 'No definido';
            }
            $start_date_work_es = Carbon::parse($contract_user->start_date_work)->day . ' de ' . Carbon::parse($contract_user->start_date_work)->monthName . ' de ' . Carbon::parse($contract_user->start_date_work)->year;
            if ($contract_user->end_date_work != null) {
                $end_date_work_es = Carbon::parse($contract_user->end_date_work)->day . ' de ' . Carbon::parse($contract_user->end_date_work)->monthName . ' de ' . Carbon::parse($contract_user->end_date_work)->year;
            } else {
                $end_date_work_es = 'No definido';
            }
            $salary = '$'.number_format($contract_user->salary, 2, '.', ',');

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


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


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

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

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

            $signature_document_type_abb = DataTypeDocument($contract_user->signature_document_type,true);//abreviacion del tipo de documento del encargado de la firma del contrato

            $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,
            $contract_user->signature_full_name, $contract_user->signature_position, $signature_document_type_abb, $contract_user->signature_document_number,
            $user_job_position, $salary, $salary_letras, $profile_employee->pivot->payment_method, $fecha_hoy, $contract_user->place_hired,
            $contract_user->place_work, $start_date_work_es, $end_date_work_es, $start_date_es, $end_date_es, $duration_contract,
            $energy_cost, $maintenance_technology_resources_cost, $phone_cost, $others_cost, $contract_user->no_salary_cost];



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

            $this->annex_content = $new_content;
            $this->resetSearch();
            //$this->emit('item-added', 'addAnnex');
        }

    }

    public function add_user_annex_others(){
        $this->annex_content_edit = $this->annex_content;
        $this->emit('reload-annex-info','reload-modal');
        $this->emit('item-added', 'Anexo Agregado Correctamente');
    }
    public function createAnnex(){

        $rules = [
            'annex_id' => 'required',
            'annex_content_edit' => 'required',
            'signature_validate' => 'required',
            'signature_full_name' => 'required',
            'signature_position' => 'required',
            'signature_document_type' => 'required',
            'signature_document_number' => 'required',
        ];

        $messages = [
            'annex_id.required' => 'Seleccione un Anexo',
            'annex_content_edit.required' => 'El contenido es requerido',
            'signature_validate.required' => 'La firma es requerida',
            'signature_full_name.required' => 'El nombre completo es requerido',
            'signature_position.required' => 'La posición es requerida',
            'signature_document_type.required' => 'El tipo de documento es requerido',
            'signature_document_number.required' => 'El número de documento es requerido',
        ];

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


        if ($this->signature_company == NULL) {
            $this->annex_content_edit = $this->annex_content_edit;
            return redirect()->route('otro-si-contrato-empleado', $this->contract_id)->with([
                'error' => 'Debe Firmar el Contrato',
            ]);
        }

        $annex_other_contract_user = AnnexOthersContractUser::create([
            'annex_other_id' => $this->annex_id,
            'contract_user_id' => $this->contract_user_id,
            'user_id' => $this->selected_user_id,
            'company_id' => $this->company_id,
            'signature_full_name' => $this->signature_full_name,
            'signature_position' => $this->signature_position,
            'signature_document_type' => $this->signature_document_type,
            'signature_document_number' => $this->signature_document_number,
            'content_annex' => $this->annex_content_edit,
            'created_by' => Auth::user()->id,
        ]);

        $image_parts = explode(";base64,", $this->signature_company);
        $image_type_aux = explode("image/", $image_parts[0]);
        $image_type = $image_type_aux[1];
        $image_base64 = base64_decode($image_parts[1]);
        //$this->signature_file->storeAs('storage/users/' .$user_id. '/signature_contracts/' ,$signatureName);
        $folderPath = public_path('storage/users/' .$this->selected_user_id. '/signature_contracts/'.$this->selected_contract_id.'/annex_others/'.$annex_other_contract_user->id.'/');
        if (!file_exists($folderPath)) {
            mkdir($folderPath, 0777, true);
        }
        $signatureName = 'signature_company_'.uniqid().'_'.$annex_other_contract_user->id.'.'.$image_type;
        $file = $folderPath . $signatureName;
        file_put_contents($file, $image_base64);
        /** eliminar partes blancas externas de la firma */
        $im  = imagecreatefromjpeg($file);
        $cropped = imagecropauto($im, IMG_CROP_SIDES);
        if ($cropped !== false) { // in case a new image object was returned
            imagedestroy($im);    // we destroy the original image
            $im = $cropped;       // and assign the cropped image to $im
        }
        $firma = $folderPath . $signatureName;
        imagejpeg($im, $firma);
        imagedestroy($im);
        $annex_other_contract_user->signature_company = $signatureName;
        $annex_other_contract_user->save();
        $message = NotifyMessageCustom(
            $title = 'Tienes un Anexo Otro sí disponible para firmar',
            $body = 'Tienes un Anexo Otro sí disponible para firmar en la plataforma.',
            $url = route('empleado-contrato-otro-si', $annex_other_contract_user->id),
            $button_text = 'Ver Anexo Otro sí',
            $via_from = 'Company',
            $user_to_id = $this->selected_user_id,
            $user_from_id = Auth::user()->id
        );
        return redirect()->route('contratos-empleados.historial', $this->selected_user_id)->with([
            'item-updated' => 'Anexo Agregado Correctamente',
        ]);
    }

}
