<?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 Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Livewire\WithFileUploads;

use App\Notifications\MessageSent;

class Employee_ContractSignatureController extends Component
{
    use WithFileUploads;
    use OrderByTable;

    public $user, $first_name, $last_name;
    public $sel_contract_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);

        if ($contract_user != NULL) {
            UserAuthPermission('Employee_index');
            $user = User::find(auth()->user()->id);
            EmployeeOtherCompany($user->id); //Verifica que el empleado pertenezca a la empresa

            if ($contract_user->active_signature_employee == 0) {
                return redirect()->route('empleado-contratos')->with('error', 'El contrato no tiene activa la opción de firma');
            }
            if ($contract_user->signature_employee != NULL) {
                return redirect()->route('empleado-contratos')->with('error', 'El contrato 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_contract_id = $id;
            $contract_id = $contract_user->contract_id; //id del contrato modelo
            $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->signature_employee = $contract_user->signature_employee;
            $this->signature_employee_saved = $contract_user->signature_employee;
            $this->sel_contract_content = $contract_user->content_contract;
            $this->status_contract = $contract_user->status;

            $company = Company::find(Auth::user()->CompanyId());
            $this->company_id = $company->id;
            $this->pageTitle = 'Firmar Contrato';
            $this->componentName = 'Empleado';
            $this->company_id = $company->id;
            ContractUserOtherCompany($contract_user->id, $this->company_id);// validar que el contrato pertenezca a la empresa y empleado


        }
        else {
            return redirect()->route('empleado-contratos')->with('error', 'No se encontro el contrato');
        }
    }

    public function render()
    {
        $contract_user = $this->sel_contract_content;

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

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

        $contract_user = HistoryContractsUser::find($this->selected_contract_id);
        if ($contract_user->status == '0' && $contract_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->selected_contract_id.'/');
                if (!file_exists($folderPath)) {
                mkdir($folderPath, 0777, true);
            }

            $signatureName = 'signature_employee_'.uniqid().'_'.$this->selected_contract_id.'.'.$image_type;

            $param = ["{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];
            $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_employee = $signatureName;
            $contract_user->save();
            $this->sel_contract_content = $contract_user->content_contract;
            $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 contrato',
                    $body = 'El contrato '.$this->sel_contract_name.' ha sido firmado por el empleado '.$this->first_name.' '.$this->last_name,
                    $url = route('contratos-empleados.firmar', $this->selected_contract_id),
                    $button_text = 'Ver Contrato',
                    $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', 'Contrato firmado');
        }

    }



}
