<?php

namespace App\Http\Controllers;

use App\Custom\SQLConnection;
use App\Models\Mailer;
use Illuminate\Support\Facades\Session;
use App\Custom\Misc; 
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
use DB;
use DateTime;
use stdClass;


class EmailController extends Controller  {


    public static function emailHRAGB($obj,$to,$referencia,$usuario_creador,$operador_cancela=NULL){
        //
        $app_id = Session::get('webdata')['app_id'];
        $servicio = 10; 
        $cliente = 738156811; 
        $web = SQLConnection::backendStoreProcedure('multi_web_', array('mail_cliente', NULL, $app_id, $cliente, null, $servicio), 'selectOne');
        $sender = $web->sender ?? 'servicio@fidelitas.com.ar';
        //
        $url = $web->http_host ?? 'https://www.inquirovitae.com';
        $protocol = (strpos($url, 'https://', 0)===0) ? ('https' . chr(58) . chr(47) . chr(47)) : ('https' . chr(58) . chr(47) . chr(47));
        $url = (strpos($url, 'http', 0)===0) ? $url : $protocol . $url ;
        $logo_url = (!empty($url) and !empty($web->uri_email_logo)) ? ((strpos($web->uri_email_logo, 'http', 0)===0) ? $web->uri_email_logo : ($url . $web->uri_email_logo)) : 'https://www.fidelitas.com.ar/img/mail_logo.png';
        //
        $mail_subject = NULL;
        $texto = NULL;
        if ( $obj == 'K' ){
            // Informe terminado
            $texto = "Dear <b>$usuario_creador</b> <br>
            Order <i>$referencia</i> has been processed and closed. <br>
            Please contact HireRight.support@inquirovitae.com if you require any further information.";
            $mail_subject = "Your order $referencia has been completed";
        } elseif ( $obj == 'R' ){
            // Informe Observado
            $texto = "Dear <b>$usuario_creador</b> <br>
            Data inconsistency has been detected on order <i>$referencia</i>, please review. <br>
            Please contact HireRight.support@inquirovitae.com if you require any further information.";
            $mail_subject = "Your order $referencia under Observation";
            // Informe Cancelado
        } elseif ( $obj == 'C' ){
            $texto = "Dear <b>$usuario_creador</b> <br>
            Order <i>$referencia</i> has been rejected by <strong>$operador_cancela</strong>. <br>
            Please contact HireRight.support@inquirovitae.com if you require any further information.";
            $mail_subject = "Your order $referencia has been rejected";
        } elseif ( $obj == 'E' ){
            // Informe En proceso
            $texto = "Dear <b>$usuario_creador</b> <br>
            Order <i>$referencia</i> is being processed. <br>
            Please contact HireRight.support@inquirovitae.com if you require any further information.";
            $mail_subject = "Your order $referencia is under process";
        } elseif ( $obj == 'N' && !is_null($operador_cancela) ){
            // Informe Anulado
            // $texto = "Dear <b>$usuario_creador</b> <br>
            // Order <i>$referencia</i> has been canceled by <strong>$operador_cancela</strong>. <br>
            // Please contact “HireRight.support@inquirovitae.com” if you require any further information.";
            $texto = "Dear <b>$usuario_creador</b> <br>
            // Order <i>$referencia</i> has been cancelled. <br>
            // Please contact HireRight.support@inquirovitae.com if you require any further information.";
            $mail_subject = "Your order $referencia has been Cancelled";
        }
        //
        if ( !is_null($texto) ){
            $texto = "
                <table width='100%' border='0' cellspacing='0' cellpadding='3' class='HeaderTable'>
                <tr>
                    <td valign='top' valign='middle'><img src='$logo_url' alt='' border='0' height='34'></td>
                </tr>
                <tr>
                    <td>
                        <br />
                        $texto
                        <br />
                        <br />
                    </td>
                </tr>
                </table>
            ";
            //
            Mailer::from($sender);
            Mailer::to($to);
            Mailer::bcc('soporteled@fidelitas.com.ar');
            Mailer::replyto('soporteled@fidelitas.com.ar');
            Mailer::text($texto,$mail_subject);
            Mailer::send();
            return true;
        }
        //
        return false;
    }
    public static function emailHR($obj, $to, $referencia, $usuario_creador, $operador_cancela = NULL) {
        //
        $app_id = Session::get('webdata')['app_id'];
        $servicio = 10;
        $cliente = 738156811;
        $web = SQLConnection::backendStoreProcedure('multi_web_', array('mail_cliente', NULL, $app_id, $cliente, null, $servicio), 'selectOne');
        $sender = $web->sender ?? 'servicio@fidelitas.com.ar';
        //
        $url = $web->http_host ?? 'https://www.inquirovitae.com';
        $protocol = (strpos($url, 'https://', 0) === 0) ? ('https' . chr(58) . chr(47) . chr(47)) : ('https' . chr(58) . chr(47) . chr(47));
        $url = (strpos($url, 'http', 0) === 0) ? $url : $protocol . $url;
        $logo_url = (!empty($url) and !empty($web->uri_email_logo)) ? ((strpos($web->uri_email_logo, 'http', 0) === 0) ? $web->uri_email_logo : ($url . $web->uri_email_logo)) : 'https://www.fidelitas.com.ar/img/mail_logo.png';
        //
        $mail_subject = NULL;
        $texto = NULL;
        if ($obj == 'K') {
            // Informe terminado
            $texto = "Dear <b>$usuario_creador</b> <br>
            Your order <i>$referencia</i> has been processed and closed. <br>
            Please contact HireRight.support@inquirovitae.com if you require any further information.";
            $mail_subject = "Your order $referencia has been completed";
        } elseif ($obj == 'R') {
            // Informe Observado
            $texto = "Dear <b>$usuario_creador</b> <br>
            Data inconsistency has been detected on your order <i>$referencia</i>, please review it. <br>
            Please contact HireRight.support@inquirovitae.com if you require any further information.";
            $mail_subject = "Your order $referencia has been put under observation";
            // Informe Cancelado
        } elseif ($obj == 'C') {
            $texto = "Dear <b>$usuario_creador</b> <br>
            Your order <i>$referencia</i> has been rejected by <strong>$operador_cancela</strong>. <br>
            Please contact HireRight.support@inquirovitae.com if you require any further information.";
            $mail_subject = "Your order $referencia has been rejected";
        } elseif ($obj == 'E') {
            // Informe En proceso
            $texto = "Dear <b>$usuario_creador</b> <br>
            Your order <i>$referencia</i> is being processed. <br>
            Please contact HireRight.support@inquirovitae.com if you require any further information.";
            $mail_subject = "Your order $referencia is being processed";
        } elseif ($obj == 'N' && !is_null($operador_cancela)) {
            // Informe Anulado
            // $texto = "Dear <b>$usuario_creador</b> <br>
            // Order <i>$referencia</i> has been canceled by <strong>$operador_cancela</strong>. <br>
            // Please contact “HireRight.support@inquirovitae.com” if you require any further information.";
            $texto = "Dear <b>$usuario_creador</b> <br>
            // Your order <i>$referencia</i> has been cancelled. <br>
            // Please contact HireRight.support@inquirovitae.com if you require any further information.";
            $mail_subject = "Your order $referencia has been cancelled";
        } elseif ($obj == 'R_TICKET') {
            // Informe En proceso
            if (!is_null($operador_cancela)) {
                $texto = "Dear <b>$usuario_creador</b> <br>
                Your ticket from the order <i>$referencia</i> has been replied by <strong>$operador_cancela</strong>. <br>
                Please contact HireRight.support@inquirovitae.com if you require any further information.";
                $mail_subject = "Your tikcet from the order $referencia has been replied";
            } else {
                $texto = "Dear <b>$usuario_creador</b> <br>
                Your tikcet from the order <i>$referencia</i> has been replied. <br>
                Please contact HireRight.support@inquirovitae.com if you require any further information.";
                $mail_subject = "Your tikcet from the order $referencia has been replied";
            }
        }
        //
        if (!is_null($texto)) {
            $texto = "
                <table width='100%' border='0' cellspacing='0' cellpadding='3' class='HeaderTable'>
                <tr>
                    <td valign='top' valign='middle'><img src='$logo_url' alt='' border='0' height='34'></td>
                </tr>
                <tr>
                    <td>
                        <br />
                        $texto
                        <br />
                        <br />
                    </td>
                </tr>
                </table>
            ";
            //
            Mailer::from($sender);
            Mailer::to($to);
            Mailer::bcc('HireRight.support@inquirovitae.com');
            Mailer::replyto('HireRight.support@inquirovitae.com');
            Mailer::text($texto, $mail_subject);
            Mailer::send();
            return true;
        }
        //
        return false;
    }
	public static function encryptString() {
		return (encrypt(Request::input('s')));
	} 
	public static function decryptString() {
		return (decrypt(Request::input('s')));
	} 
    
