<?php

use App\Models\Company;
use App\Models\HistoryContractsUser;
use App\Models\User;
use App\Models\WorkCertificate;
use App\Notifications\MessageSent;
use Carbon\Carbon;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;

if (! function_exists('NotifyMessageCustom')) {
    function NotifyMessageCustom($title, $body, $url, $button_text, $via_from, $user_id_to, $user_id_from, $attached_file=null)
    {
        $message = (object)collect([
            'title' => $title,
            'body' => $body,
            'url' => $url,
            'button_text' => $button_text,
            'via_from' => $via_from, //Employee, Company, Soporte, SuperAdmin
            'user_id_to' => $user_id_to,
            'user_id_from' => $user_id_from,
            'attached_file' => $attached_file,
        ])->all();

        $user = User::find($user_id_to);

        $user->notify(new MessageSent($message));
    }
}

/*** Descargar certificado laboral */
if (! function_exists('downloadCertificatePDF')){
    function downloadCertificatePDF($id)
    {
        $work_certificate = WorkCertificate::find($id);
        if ($work_certificate != null){
            if ($work_certificate->status == '1'){ //Si el certificado esta aprobado
                $user = User::find($work_certificate->user_id);
                $company_id = $work_certificate->company_id;
                $info_contract = HistoryContractsUser::select('job_position', 'salary_type', 'base_salary', 'performance_factor',
                                                                'salary', 'payment_method', 'start_date', 'end_date',
                                                                'contracts.type')
                                                    ->join('contracts', 'contracts.id', '=', 'history_contracts_users.contract_id')
                                                    ->where('user_id', $user->id)
                                                    ->where('company_id', $company_id)
                                                    ->where('history_contracts_users.status', '!=', '0')
                                                    ->orderBy('history_contracts_users.id', 'desc')->get();
                if ($info_contract != null){

                    $company = Company::find($company_id);
                    if ($user->gender_user == 'Masculino')
                        $prefix = 'el señor';
                    else
                        $prefix = 'la señora';


                    $reviewed = User::find($work_certificate->reviewed_by);
                    if ($reviewed->job_position_administrative_area != null) //Si el usuario tiene cargo administrativo asignado en su perfil
                        $job_position_administrative_area = $reviewed->job_position_administrative_area;
                    else
                        $job_position_administrative_area = $reviewed->getRoleNames()[0]; //Si no, asignamos el nombre del rol administrativo

                    $info =[
                        'requested_to' => $work_certificate->requested_to,
                        'first_name' => $user->first_name,
                        'last_name' => $user->last_name,
                        'city_name' => $company->city_name,
                        'company_name' => $company->name,
                        'solicitation_date' => $work_certificate->solicitation_date,
                        'document_type_name' => $user->document_type_name,
                        'document_number' => $user->document,
                        'document_expedition' => $user->document_expedition,
                        'prefix' => $prefix,
                        'salary_include' => $work_certificate->salary_include,
                        'reviewed_id' => $reviewed->id,
                        'reviewed_document_type_name' => $reviewed->document_type_name_abbreviation,
                        'reviewed_document_number' => $reviewed->document,
                        'reviewed_name' => $reviewed->first_name.' '.$reviewed->last_name,
                        'reviewed_position' => $job_position_administrative_area,
                        'reviewed_signature' => $reviewed->signature,
                    ];

                    $info = ['info' => $info];
                    $info_contract = ['info_contract' => $info_contract];
                    //dd($info_contract);
                    $pdf = PDF::loadView('pdf.work_certificate_employee', $info, $info_contract);
                    /*
                    return response()->streamDownload(function() use ($pdf) {
                        echo $pdf;
                    }, 'certificado_laboral_'.$user->first_name.'_'.$user->last_name.'_'.Carbon::now()->format('d-m-Y').'.pdf');
                    */
                    return $pdf->stream('certificado_laboral_'.$user->first_name.'_'.$user->last_name.'_'.Carbon::now()->format('d-m-Y').'.pdf');


                }
                else{
                    return redirect()->back()->with('error', 'No se encontró información para el usuario seleccionado.');
                }
            }
        }


    }
}

