<?php
namespace App\Http\Livewire;

use App\Models\Company;
use App\Models\Contract;
use App\Models\HistoryContractsUser;
use App\Models\User;
use App\Traits\OrderByTable;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Livewire\WithFileUploads;
use Livewire\WithPagination;

class Company_ContractsUsersSignatureController extends Component
{
    use WithPagination;
    use WithFileUploads;
    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, $signature_company, $signature_company_saved;
    public $sel_contract_name, $sel_contract_type, $sel_contract_sub_type, $sel_contract_description, $sel_contract_content;
    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 $signature_full_name, $signature_position, $signature_document_type, $signature_document_number;
    public $breadcrumb_show = true;

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

        UserAuthPermission('Company_contracts_users_add_signature');
        $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 = 'Empleado';
            $this->componentName = 'Contrato';

            $contract_info = Contract::find($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->status_contract = $contract_user->status;

            $company = Company::find(Auth::user()->CompanyId());
            $this->company_id = $company->id;
            if(ContractUserOtherCompany($contract_user->id, $this->company_id, true)[0] == NULL){
                $this->emit('item-error', ContractUserOtherCompany($contract_user->id, $this->company_id, true)[1]);
                return false;
            }
            $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;

            $company_plan_id = $company->plan->id;
            UserAuthPermission('ContractEmployee_pdf');

            EmployeeOtherCompany($this->selected_user_id); // Verificamos si el empleado pertenece a otra empresa


            $this->sel_contract_content = $contract_user->content_contract;

            if ($request->session()->get('item-updated') == 'Firma guardada') {
                $this->emit('item-updated', session()->get('item-updated'));
                $request->session()->forget('item-updated');
            }

        }
        else {
            return redirect()->route('dashboard')->with('error', 'No se encontró el contrato');
        }
    }


    public function render()
    {
        $contract_user = $this->sel_contract_content;
        return view('livewire.company.contracts.signature.component',compact('contract_user'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }


    public function SignatureEmployee()
    {

    }
    public function saveSignature(){
        if ($this->signature_company == NULL) {
            return redirect()->route('contratos-empleados.firmar',$this->selected_contract_id)->with('error', 'Debe ingresar la firma');
        }

        $contract_user = HistoryContractsUser::find($this->selected_contract_id);
        if ($contract_user->status == '0' && $contract_user->signature_company == NULL) {
            $rules=[
                'signature_full_name' => 'required',
                'signature_position' => 'required',
                'signature_document_type' => 'required',
                'signature_document_number' => 'required',
            ];
            $messages=[
                'signature_full_name.required' => 'El campo Nombre completo es obligatorio',
                'signature_position.required' => 'El campo Cargo es obligatorio',
                'signature_document_type.required' => 'El campo Tipo de documento es obligatorio',
                'signature_document_number.required' => 'El campo Número de documento es obligatorio',
            ];
            $this->validate($rules, $messages);

            $user_id = $contract_user->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/' .$user_id. '/signature_contracts/'.$this->selected_contract_id.'/');
                if (!file_exists($folderPath)) {
                mkdir($folderPath, 0777, true);
            }
           // dd($folderPath);
            $signatureName = 'signature_company_'.uniqid().'_'.$this->selected_contract_id.'.'.$image_type;
            $document_type = DataTypeDocument($this->signature_document_type, true);// tipo de documento abreviado
            $param = ["{Firma_empresa}","{Nombre_encargado_firma}","{Cargo_encargado_firma}","{Tipo_doc_encargado_firma}","{Numero_doc_encargado_firma}"];
            $firma_img_tag = '<img src="'.asset('storage/users/' .$user_id. '/signature_contracts/'.$this->selected_contract_id.'/'.$signatureName).'" alt="Firma" class="signature_pdf">';
            $data=[$firma_img_tag, $this->signature_full_name,$this->signature_position, $document_type, $this->signature_document_number];
            $new_content = str_replace($param, $data, $contract_user->content_contract);
            $contract_user->content_contract = $new_content;


            $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_user->signature_company = $signatureName;
            $contract_user->signature_full_name = $this->signature_full_name;
            $contract_user->signature_position = $this->signature_position;
            $contract_user->signature_document_type = $this->signature_document_type;
            $contract_user->signature_document_number = $this->signature_document_number;
            $contract_user->save();
            $this->sel_contract_content = $contract_user->content_contract;
            $this->emit('item-updated', 'Firma guardada');
            $this->refreshComponent();
            //dd($this->signature_employee);
        }

    }
    public function refreshComponent() {
        return redirect()->route('contratos-empleados.firmar',$this->selected_contract_id)->with('item-updated', 'Firma guardada');

    }
    /*
    public function store(Request $request)
    {
        $folderPath = public_path('upload/');

        $image_parts = explode(";base64,", $request->signed);

        $image_type_aux = explode("image/", $image_parts[0]);

        $image_type = $image_type_aux[1];

        $image_base64 = base64_decode($image_parts[1]);

        $signature = uniqid() . '.'.$image_type;

        $file = $folderPath . $signature;

        file_put_contents($file, $image_base64);

        $save = new Signature;
        $save->name = $request->name;
        $save->signature = $signature
        $save->save();


        return back()->with('success', 'Form successfully submitted with signature');
    }
    */

}