    //public static function enviarMailAlta($contraparte=null, $link_expira='', $email_alt='', $link_forced = false) 
    public static function enviarMail($app_key = 'EMAIL-LED', $tipo = 'ALTA', $tipo2 = '', $contraparte = '', $link_expira = '', $email_alt = '', $link_forced = false, $doc_id = NULL, $transact_id = NULL, $to_array = []) {
        if ($contraparte == null) {
            return false;
        }

        //$bcc = (env('LED_TEST_MODE') == true) ? NULL : 'soporteled@fidelitas.com.ar';
        $bcc = 'soporteled@fidelitas.com.ar';
        $replyto = 'soporteled@fidelitas.com.ar';

        if ($app_key == 'IV') {
            $qcontrap = SQLConnection::backendStoreProcedure('IV_busquedas_', array('search', NULL, $contraparte), 'selectOne');
        } else {
            if ($app_key == 'EMAIL-IMPE') {
                $qcontrap = SQLConnection::backendStoreProcedure('Imperium_cliente_contraparte_led', array('buscar_contratista_imperium', $contraparte), 'selectOne');
                //$bcc = 'soporte@imperium.com.ar';
                $bcc = 'soporte@fidelitas.com.ar';

                $replyto = 'soporte@imperium.com.ar';
            } else {
                $qcontrap = SQLConnection::backendStoreProcedure('LN_contrapartes_', array('select', $contraparte, null, null, null, null, null, null, null, NULL, NULL, null, null, null, null), 'selectOne');
            }
        }

        //
        if ($qcontrap->cliente == 1226057645) // BBVA
        {
            $bcc = 'soportevrm@fidelitas.com.ar';
            $replyto = 'soportevrm@fidelitas.com.ar';
        }


        if ($qcontrap->cliente == 5546348) {
            $qcontrap->nombre_cliente = ($qcontrap->country_code == 'PY') ? 'AMX PARAGUAY S.A.' : (($qcontrap->country_code == 'UY') ? 'AM Wireless Uruguay S.A.' : $qcontrap->nombre_cliente);
            $cc = 'evaluaciondeproveedores@claro.com.ar';
        }



        $tipo = strtoupper($tipo);
        if ($tipo == '') {
            $tipo = NULL;
        }
        $tipo2 = strtoupper($tipo2);
        if ($tipo2 == '') {
            $tipo2 = NULL;
        }
        if ($app_key == 'IV') {
            $app_id = 6;
            $servicio = 10;
            $cliente = $qcontrap->cliente;
            $web = SQLConnection::backendStoreProcedure('multi_web_', array('mail_cliente', NULL, $app_id, $cliente, null, $servicio), 'selectOne');
            $idioma = $qcontrap->idioma ?? 'spa';
            if ($idioma == 'eng') {
                $web->mensaje = str_replace(Chr(13) . Chr(10), '<br />', $web->body_eng);
                $web->asunto = $web->subj_eng;
            } elseif ($idioma == 'por') {
                $web->mensaje = str_replace(Chr(13) . Chr(10), '<br />', $web->body_por);
                $web->asunto = $web->subj_por;
            } else {
                $web->mensaje = str_replace(Chr(13) . Chr(10), '<br />', $web->body_spa);
                $web->asunto = $web->subj_spa;
            }

        } else {
            $web = SQLConnection::backendStoreProcedure('multi_web_', array('mail_contraparte', null, null, null, null, null, $contraparte, $app_key, $tipo, $tipo2), 'selectOne');
        }
        /*----------------------------------------------------------------*/
        /* 08/10/2024: Si tenemos un nombre especial como nombre de filial, 
               usamos ese nombre como nombre del cliente, 
               tanto en el asunto como en el cuerpo del mensaje. 
        */
        if (!empty($qcontrap->nombre_filial)) {
            $web->nombre_cliente = $qcontrap->nombre_filial;
        }
        /*----------------------------------------------------------------*/

        /* AGB */
        $body = self::generateMailBody($app_key, $qcontrap, $web);
        $content = self::generateMailContent($app_key, $qcontrap, $web, $link_expira, $doc_id, $transact_id);
        $mail_subject = self::generateMailSubject($app_key, $qcontrap, $web);
        //$mail_subject = 'NUEVOS REQUERIMENTOS - ' . $mail_subject; 

        //var_dump($qcontrap);die();


        // Reemplazo el contenido del mail
        $mail_content = str_replace(['%%EMAIL_CONTENT%%'], [$content], $body);

        $from = $web->sender ?? 'servicio@fidelitas.com.ar';

       
        /*  
        if ($email_alt !== '' and $email_alt !== null) {
            $to[] = trim($email_alt);
        } else {
            if (!empty($to_array)) {
                $to = $to_array;
            } else {
                $to[] = trim($qcontrap->email_contacto);
                if (!is_null($qcontrap->email_ejecutivo_cuenta) && !empty($qcontrap->email_ejecutivo_cuenta)) {
                    $to_mails = explode(",", trim($qcontrap->email_ejecutivo_cuenta));
                    $to = array_merge($to_mails, $to);
                    //$to[] = trim($qcontrap->email_ejecutivo_cuenta) ;                 
                }
            }

        }

  
        if (empty($to)) {
            $to[] = (env('LED_TEST_MODE') == true) ? env('LED_TEST_EMAIL_ADDR') : (($email_alt == '') ? trim($qcontrap->email_contacto) : trim($email_alt));
        }
        */

        /* 09/01/2025: Ahora puede venir mas de una direccion de mail, separada por coma */
        $to = [];
        if ( ( env('LED_TEST_MODE') == true) ) {
            $to[] = env('LED_TEST_EMAIL_ADDR');
        } else {
            if ($email_alt !== '' and $email_alt !== null) {
                $email_alt = str_replace(' ','',$email_alt);
                $email_alt = str_replace(';',',',$email_alt);
                $to = explode(",", trim($email_alt));
            } else {
                if (!empty($to_array)) {
                    $to = $to_array;
                } else {
                    if (!is_null($qcontrap->email_contacto) && !empty($qcontrap->email_contacto)) {
                        $qcontrap->email_contacto = str_replace(' ','',$qcontrap->email_contacto);
                        $qcontrap->email_contacto = str_replace(';',',',$qcontrap->email_contacto);
                        $to = explode(",", trim($qcontrap->email_contacto));
                    }

                    if (!is_null($qcontrap->email_ejecutivo_cuenta) && !empty($qcontrap->email_ejecutivo_cuenta)) {
                        $qcontrap->email_ejecutivo_cuenta = str_replace(' ','',$qcontrap->email_ejecutivo_cuenta);
                        $qcontrap->email_ejecutivo_cuenta = str_replace(';',',',$qcontrap->email_ejecutivo_cuenta);
                        $to_mails = explode(",", trim($qcontrap->email_ejecutivo_cuenta));
                        $to = array_merge($to_mails, $to);
                    }
                }

            }
        }
        /**/


        if ($qcontrap->cliente == 7500717) {
            $to[] = 'paulina.meza@cencosud.cl';
        }
        if ($qcontrap->cliente == 5546348 && $qcontrap->servicio_contratado == '47') {
            $to[] = 'evaluaciondeproveedores@claro.com.ar';
            // Inicio gestion 2024 Chechu pidio que la saquemos de copia. Ver si despues lo quieren otra vez.
            /*$to[] ='ClaroCompliance@claro.com.ar';*/
        }


        /*
                 if ($qcontrap->cliente == 2254875)
                 {
                    $to[] = 'alejandro.burgol@fidelitas.com.ar';
                 }
        */


        /*
                $bcc = (env('LED_TEST_MODE') == true) ? NULL : 'soporteled@fidelitas.com.ar';
                $replyto = 'soporteled@fidelitas.com.ar';
        */
        if ($app_key !== 'IV') {
            $temp = SQLConnection::backendStoreProcedure('insertar_trazabilidad', array('Envío mail a la contraparte', $web->cliente, $web->blade, 'BACK', $contraparte, 15342812, null), 'selectOne');
        }

        /* 09/01/2025: No funciona el filter_var_array($to, FILTER_VALIDATE_EMAIL)) cuando los emails son un array */
        $error = 0;
        if (is_array($to))
        {
            foreach ($to as $key => $to1) {
                if (!filter_var($to1, FILTER_VALIDATE_EMAIL))
                    { $error = 1; break;}
            }  
        }
        else 
        {
            if (!filter_var($to, FILTER_VALIDATE_EMAIL))
                { $error = 1; }
        }
        
        //if ((is_array($to) && filter_var_array($to, FILTER_VALIDATE_EMAIL)) || (filter_var($to, FILTER_VALIDATE_EMAIL))) {
        if ($error == 0) {
        /**/

            //$to = [trim('alejandro.burgol@fidelitas.com.ar'),trim('alejandro.burgol@inquirovitae.com')];
            //$to = [trim('marita.soria@gmail.com'),trim('maria.soria@fidelitas.com.ar')];
            Mailer::from($from);
            Mailer::to($to);
            Mailer::bcc($bcc);
            Mailer::replyto($replyto);
            Mailer::text($mail_content, $mail_subject);

            //die(); 
            return Mailer::send();

        }

        return false;
    }