/*** función para mostrar en días, horas y minutos la diferencia entre dos fechas */
if (! function_exists('getDifferenceDateWithDays')){
    function getDifferenceDateWithDays($date, $days)
    {
        if ($date == null){
            $difference = $days == 1 ? '1 día' : $days.' días';
            return array('difference' => $difference, 'status' => '2');
        }
        $date_now = Carbon::now()->subDays($days); //Fecha actual menos los días que se pasan como parámetro
        //dd($date, $date_now);
        if ($date_now >= $date){
            //dd($date_now);
            $difference = '0 días';
            return array('difference' => $difference, 'status' => '0');
        }
        else {
            //dd($date_now, $date);
            $difference = Carbon::parse($date)->diffInSeconds($date_now);
            //dd($difference);
            $difference = gmdate('d:H:i:s', $difference);
            //dd($difference);
            $difference = explode(':', $difference);
            $difference[0] == 1 ? $difference[0] = $difference[0].' día' : $difference[0] = $difference[0].' días';
            $difference[1] == 1 ? $difference[1] = $difference[1].' hora' : $difference[1] = $difference[1].' horas';
            $difference[2] == 1 ? $difference[2] = $difference[2].' minuto' : $difference[2] = $difference[2].' minutos';
            $difference = $difference[0].', '.$difference[1].' y '.$difference[2];

            return array('difference' => $difference, 'status' => '1');
        }

    }
}

/** función para combinar dos arrays en uno solo, conservando los del primero y agregando los del segundo */
if (! function_exists('combineArray')){
    function combineArray($array_1, $array_2)
    {
        $array_final = array();
        foreach ($array_1 as $key => $value){
            $array_final[$key] = $value;
        }
        foreach ($array_2 as $key => $value){
            $array_final[$key] = $value;
        }
        return $array_final;
    }
}

/** función para obtener la lista de nombre de los anexos de un contrato de un usuario */
if (! function_exists('getAnnexesContractUser')){
    function getAnnexesContractUser($contract_id, $user_id, $company_id)
    {
        $annexes = DB::table('annex_others')
                            ->join('annex_others_contract_users', 'annex_others_contract_users.annex_other_id', '=', 'annex_others.id')
                            ->where('annex_others_contract_users.contract_user_id', $contract_id)
                            ->where('annex_others_contract_users.user_id', $user_id)
                            ->where('annex_others_contract_users.company_id', $company_id)
                            ->get();
        return array('annexes' => $annexes, 'count' => count($annexes));
    }
}

/**función que crea las tablas html para las firmas de los anexos de un contrato de un usuario */
if (! function_exists('createTableAnnexesSignatures')){
    function createTableAnnexesSignatures($annex){


        $annex_user_id = $annex['annex_user_id'];
        $contract_user_id = $annex['contract_user_id'];
        $signature_company = $annex['signature_company'];
        $signature_full_name_company =  $annex['signature_full_name_company'];
        $signature_position_company = $annex['signature_position_company'];
        $signature_document_type_company = DataTypeDocument($annex['signature_document_type_company'],true);
        $signature_document_number_company = $annex['signature_document_number_company'];
        $user_id_employee = $annex['user_id_employee'];
        $signature_employee = $annex['signature_employee'];
        $signature_full_name_employee = $annex['signature_full_name_employee'];
        $signature_document_type_employee = DataTypeDocument($annex['signature_document_type_employee'],true);
        $signature_document_number_employee = $annex['signature_document_number_employee'];

        $signature_img_tag_company='';
        $signature_img_tag_employee='';
        if ($signature_company != null){
            $signature_img_tag_company = '<img src="'.asset('storage/users/' .$user_id_employee. '/signature_contracts/'.$contract_user_id.'/annex_others/'.$annex_user_id.'/'.$signature_company).'" alt="Firma" class="signature_pdf">';
        }
        if($signature_employee != null){
            $signature_img_tag_employee = '<img src="'.asset('storage/users/' .$user_id_employee. '/signature_contracts/'.$contract_user_id.'/annex_others/'.$annex_user_id.'/'.$signature_employee).'" alt="Firma" class="signature_pdf">';
        }


        $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_company.'</td>'
                    .'<td>'.$signature_img_tag_employee.'</td>'
                .'</tr>'
                .'<tr>'
                    .'<td>'.$signature_full_name_company.'</td>'
                    .'<td>'.$signature_full_name_employee.'</td>'
                .'</tr>'
                .'<tr>'
                    .'<td>'.$signature_document_type_company.' '.$signature_document_number_company.'</td>'
                    .'<td>'.$signature_document_type_employee.' '.$signature_document_number_employee.'</td>'
                .'</tr>'
                .'<tr>'
                    .'<td>'.$signature_position_company.'</td>'
                    .'<td>Trabajador</td>'
                .'</tr>'
            .'</tbody>'
        .'</table>';

        return $signature_content_html;

    }
}
