<?php

namespace App\Http\Livewire;

use App\Models\AnnexOther;
use App\Models\AnnexOthersContractUser;
use App\Models\Company;
use App\Models\Contract;
use App\Models\HistoryContractsUser;
use App\Models\User;
use App\Traits\OrderByTable;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Livewire\WithFileUploads;

use App\Notifications\MessageSent;

class Employee_ContractAnnexOthersController extends Component
{
    use WithFileUploads;
    use OrderByTable;

    public $user, $first_name, $last_name;
    public $sel_annex_content, $selected_contract_id, $company_id, $sel_contract_name, $sel_contract_type, $sel_contract_sub_type, $sel_contract_description;
    public $selectedCompany, $start_date, $end_date, $signature_employee, $signature_employee_saved;

    public $breadcrumb_show = true;


    public function mount($id)
    {
        if ($id == null) {
            return redirect()->route('empleado-contratos');
        }
        //$contract_user = HistoryContractsUser::find($id);
        $contract_annex_user = AnnexOthersContractUser::find($id);
        $this->sel_annex_content ='';
        if ($contract_annex_user != NULL) {
            UserAuthPermission('Employee_index');
            $user = User::find(auth()->user()->id);
            EmployeeOtherCompany($user->id); //Verifica que el empleado pertenezca a la empresa

            if ($contract_annex_user->signature_employee != NULL) {
                return redirect()->route('empleado-contratos')->with('error', 'El Anexo Otro Sí ya tiene firma del empleado');
            }

            $this->user = $user;
            $this->user_id = $user->id;
            $this->first_name = $user->first_name;
            $this->last_name = $user->last_name;
            $this->selected_annex_id = $id;
            $this->contract_user_id = $contract_annex_user->contract_user_id; //id del contrato asociado al anexo otro si
            $this->sel_annex_name = AnnexOther::find($contract_annex_user->annex_other_id)->name; //nombre del anexo otro si
            //dd($contract_annex_user);
            $history_contract_user = HistoryContractsUser::find($this->contract_user_id);
            //dd($history_contract_user);
            $contract_info = Contract::find($history_contract_user->contract_id);
            $this->sel_contract_name = $contract_info->name;
            $this->sel_contract_type = $contract_info->type;
            $this->sel_contract_sub_type = $contract_info->sub_type;
            $this->signature_employee = $contract_annex_user->signature_employee;
            $this->signature_employee_saved = $contract_annex_user->signature_employee;
            $this->sel_annex_content = $contract_annex_user->content_annex;
            //firma info
            $signature_user = $contract_annex_user->created_by;
            $signature_company = $contract_annex_user->signature_company;
            $signature_full_name = $contract_annex_user->signature_full_name;
            $signature_position = $contract_annex_user->signature_position;
            $signature_document_type = DataTypeDocument($contract_annex_user->signature_document_type, true);// tipo de documento abreviado
            $signature_document_number = $contract_annex_user->signature_document_number;
            $signature_full_name_employee = $user->first_name . ' ' . $user->last_name;
            $signature_document_type_employee = DataTypeDocument($user->document_type, true);// tipo de documento abreviado
            $signature_document_number_employee = $user->document;

            $signature_img_tag = '<img src="'.asset('storage/users/' .$this->user_id. '/signature_contracts/'.$this->contract_user_id.'/annex_others/'.$this->selected_annex_id.'/'.$signature_company).'" alt="Firma" class="signature_pdf">';
            $signature_img_tag_employee = '';
            $signature_content_html=
            '<table border="0" cellpadding="1" cellspacing="1" class="col-50 no-border" style="width:100%">'
                .'<tbody>'
                    .'<tr>'
                        .'<td>EL EMPLEADOR</td>'
                        .'<td>EL TRABAJADOR</td>'
                    .'</tr>'
                    .'<tr>'
                    .' <td>'.$signature_img_tag.'</td>'
                        .'<td>'.$signature_img_tag_employee.'</td>'
                    .'</tr>'
                    .'<tr>'
                        .'<td>'.$signature_full_name.'</td>'
                        .'<td>'.$signature_full_name_employee.'</td>'
                    .'</tr>'
                    .'<tr>'
                        .'<td>'.$signature_document_type.' '.$signature_document_number.'</td>'
                        .'<td>'.$signature_document_type_employee.' '.$signature_document_number_employee.'</td>'
                    .'</tr>'
                    .'<tr>'
                        .'<td>'.$signature_position.'</td>'
                        .'<td>Trabajador</td>'
                    .'</tr>'
                .'</tbody>'
            .'</table>';

            $this->sel_annex_content.= $signature_content_html;


            $company = Company::find(Auth::user()->CompanyId());
            $this->company_id = $company->id;
            $this->pageTitle = 'Firmar Anexo Otro Sí';
            $this->componentName = 'Empleado';
            $this->company_id = $company->id;
            AnnexUserOtherCompany($contract_annex_user->id, $this->company_id);// validar que el anexo otro si pertenezca a la empresa y empleado


        }
        else {
            return redirect()->route('empleado-contratos')->with('error', 'No se encontró el Anexo Otro Sí');
        }
    }

    public function render()
    {
        $annex_content = $this->sel_annex_content;

        return view('livewire.employee.contracts.annex-others.component', compact('annex_content'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function saveSignature(){
        if ($this->signature_employee == NULL) {
            return redirect('/empleado/empleado-contrato-otro-si/'.$this->selected_annex_id)->with('error', 'Debe ingresar una firma');
        }

        $contract_annex_user = AnnexOthersContractUser::find($this->selected_annex_id);
        if ($contract_annex_user->signature_employee == NULL) {


            $user_id = $this->user_id;

            $image_parts = explode(";base64,", $this->signature_employee);
            $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/' .$user_id. '/signature_contracts/'.$this->contract_user_id.'/annex_others/'.$contract_annex_user->id.'/');
                if (!file_exists($folderPath)) {
                mkdir($folderPath, 0777, true);
            }

            $signatureName = 'signature_employee_'.uniqid().'_'.$this->selected_annex_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);
            /** end */
            $contract_annex_user->signature_employee = $signatureName;
            $contract_annex_user->save();

            $this->emit('saved-signature');
            foreach (AdminsCompany($this->company_id) as $admin) {
                $message = NotifyMessageCustom(
                    $title ='El Empleado '.$this->first_name.' '.$this->last_name.' ha firmado el Anexo Otro Sí',
                    $body = 'El Anexo '.$this->sel_annex_name.' ha sido firmado por el empleado '.$this->first_name.' '.$this->last_name,
                    $url = route('otros-si-contrato-empleado', $this->user_id),
                    $button_text = 'Ver Anexos del Empleado',
                    $via_from = 'Employee', //Employee, Company, Soporte, SuperAdmin
                    $user_id_to = $admin->user_id,
                    $user_id_from = Auth::user()->id
                );
            }
            return redirect()->route('empleado-contratos')->with('updated', 'Anexo otro sí firmado');
        }

    }



}