    public static function enviarMailAnalisis($nombre_informe, $app_key = 'EMAIL-LED', $tipo = 'ALTA', $tipo2 = '', $contraparte = '', $link_expira = '', $email_alt = '', $transact_id = NULL, $paths = [], $names = [], $bcc_user = null) {
        $bcc = 'soporteled@fidelitas.com.ar';
        if (!is_null($bcc_user)) {
            $bcc = [$bcc, $bcc_user];
        }
        if ($contraparte == null) return false;

        $replyto = 'soporteled@fidelitas.com.ar';
        $qcontrap = SQLConnection::backendStoreProcedure('LN_contrapartes_', ['select', $contraparte, null, null, null, null, null, null, null, NULL, NULL, null, null, null, null], 'selectOne');

        $tipo = strtoupper($tipo) ?: null;
        $tipo2 = strtoupper($tipo2) ?: null;
        $web = SQLConnection::backendStoreProcedure('multi_web_', ['mail_contraparte', null, null, null, null, null, $contraparte, $app_key, $tipo, $tipo2], 'selectOne');

        $body = self::generateMailBody($app_key, $qcontrap, $web);

        if ($nombre_informe === 'INFORME COMERCIAL TRADICIONAL CONFIDENCIAL') {
            $content = ['Estimado ' . $qcontrap->nombre_cliente . ' <br> Como lo solicitó, el análisis relacionado a ' . $qcontrap->nombre_persona . ' ha finalizado. <br><br> Ante cualquier duda, por favor contáctese al +5411-5254-9950 o vía e-mail a produccion@Fidelitas.com.ar <br><br> Saludos, <br><br> Departamento de producción <br> Fidelitas S.A. <br><br> Fidelitas adhiere a todos los términos incluídos en la ley de protección de datos personales Ley # 25326- Habeas Data.'];
        } elseif ($nombre_informe === 'HABEAS DATA') {
            $content = ['Estimado ' . $qcontrap->nombre_persona . ': <br> Su consulta recibida ha sido procesada y finalizada. Se adjunta el informe con los datos finales que nosotros contamos de Ud. Un saludo cordial <br><br> Fidelitas SA'];
        } elseif ($nombre_informe === 'PEP UY') {
            $content = ['Estimado ' . $qcontrap->nombre_cliente . '. <br> El ' . $nombre_informe . ' correspondiente a ' . $qcontrap->nombre_persona . ' ha sido finalizado. <br> Cualquier duda contactarse con Fidelitas SA al +54 11 5254 9950'];
        } else {
            // $content = ['Estimado ' . $qcontrap->nombre_cliente . ' <br> Como lo solicitó, el análisis relacionado a ' . $qcontrap->nombre_persona . ' ha finalizado. Se adjunta documentación. <br><br> Ante cualquier duda, por favor contáctese al +5411-5254-9950 o vía e-mail a produccion@Fidelitas.com.ar <br><br> Saludos, <br><br> Departamento de producción <br> Fidelitas S.A.'];
            if(!empty($paths)){ // tenemos adjunto
                $content = ['Estimado ' . $qcontrap->nombre_cliente . ' <br> Como lo solicitó, el análisis relacionado a ' . $qcontrap->nombre_persona . ' ha finalizado. Se adjunta documentación. <br><br> Ante cualquier duda, por favor contáctese al +5411-5254-9950 o vía e-mail a produccion@Fidelitas.com.ar <br><br> Saludos, <br><br> Departamento de producción <br> Fidelitas S.A.'];
            } else {
                $content = ['Estimado ' . $qcontrap->nombre_cliente . ' <br> Como lo solicitó, el análisis relacionado a ' . $qcontrap->nombre_persona . ' ha finalizado.<br><br> Ante cualquier duda, por favor contáctese al +5411-5254-9950 o vía e-mail a produccion@Fidelitas.com.ar <br><br> Saludos, <br><br> Departamento de producción <br> Fidelitas S.A.'];
            }
        }

        $mail_content = str_replace(['%%EMAIL_CONTENT%%'], $content, $body);
        $mail_subject = 'Análisis de ' . $qcontrap->nombre_persona . ' finalizado';
        $from = $web->sender ?? 'servicio@fidelitas.com.ar';

        // Correos destinatarios
        $to = [];
        if (env('LED_TEST_MODE') == true) {
            $to[] = env('LED_TEST_EMAIL_ADDR');
        } else {
            if (!empty($email_alt)) {
                $email_alt = str_replace([' ', ';'], ['', ','], $email_alt);
                $to = explode(",", trim($email_alt));
            } else {
                /*if (!is_null($qcontrap->email_contacto)) {
                    $email = str_replace([' ', ';'], ['', ','], $qcontrap->email_contacto);
                    $to = explode(",", trim($email));
                }*/
                if (!is_null($qcontrap->email_ejecutivo_cuenta)) {
                    $email_ejec = str_replace([' ', ';'], ['', ','], $qcontrap->email_ejecutivo_cuenta);
                    $to = array_merge($to, explode(",", trim($email_ejec)));
                }
            }
        }

        if ($app_key !== 'IV') {
            SQLConnection::backendStoreProcedure('insertar_trazabilidad', ['Envío mail a la contraparte', $web->cliente, $web->blade, 'BACK', $contraparte, 15342812, null], 'selectOne');
        }

        // Validación de emails
        $error = 0;
        foreach ($to as $to1) {
            if (!filter_var($to1, FILTER_VALIDATE_EMAIL)) {
                $error = 1;
                break;
            }
        }

        if ($error == 0) {
            Mailer::from($from);
            Mailer::to($to);
            Mailer::bcc($bcc);
            Mailer::replyto($replyto);
            Mailer::text($mail_content, $mail_subject);

            // Adjuntar múltiples archivos con nombres personalizados
            if (!empty($paths) && is_array($paths)) {
                foreach ($paths as $index => $path_adj) {
                    if (file_exists($path_adj)) {
                        $name = $names[$index] ?? basename($path_adj);
                        Mailer::attachment($path_adj, $name);
                    }
                }
            }

            return Mailer::send();
        }

        return true;
    }

    public static function enviarMailAnalisisOrg($nombre_informe, $app_key='EMAIL-LED',$tipo='ALTA', $tipo2='', $contraparte='', $link_expira='', $email_alt='', $transact_id=NULL,$path=null,$name_file=null,$bcc_user=null) {    
        $bcc='soporteled@fidelitas.com.ar';
        if (!is_null($bcc_user)){
            $bcc = array($bcc,$bcc_user);
        }
        if ($contraparte == null){ return false; }        	
        // $bcc = !empty($email_alt) ?? 'soporteled@fidelitas.com.ar';
        $replyto = 'soporteled@fidelitas.com.ar';
        $qcontrap = SQLConnection::backendStoreProcedure('LN_contrapartes_', array('select', $contraparte, null, null, null, null, null, null, null, NULL, NULL, null, null, null, null), 'selectOne');
        
        $tipo = strtoupper($tipo);
        if ($tipo == '')  { $tipo = NULL;}
        $tipo2 = strtoupper($tipo2); 
        if ($tipo2 == '')  { $tipo2 = NULL;}
        $web = SQLConnection::backendStoreProcedure('multi_web_', array('mail_contraparte',null,null,null,null,null,$contraparte,$app_key,$tipo,$tipo2),'selectOne');
        /* AGB */
        $body = self::generateMailBody($app_key,$qcontrap, $web);
        // $content = self::generateMailContent($app_key,$qcontrap, $web, $link_expira,null, $transact_id);
        if ($nombre_informe == 'INFORME COMERCIAL TRADICIONAL CONFIDENCIAL') {
            $content = ['Estimado '.$qcontrap->nombre_cliente.' <br> Como lo solicitó, el análisis relacionado a '.$qcontrap->nombre_persona.' ha finalizado. <br><br> Ante cualquier duda, por favor contáctese al +5411-5254-9950 o vía e-mail a produccion@Fidelitas.com.ar <br><br> Saludos, <br><br> Departamento de producción <br> Fidelitas S.A. <br><br> Fidelitas adhiere a todos los términos incluídos en la ley de protección de datos personales Ley # 25326- Habeas Data.'];
        } else if ($nombre_informe == 'HABEAS DATA') {
            $content = ['Estimado '.$qcontrap->nombre_persona.': <br>
            Su consulta recibida ha sido procesada y finalizada.  Se adjunta el informe con los datos finales que nosotros contamos de Ud.  Un saludo cordial <br><br> Fidelitas Sa'];
        } else if ($nombre_informe == 'PEP UY') {
            $content = ['Estimado '.$qcontrap->nombre_cliente.'. <br> El '.$nombre_informe.' correspondiente a '.$qcontrap->nombre_persona.' ha sido finalizado. <br> Cualquier duda contactarse con Fidelitas SA al +54 11 5254 9950'];            
        } else {
            $content = ['Estimado '.$qcontrap->nombre_cliente.' <br> Como lo solicitó, el análisis relacionado a '.$qcontrap->nombre_persona.' ha finalizado. Se adjunta documentación. <br><br> Ante cualquier duda, por favor contáctese al +5411-5254-9950 o vía e-mail a produccion@Fidelitas.com.ar <br><br> Saludos, <br><br> Departamento de producción <br> Fidelitas S.A.'];
        }
        $mail_subject = self::generateMailSubject($app_key,$qcontrap, $web);
        
        // Reemplazo el contenido del mail
        $mail_content = str_replace(['%%EMAIL_CONTENT%%'], $content, $body);
        $mail_subject = 'Análisis de '.$qcontrap->nombre_persona.' finalizado';
        
        $from = $web->sender ?? 'servicio@fidelitas.com.ar';
        /*
        if ($email_alt !== '' and $email_alt !== null) {
            $to[] = trim($email_alt); 
        } else {
            if (!empty($to_array)) {
                $to = $to_array; 
            } else {
                $to[]= trim($qcontrap->email_contacto);
                if ( !is_null($qcontrap->email_ejecutivo_cuenta) && !empty($qcontrap->email_ejecutivo_cuenta) ) {
                    $to_mails = explode (",", trim($qcontrap->email_ejecutivo_cuenta));
                    $to = array_merge($to_mails,$to);
                }
            }
  
        }

        if (empty($to)) {
            $to[] = (env('LED_TEST_MODE') == true) ? env('LED_TEST_EMAIL_ADDR') : ( ($email_alt == '') ? trim($qcontrap->email_contacto) : trim($email_alt) );
        }
        */

        /* 09/01/2025: Ahora puede venir mas de una direccion de mail, separada por coma */
        $to = [];
        if ( (env('LED_TEST_MODE') == true) ) {
            $to[] = env('LED_TEST_EMAIL_ADDR');
        } else {
            if ($email_alt !== '' and $email_alt !== null) {
                $email_alt = str_replace(' ','',$email_alt);
                $email_alt = str_replace(';',',',$email_alt);
                $to = explode(",", trim($email_alt));
            } else {
                if (!empty($to_array)) {
                    $to = $to_array;
                } else {
                    if (!is_null($qcontrap->email_contacto) && !empty($qcontrap->email_contacto)) {
                        $qcontrap->email_contacto = str_replace(' ','',$qcontrap->email_contacto);
                        $qcontrap->email_contacto = str_replace(';',',',$qcontrap->email_contacto);
                        $to = explode(",", trim($qcontrap->email_contacto));
                    }

                    if (!is_null($qcontrap->email_ejecutivo_cuenta) && !empty($qcontrap->email_ejecutivo_cuenta)) {
                        $qcontrap->email_ejecutivo_cuenta = str_replace(' ','',$qcontrap->email_ejecutivo_cuenta);
                        $qcontrap->email_ejecutivo_cuenta = str_replace(';',',',$qcontrap->email_ejecutivo_cuenta);
                        $to_mails = explode(",", trim($qcontrap->email_ejecutivo_cuenta));
                        $to = array_merge($to_mails, $to);
                    }
                }

            }
        }
        /**/

        if ($app_key !== 'IV') {
            $temp = SQLConnection::backendStoreProcedure('insertar_trazabilidad', array('Envío mail a la contraparte', $web->cliente, $web->blade, 'BACK', $contraparte, 15342812, null), 'selectOne');
        }
        
        /* 09/01/2025: No funciona el filter_var_array($to, FILTER_VALIDATE_EMAIL)) cuando los emails son un array */
        $error = 0;
        if (is_array($to))
        {
            foreach ($to as $key => $to1) {
                if (!filter_var($to1, FILTER_VALIDATE_EMAIL))
                    { $error = 1; break;}
            }  
        }
        else 
        {
            if (!filter_var($to, FILTER_VALIDATE_EMAIL))
                { $error = 1; }
        }
        
        //if ((is_array($to) && filter_var_array($to, FILTER_VALIDATE_EMAIL)) || (filter_var($to, FILTER_VALIDATE_EMAIL))) {
        if ($error == 0) {
        /**/            
            Mailer::from($from);
            Mailer::to($to);
            Mailer::bcc($bcc);
            Mailer::replyto($replyto);
            Mailer::text($mail_content, $mail_subject);
            //
            if ( !is_null($path) && !is_null($name_file) ){
                Mailer::attachment($path);
            }
            return Mailer::send();
        }
       
        return false;  
    }

    public static function generateMailBody($app_key, $qcontrap, $web) {
        $cliente = $web->cliente;
        $ncliente = $web->nombre_cliente;
        

        if ($cliente == 5546348) {
            /** Chanchada para cambiar el nombre del cliente en caso de ser AMX **/
            $ncliente = ($qcontrap->country_code == 'PY') ? 'AMX PARAGUAY S.A.' : ( ($qcontrap->country_code == 'UY') ? 'AM Wireless Uruguay S.A.' : $ncliente );
        }
        if ($cliente == 7855254) {
            /** Chanchada para cambiar el nombre del cliente en caso de ser VALID **/
            $ncliente = ($qcontrap->country_code == 'BR') ? 'VALID SOLUÇOES S A' : (($qcontrap->country_code != 'AR') ? 'VALID S.A.' : $ncliente);
        }

        
        if ( isset($qcontrap->nombre_filial) && !is_null($qcontrap->nombre_filial))
        {
            $ncliente = $qcontrap->nombre_filial;
        }

        //$ncliente 
        
        //
        $template = \View::make('/led/led_email_template')->render(); 
        if ($app_key == 'EMAIL-IMPE')
        {
            $url =  $web->http_host ?? env('URL_CONTRATISTA'); 
        }
        else 
        {
            $url =  $web->http_host ?? env('URL_LEGAJOS'); 
        }
        $protocol = (strpos($url, 'https://', 0)==0) ? ('https' . chr(58) . chr(47) . chr(47)) : ('https' . chr(58) . chr(47) . chr(47));
        $url = (strpos($url, 'http', 0)==0) ? $url : $protocol . $url ;
        $logo_url = (!empty($url) and !empty($web->uri_email_logo)) ? ((strpos($web->uri_email_logo, 'http', 0)==0) ? $web->uri_email_logo : ($url . $web->uri_email_logo)) : 'https://www.fidelitas.com.ar/img/mail_logo.png';


        $body = str_replace(['%%EMAIL_TITLE%%', '%%LOGO_URL%%'], [$ncliente, $logo_url], $template);

        return $body;
    }

    public static function generateMailContent($app_key, $qcontrap, $web, $link_expira = '', $doc_id = NULL, $transact_id = NULL) {

        $cliente = $web->cliente;
        $ncliente = $web->nombre_cliente;
        if ($cliente == 5546348) {
            /** Chanchada para cambiar el nombre del cliente en caso de ser AMX **/
            $ncliente = ($qcontrap->country_code == 'PY') ? 'AMX PARAGUAY S.A.' : (($qcontrap->country_code == 'UY') ? 'AM Wireless Uruguay S.A.' : $ncliente);
        }
        if ($cliente == 7855254) {
            /** Chanchada para cambiar el nombre del cliente en caso de ser VALID **/
            $ncliente = ($qcontrap->country_code == 'BR') ? 'VALID SOLUÇOES S A' : (($qcontrap->country_code != 'AR') ? 'VALID S.A.' : $ncliente);
        }
        if (isset($qcontrap->nombre_filial) && !is_null($qcontrap->nombre_filial)) {
            $ncliente = $qcontrap->nombre_filial;
        }
        // 
        if ($app_key == 'EMAIL-IMPE') {
            $legajos_url = $web->http_host ?? env('URL_CONTRATISTA');
        } else {
            $legajos_url = $web->http_host ?? env('LED_WEB_PROVEEDOR_URL');
        }
        $protocol = (strpos($legajos_url, 'https://', 0) === 0) ? ('https' . chr(58) . chr(47) . chr(47)) : ('https' . chr(58) . chr(47) . chr(47));
        $legajos_url = (strpos($legajos_url, 'http', 0) === 0) ? $legajos_url : $protocol . $legajos_url;

        $link_expira = !empty($link_expira) ? str_replace('-', '/', $link_expira) : NULL;
        $expira = !empty($link_expira) ? date_format(date_create_from_format('!d/m/Y', $link_expira), 'Y-m-d') : NULL;

        $restan_dias = '';
        $autologin = '';
        $link = '';

        // datos de documentacion rechazada
        $doc_rechazada = '';
        if ($doc_id != NULL) {
            $doc = SQLConnection::backendStoreProcedure('LN_docs_', array('select', $doc_id, null, null, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, null, NULL), 'selectOne');
            if ($doc->estado_doc == 'R') {
                $doc_rechazada = $doc_rechazada . '<strong>Documento: </strong>' . $doc->nombre_tipo_doc . (($doc->es_balance > 0 || $doc->es_manif_bienes > 0) ? ' al ' . $doc->fin_ejercicio : '') . '<br />';
                $doc_rechazada = $doc_rechazada . '<strong>Plazo de carga: </strong>' . $doc->vencimiento_carga . '<br />';
                $doc_rechazada = $doc_rechazada . '<strong>Rechazado el: </strong>' . $doc->rechazado . '<br />';
                $doc_rechazada = $doc_rechazada . '<strong>Rechazado por: </strong>' . $doc->rechazado_por_alias . '<br />';
                $doc_rechazada = $doc_rechazada . '<strong>Motivo del rechazo: </strong>' . $doc->texto_rechazo . '<br />';
            }
        }

        $link_pago = '';

        if ($expira != NULL) {
            $hoy = new DateTime('today');

            $days_interval = date_diff($hoy, date_create_from_format('!d/m/Y', $link_expira));
            $restan_dias = $days_interval->format('%d') + 1;

            // Este es el string que viene luego del '/autologin?q='
            $autologin = encrypt($qcontrap->country_code . '|' . $qcontrap->identificador . '|' . $qcontrap->identificacion . '|' . $qcontrap->contraparte . '|' . $expira);
            $link = '<a href="' . $legajos_url . '/autologin?q=' . $autologin . '">';

            // Link para prepago
            $trans = (NULL != $transact_id) ? '|' . $transact_id : '';
            $autologin_pago = encrypt($qcontrap->country_code . '|' . $qcontrap->identificador . '|' . $qcontrap->identificacion . '|' . $qcontrap->contraparte . '|' . $expira . '|pago' . $trans);
            $link_pago = '<a href="' . $legajos_url . '/autologin?q=' . $autologin_pago . '">';

        }

        $content = $web->mensaje;


        if ($app_key == 'IV') {
            $content = str_replace('%%CLIENTE%%', $web->nombre_cliente, $content);
            $content = str_replace('%%nombre_persona%%', $qcontrap->nombre_persona, $content);
            $content = str_replace('%%uri_host%%', $web->http_host, $content);
            return $content;
        }

        if (isset($qcontrap->password) and $qcontrap->password == '@encripted') {
            $qcontrap->password = 'genereda previamente';
        }


        if ($app_key == 'EMAIL-IMPE') {
            $source = array('%%CLIENTE%%',
                '%%NOMBRE_CLIENTE%%',
                '%%NOMBRE_CONTACTO%%',
                '%%CONTACTO%%',
                '%%CONTRAPARTE%%',
                '%%CONTRATISTA%%',
                '%%ID%%',
                '%%IDENTIFICADOR%%',
                '%%ABREVIATURA%%',
                '%%IDENTIFICACION%%',
                '%%NUMERO%%',
                '%%CLAVE%%',
                '%%PASSWORD%%',
                '%%COUNTRY_CODE%%',
                '%%CODIGO_PAIS%%',
                '%%COUNTRY_NAME%%',
                '%%COUNTRY%%',
                '%%PAIS%%',
                '%%PAIS_SERVICIO%%',
                '%%EMAIL%%',
                '%%EMAIL_CONTACTO%%',
                '%%USUARIO%%',
                '%%NOMBRE_USUARIO%%',
                '%%NOMBRE-USUARIO%%',
                '%%USERNAME%%',
                '%%CONTRATISTA_URL%%',
                '%%URL-CONTRATISTA-IMPERIUM%%');

            $replace = array($ncliente,
                $ncliente,
                $qcontrap->first_name . ' ' . $qcontrap->last_name,
                $qcontrap->first_name . ' ' . $qcontrap->last_name,
                $qcontrap->nombre_persona,
                $qcontrap->nombre_persona,
                $qcontrap->abreviatura,
                $qcontrap->abreviatura,
                $qcontrap->abreviatura,
                $qcontrap->identificacion,
                $qcontrap->identificacion,
                $qcontrap->password,
                $qcontrap->password,
                $qcontrap->country_code,
                $qcontrap->country_code,
                $qcontrap->country_name,
                $qcontrap->country_name,
                $qcontrap->country_name,
                $qcontrap->pais_servicio,
                $qcontrap->email,
                $qcontrap->email,
                $qcontrap->username,
                $qcontrap->username,
                $qcontrap->username,
                $qcontrap->username,
                env('URL_CONTRATISTA'),
                env('URL_CONTRATISTA'));
            return str_replace($source, $replace, $content);

        }
        if (!empty($doc)) {
            // Busco la traducción del tipo de documento
            $trad = \App\Http\Controllers\Traducciones::traduccionesGet(4, 'home legajos', $doc->nombre_tipo_doc);
            $nombre = !empty($trad) ? $trad->{$qcontrap->codigo_idioma} : $doc->nombre_tipo_doc;

            $source = array('%%CLIENTE%%',
                '%%NOMBRE_CONTACTO%%',
                '%%CONTACTO%%',
                '%%CONTRAPARTE%%',
                '%%LINK%%',
                '%%LINK_PAGO%%',
                '%%LINK_EXPIRA%%',
                '%%RESTAN_DIAS%%',
                '%%DIAS%%',
                '%%FECHA_LIMITE%%',
                '%%ID%%',
                '%%IDENTIFICADOR%%',
                '%%NUMERO%%',
                '%%CLAVE%%',
                '%%CLAVE_EXPIRA%%',
                '%%COUNTRY_CODE%%',
                '%%COUNTRY_NAME%%',
                '%%PAIS%%',
                '%%CODIGO_PAIS%%',
                '%%EMAIL_CONTACTO%%',
                '%%LEGAJOS_URL%%',
                '%%DOCUMENTACION_RECHAZADA%%',
                '%%TEXTO_ADICIONAL%%',
                '%%DOCUMENTO%%',
                '%%PLAZO_CARGA%%',
                '%%RECHAZADO%%',
                '%%RECHAZADO_FECHA_HORA%%',
                '%%RECHAZADO_POR%%',
                '%%MOTIVO_RECHAZO%%');

            $replace = array($ncliente,
                $qcontrap->nombre_contacto,
                $qcontrap->nombre_contacto,
                $qcontrap->nombre_persona,
                $link,
                $link_pago,
                $link_expira,
                $restan_dias,
                $restan_dias,
                $link_expira,
                $qcontrap->abreviatura,
                $qcontrap->abreviatura,
                $qcontrap->identificacion,
                $qcontrap->clave,
                $qcontrap->clave_expira,
                $qcontrap->country_code,
                $qcontrap->country_name,
                $qcontrap->country_name,
                $qcontrap->country_code,
                $qcontrap->email_contacto,
                $legajos_url,
                $doc_rechazada,
                '',
                $nombre,
                $doc->vencimiento_carga,
                $doc->rechazado,
                $doc->rechazado,
                $doc->rechazado_por_alias,
                $doc->texto_rechazo);

        } else {

            $source = array('%%CLIENTE%%',
                '%%NOMBRE_CONTACTO%%',
                '%%CONTACTO%%',
                '%%CONTRAPARTE%%',
                '%%LINK%%',
                '%%LINK_PAGO%%',
                '%%LINK_EXPIRA%%',
                '%%RESTAN_DIAS%%',
                '%%DIAS%%',
                '%%FECHA_LIMITE%%',
                '%%ID%%',
                '%%IDENTIFICADOR%%',
                '%%NUMERO%%',
                '%%CLAVE%%',
                '%%CLAVE_EXPIRA%%',
                '%%COUNTRY_CODE%%',
                '%%COUNTRY_NAME%%',
                '%%PAIS%%',
                '%%CODIGO_PAIS%%',
                '%%EMAIL_CONTACTO%%',
                '%%LEGAJOS_URL%%',
                '%%DOCUMENTACION_RECHAZADA%%',
                '%%TEXTO_ADICIONAL%%');

            $replace = array($ncliente,
                $qcontrap->nombre_contacto,
                $qcontrap->nombre_contacto,
                $qcontrap->nombre_persona,
                $link,
                $link_pago,
                $link_expira,
                $restan_dias,
                $restan_dias,
                $link_expira,
                $qcontrap->abreviatura,
                $qcontrap->abreviatura,
                $qcontrap->identificacion,
                $qcontrap->clave,
                $qcontrap->clave_expira,
                $qcontrap->country_code,
                $qcontrap->country_name,
                $qcontrap->country_name,
                $qcontrap->country_code,
                $qcontrap->email_contacto,
                $legajos_url,
                $doc_rechazada,
                '');
        }

        return str_replace($source, $replace, $content);
    }

    public static function generateMailSubject($app_key, $qcontrap, $web) {
        $cliente = $web->cliente;
        $ncliente = $web->nombre_cliente;
        if ($cliente == 5546348) {
            /** Chanchada para cambiar el nombre del cliente en caso de ser AMX **/
            $ncliente = ($qcontrap->country_code == 'PY') ? 'AMX PARAGUAY S.A.' : (($qcontrap->country_code == 'UY') ? 'AM Wireless Uruguay S.A.' : $ncliente);
        }

        if ($cliente == 7855254) {
            /** Chanchada para cambiar el nombre del cliente en caso de ser VALID **/
            $ncliente = ($qcontrap->country_code == 'BR') ? 'VALID SOLUÇOES S A' : (($qcontrap->country_code != 'AR') ? 'VALID S.A.' : $ncliente);
        }

        if (isset($qcontrap->nombre_filial) && !is_null($qcontrap->nombre_filial)) {
            $ncliente = $qcontrap->nombre_filial;
        }

        $restan_dias = '';
        $autologin = '';
        $link = '';
        $doc_rechazada = '';
        $link_pago = '';
        $link_expira = NULL;
        $legajos_url = '';
        $content = $web->asunto;

        if ($app_key == 'IV') {
            $content = str_replace('%%nombre_persona%%', $qcontrap->nombre_persona, $content);
            return $content;
        }


        $source = array('%%CLIENTE%%',
            '%%NOMBRE_CONTACTO%%',
            '%%CONTACTO%%',
            '%%CONTRAPARTE%%',
            '%%LINK%%',
            '%%LINK_PAGO%%',
            '%%LINK_EXPIRA%%',
            '%%RESTAN_DIAS%%',
            '%%DIAS%%',
            '%%FECHA_LIMITE%%',
            '%%ID%%',
            '%%IDENTIFICADOR%%',
            '%%NUMERO%%',
            '%%CLAVE%%',
            '%%CLAVE_EXPIRA%%',
            '%%COUNTRY_CODE%%',
            '%%COUNTRY_NAME%%',
            '%%PAIS%%',
            '%%CODIGO_PAIS%%',
            '%%EMAIL_CONTACTO%%',
            '%%LEGAJOS_URL%%',
            '%%DOCUMENTACION_RECHAZADA%%',
            '%%TEXTO_ADICIONAL%%');

        $replace = array($ncliente,
            $qcontrap->nombre_contacto,
            $qcontrap->nombre_contacto,
            $qcontrap->nombre_persona,
            $link,
            $link_pago,
            $link_expira,
            $restan_dias,
            $restan_dias,
            $link_expira,
            $qcontrap->abreviatura,
            $qcontrap->abreviatura,
            $qcontrap->identificacion,
            $qcontrap->clave,
            $qcontrap->clave_expira,
            $qcontrap->country_code,
            $qcontrap->country_name,
            $qcontrap->country_name,
            $qcontrap->country_code,
            $qcontrap->email_contacto,
            $legajos_url,
            $doc_rechazada,
            '');

        return str_replace($source, $replace, $content);
    }

    //FUNCIONES PARA EL ABM DE EMAILS
    public function buscarEmails(){
        return view("/abm-email/email");
    }

    //FUNCION QUE LLAMA A TABLA EMAILS PARA ARMAR LA TABLA
    public function mostarTablaEmail(){        
        $id_padron = Request::input('id_padron');        
        
        if ($id_padron != NULL) {                        
            $tabla = self::tablaEmails($id_padron);                        
            return $tabla;                                    
        }else{            
            return 'El cuit es invalido o no fue recibido';
        }
    }

    //FUNCION QUE TRAE LOS DATOS PARA ARMAR LA TABLA    
    public static function tablaEmails($id_padron){
        $data = [];

        if( $id_padron != NULL ){
            try {
                $data = SQLConnection::backendStoreProcedure('abm_email', array('SELECCIONAR',NULL, $id_padron), 'select');                                
            } catch (\Throwable $th) {
                return 'error_datos_tabla';
            }            
        }
        
        $tabla = \View::make('/abm-email/tabla_email')->with(compact(['data'],'id_padron'))->render();
		
        return $tabla;
    }

    //FUNCION PARA DAR DE ALTA UN REGISTRO
    public function altaRegistro(){                
        if( isset($_POST['id_padron']) && (isset($_POST['tipoEmail']) && $_POST['tipoEmail'] != 'Seleccione una opcion...') && isset($_POST['email']) ){
            
            $id_padron = Request::input('id_padron');
            $email = Request::input('email');
            $tipo_email = Request::input('tipoEmail');
            
            SQLConnection::backendStoreProcedure('abm_email', array('ALTA',NULL, $id_padron,$email, $tipo_email, 1), 'select');

            $tabla = self::tablaEmails($id_padron);
            
            return $tabla;            
        }else{
            return 'error_alta';
        }   
    }

    //FUNCION QUE EDITA UN REGISTRO
    public function editarRegistro(){                    
        if( isset($_POST['id_email_edit']) && isset($_POST['id_padron_edit']) && (isset($_POST['tipoEmailEdit']) && $_POST['tipoEmailEdit'] != 'Seleccione una opcion...') && isset($_POST['emailEdit']) ){
            
            $id_padron = Request::input('id_padron_edit');
            $id_email = Request::input('id_email_edit');            
            $email = Request::input('emailEdit');
            $tipo_email = Request::input('tipoEmailEdit');
            $estado = Request::input('registro_estado');
            
            SQLConnection::backendStoreProcedure('abm_email', array('EDITAR',$id_email, NULL,$email, $tipo_email, $estado), 'select');            

            $tabla = self::tablaEmails($id_padron);
            
            return $tabla;
        }else{
            return 'error_editar';
        }
    }

    //FUNCION QUE CAMBIA EL ESTADO DE UN REGISTRO
    public function estadoRegistro(){                          
        if (isset($_POST['id_email']) && isset($_POST['activo']) && isset($_POST['id_padron']) ) {
            
            $id_email = Request::input('id_email');
            $estado = Request::input('activo');
            $id_padron = Request::input('id_padron');

            SQLConnection::backendStoreProcedure('abm_email', array('ESTADO',$id_email, $estado), 'select');
            
            $tabla = self::tablaEmails($id_padron);
            
            return $tabla;
        }else{
            return 'error_estado';
        }
    }


    public function generaAutologin()
    {
        $country_code   = Request::input('country_code');
        $identificador  = Request::input('identificador');
        $identificacion = Request::input('identificacion');
        $contraparte    = Request::input('contraparte');
        $expira         = Request::input('expira');
        $autologin = encrypt($country_code . '|' . $identificador . '|' . $identificacion . '|' . $contraparte . '|' . $expira);
        return $autologin; 
    }


}


