<?php

namespace App\Http\Controllers;

use App\Custom\SQLConnection;
use App\Custom\Misc;

use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Request;

use DateTime;
use stdClass;
use DB;

class PEPControllerNuevo extends Controller {

    public static $id_resultados;

    //-----------------------------------------------------------------------------------------------------------------------------------//
    //--  FUNCION PARA HACER PRUEBAS DE LAS FUNCIONES POR SEPARADO  --//
    public static function index() {
        //self::ConexionWS();
        //self::CurlPEPListas();
        $cuit = '13214623';
        $nombre_persona = 'marcelo hugo tinelli';
        $id_padron = '22';
        $token = 'DA3DBE3042BC40D4AAA7834D7FFE14D8';
        $id_llamada = '33';
        self::obtenerDatosPEP($cuit, $nombre_persona, $id_padron, $token, $id_llamada, $pais = 'AR');
    }

    //-----------------------------------------------------------------------------------------------------------------------------------//
    //--  FUNCION HEREDADA PARA LIMPIAR CARACTERES  'EN USO'  --//
    private static function limpiarCaracteresEspeciales($string) {
        $string = htmlentities($string);
        $string = preg_replace('/\&(.)[^;]*;/', '\\1', $string);
        $textoLimpio = preg_replace('([^A-Za-z0-9 .,\(\)áéíóúÁÉÍÓÚñÑ\-\:])', '', $string);
        return $textoLimpio;
    }

    //-----------------------------------------------------------------------------------------------------------------------------------//
    /* 
    ESTA FUNCION SE ENCARGA DE OBTENER EL NUEVO (TOKEN Y FECHA DE EXPIRACION) Y LOS GUARDAR 
    LOS REGISTROS.
    */
    public static function ConexionWS() {
        $user = env('PEP_USERNAME');
        $pass = env('PEP_PASSWORD');
        $curl = curl_init();
        $metodo = env('PEP_SERVICIO');

        curl_setopt_array($curl, [
            CURLOPT_URL => env('PEP_LOGIN_N'),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "{\n \"userName\": \"$user\",\n \"password\": \"$pass\"\n}\n",
            CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        /*if (env('BACKEND')!=='BACKEND') {
            $mensajeCurl = 'CurlPEPlogin Error:' . $err . ' - Response:' . $response;
        }*/

        if ($err) {
            //return json_encode("cURL Error #:" . $err);
            return false;
        } else {
            //echo(var_dump($response));
            //return $response;

            $resp = json_decode($response);
            if (isset($resp->authenticationToken) && isset($resp->tokenExpirationUtc)) {
                $token = $resp->authenticationToken;
                $expiracion = $resp->tokenExpirationUtc;
                $expiracion = new DateTime($expiracion);
                $expiracion = $expiracion->format('Y-m-d H:i:s');
                SQLConnection::backendStoreProcedure('PEP_guardar_autenticacion', array($token, '', $expiracion, $metodo));
                return true;
            }
            return false;
        }
    }
    //-----------------------------------------------------------------------------------------------------------------------------------//


    /*
    ESTA FUNCION LLAMA A 'procesar_pep' Y DEVUELVE LOS DATOS JUNTO A UNA VISTA
    */
    public static function obtenerPEPOriginal() {
        $cuit = Request::input('cuit');
        $nombre_persona = Request::input('nombre_persona');
        $id_padron = Request::input('id_padron');
        $contraparte = (null !== Request::input('contraparte')) ? Request::input('contraparte') : '0';
        $resp = "OK";
        $datos_finales = self::procesar_pep($cuit, $nombre_persona, $id_padron, $pais);
        if (isset($datos_finales['error'])) {
            $resp = $datos_finales['error'];
        }
        return json_encode(array('error' => $resp, 'tabla' => view('/led/led_tabla_fidecheck')->with(compact('cuit', 'nombre_persona', 'datos_finales', 'contraparte'))->render()));
    }

    public static function obtenerPEP() {
        $cuit = Request::input('cuit');
        $nombre_persona = Request::input('nombre_persona');
        $id_padron = Request::input('id_padron');
        //--- 
        $pais = Request::input('codigo_pais');
        //---
        $contraparte = (null !== Request::input('contraparte')) ? Request::input('contraparte') : '0';
        $resp = "OK";
        //$datos_finales = self::procesar_pep($cuit, $nombre_persona, $id_padron,$pais);
        // $datos_finales = self::consultApiWsNueva($cuit, $nombre_persona, $pais);
        $datos_finales = ($pais=='AR') ? self::consultApiWsNueva($cuit, $nombre_persona, $pais) : self::consultApiWsNueva(null, $nombre_persona, null);
        //      var_dump('119');     
        //      var_dump($datos_finales); die();   
        if (isset($datos_finales['error'])) {
            $resp = $datos_finales['error'];
        }
        //-- ACA SE ESTABLECE LA CONDICION PARA INDICAR A LA VISTA COMO MOSTRAR EL RESULTADO
        $registro_a_mostrar = 0;
        $registros_tabla = 0;
        //--
        if (!empty($datos_finales)) {
            if (count($datos_finales) == 1) {
                if ($datos_finales[0]->residencia == 'AR' || ($datos_finales[0]->nombre == $nombre_persona && ($datos_finales[0]->identificacionTributaria == $cuit || (isset($datos_finales[0]->documento) && $datos_finales[0]->documento == $cuit)) && $datos_finales[0]->residencia == $pais)) {
                    $registro_a_mostrar = 1;
                }
            }
            /* 23/08/2024: Cuando son de otro pais, a veces trae otro Tax-id o documento, que siempre lo muestre en la tabla para que el usuario lo elija o no, con criterio, viendo si es o no la misma persona... 
                        if  ($registro_a_mostrar == 0 && (count($datos_finales) > 1 || ( count($datos_finales) == 1 && $datos_finales[0]->residencia != 'AR' && ($datos_finales[0]->nombre != $nombre_persona || (  isset($datos_finales[0]->documento) && $datos_finales[0]->documento != $cuit  && $datos_finales[0]->identificacionTributaria != $cuit ) || $datos_finales[0]->residencia != $pais) ) ) ) {
                            $registros_tabla = 1;
                        }
                        */
            if ($registro_a_mostrar == 0) {
                $registros_tabla = 1;
            }
        }
        //--
        return json_encode(array('error' => $resp, 'tabla' => view('/led/led_tabla_fidecheck')->with(compact('cuit', 'nombre_persona', 'datos_finales', 'contraparte', 'pais', 'registros_tabla', 'registro_a_mostrar'))->render()));
    }

    //-----------------------------------------------------------------------------------------------------------------------------------//
    /* 
    ESTA FUNCION BUSCA PRIMERO EN LA DB SI FUERON CONSULTADOS LOS ULTIMOS N DIAS. CASO
    CONTRARIO PIDE ULTIMO TOKEN VIGENTE Y LOS CONSULTA A WS Y ANTES DE RETORNARLOS, LOS
    GUARDA EN LA DB. SI EL TOKEN ESTA VENCIDO, PIDE LA GENERACION DE UNO NUEVO.

    N -> ESTA DEFINIDO COMO VARIABLE DE ENTORNO (PEP_TOPE_DIAS).
    */
    private static function procesar_pep($cuit, $nombre_persona, $id_padron, $pais = 'AR') {
        self::$id_resultados = [];
        $datos_finales = [];
        $resp = '';
        $ids = SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_control', array($cuit, env('PEP_TOPE_DIAS')), 'select');
        foreach ($ids as $id) {
            self::$id_resultados[] = $id->id_resultado;
            $resp = 'OK';
        }
        //
        if (empty(self::$id_resultados) || !empty(self::$id_resultados)) {
            $id_llamadas = SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_llamados_', array('insert', '0', $cuit, $nombre_persona, $id_padron, 'worldsys', null, null, null), 'selectOne');
            //$forzar_login = 'S'; 
            $forzar_login = 'N';
            $resp = '401'; // No hay token valido
            while ($resp == '401') {
                $resp = '0';
                $datos = self::obtenerDatosLogin(env('PEP_SERVICIO'), $forzar_login);
                $final_response = '';
                if (isset($datos->error)) {
                    $error_llamada = SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_llamados_', array('update', $id_llamadas->id, $cuit, $nombre_persona, $id_padron, 'worldsys', '500', 'Error Login', $datos->error), 'selectOne');
                    $final_response = new stdClass();
                    $final_response->error = $datos->error;
                    $resp = $final_response->error;
                    //break; 
                    return $final_response;
                }

                if (isset($datos->token)) {
                    $resp = self::obtenerDatosPEP($cuit, $nombre_persona, $id_padron, $datos->token, $id_llamadas->id, $pais);
                    $forzar_login = 'S';
                    foreach ($resp as $i) {
                        if (isset($i->fechaNovedad)) {
                            $i->fechaNovedad = self::getFecha();
                        }
                    }
                    //$resp[0]->fechaNovedad = self::getFecha();
                    return $resp;
                }
            }
        }
        $datos_finales = [];
        if (!empty(self::$id_resultados)) {
            $ids = '';
            foreach (self::$id_resultados as $key => $id) {
                $ids .= ',' . $id;
            }

            $datos_finales = SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_select', array($ids), 'select');
        } else {
            $datos_finales['error'] = $resp;
        }
        //echo(var_dump($datos_finales)); die();
        $res_temp = new stdClass();

        $res_temp->nombre = (isset($datos_finales[0]->nombre_persona)) ? $datos_finales[0]->nombre_persona : '';
        $res_temp->identificacionTributaria = (isset($datos_finales[0]->cuit)) ? $datos_finales[0]->cuit : '';
        $res_temp->fidecheck = (isset($datos_finales[0]->fidecheck)) ? $datos_finales[0]->fidecheck : '';
        $res_temp->cargo = (isset($datos_finales[0]->Cargo)) ? $datos_finales[0]->Cargo : '';
        $res_temp->institucion = (isset($datos_finales[0]->Institucion)) ? $datos_finales[0]->Institucion : '';
        if (isset($datos_finales[0]->TipoFuente) && $datos_finales[0]->TipoFuente == 'SO') {
            $res_temp->tipoFuente = 'sujeto obligado';
        } else if (isset($datos_finales[0]->TipoFuente) && $datos_finales[0]->TipoFuente == 'SAN') {
            $res_temp->tipoFuente = $datos_finales[0]->TipoFuente;
        } else {
            $res_temp->tipoFuente = '';
        }
        //$res_temp->tipoFuente = (isset($datos_finales[0]->TipoFuente) && $datos_finales[0]->TipoFuente == 'SO') ? 'sujeto obligado' : '';
        $res_temp->orden = (isset($datos_finales[0]->orden) && $datos_finales[0]->TipoFuente != 'SAN') ? $datos_finales[0]->orden : '2';
        $res_temp->descripcionPais = (isset($datos_finales[0]->DescripcionPais)) ? $datos_finales[0]->DescripcionPais : '';
        $res_temp->relacion = (isset($datos_finales[0]->Relacion)) ? $datos_finales[0]->Relacion : '';
        //$res_temp->contraparte = (isset($datos_finales[0]->cuit)) ? $datos_finales[0]->cuit : '';
        $res_temp->fechaNovedad = (isset($datos_finales[0]->fecha)) ? $datos_finales[0]->fecha : '';
        //echo(var_dump($res_temp)); die();
        return array($res_temp);
        //return $datos_finales; 
    }

    static function getFecha() {
        date_default_timezone_set('America/Argentina/Buenos_Aires');
        setlocale(LC_TIME, "es_AR.UTF-8");
        return date("d-m-Y");
    }

    //-----------------------------------------------------------------------------------------------------------------------------------//
    /*
    ESTA FUNCION BUSCA EL TOKEN MAS RECIENTE PARA EVITAR ESTABLECER CONEXION NUEVA
    DE NO OBTENERLO, LLAMA A 'ConexionWS' QUE ESTA ENCARGADA DE PEDIR NUEVO TOKEN MAS
    FECHA DE EXPIRACION.
    */
    private static function obtenerDatosLogin($metodo, $forzar_login) {
        if ($forzar_login == "N") {
            $datos = SQLConnection::backendStoreProcedure('PEP_obtener_datos_login', array($metodo), 'selectOne');
        }
        if (!empty($datos) && $forzar_login == "N") {
            session::put($metodo, $datos);
            return $datos;
        } else {
            $login = self::ConexionWS();
            if ($login == true) {
                $datos = SQLConnection::backendStoreProcedure('PEP_obtener_datos_login', array($metodo), 'selectOne');
                session::put($metodo, $datos);
            } else {
                $datos = new stdClass();
                $datos->error = "No ha podido establecer la conexion con Worldsys";
            }
            return $datos;
        }
    }


    //-----------------------------------------------------------------------------------------------------------------------------------//
    /*
    FUNCION HEREDADA PARA NO ALTERAR MUCHO LA ESTRUCTURA, SIMPLEMENTE HACE DE CONECTOR
    */
    private static function obtenerDatosPEP($cuit, $nombre_persona, $id_padron, $token, $id_llamada, $pais = 'AR') {
        $url = env('PEP_LISTA_N') . $token;
        //--> ESTA LINEA DEBERIA QUEDAR, YA QUE SE ESPERAN LOS DATOS 
        $resp = self::CurlPEPListas($cuit, $nombre_persona, $id_padron, $element = '', $url, $token, $id_llamada, $pais);
        return $resp;

        //--> ESTA LINEA ES SOLO PARA DEBUG
        /*$element = (!isset($element)) ? '' : $element;
        self::CurlPEPListas($cuit,$nombre_persona,$id_padron,$element,$url,$token,$id_llamada,$pais);*/
    }

    //-----------------------------------------------------------------------------------------------------------------------------------//
    /* 
    ESTA FUNCION ES LA ENCARGA DE HACER LA BUSQUEDA GENERAL Y TAMBIEN LO QUE 
    ANTERIORMENTE HACIA LA FUNCION 'obtenerMasDatosPEP'. QUE EXTENDIA LOS DATOS, 
    PERO VOLVIA HACER UNA LLAMADA A OTRA URL DE WS.
    AHORA SE HACE TODO DESDE LA MISMA URL
    */
    public static function CurlPEPListas($cuit, $nombre_persona, $id_padron, $element, $url, $token, $id_llamada, $pais) {
        $resulado_alterno = array();
        $flag = '';

        if ($pais == 'AR') {
            $id_tributaria = $cuit;
            if ($cuit[0] == '3') {
                $cuit2 = 'null';
            } else {
                $cuit2 = (strlen($cuit) == 11) ? substr($cuit, 2, -1) : $cuit;
                $dni = intval($cuit2);
                $cuit2 = $dni;
            }
        } else {
            if ($cuit[0] != '3') {
                $cuit2 = (strlen($cuit) == 11) ? substr($cuit, 2, -1) : $cuit;
                $cuit2 = ($cuit2[0] == '0') ? substr($cuit2, 1) : $cuit2;
                $id_tributaria = $cuit;

            } else {
                $id_tributaria = $cuit;
                $cuit2 = 'null';
            }
        }

        $factorSimilitud = ($pais == 'AR') ? '100' : '90';
        $factorSimilitudInverso = ($pais == 'AR') ? '30' : '70';
        //------------------------------------------------------------------------------------------------------
        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "{\n \"nombre\": \"$nombre_persona\",\n \"documento\": $cuit2,\n \"identificacionTributaria\": $id_tributaria,\n \"factorSimilitud\": $factorSimilitud,\n \"factorSimilitudInverso\": $factorSimilitudInverso,\n \"tipoFuente\": \"Todas\",\n }\n",
            CURLOPT_HTTPHEADER => [
                "Content-Type: application/json"
            ],
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);
        $flag = '1';
        curl_close($curl);
        //------------------------------------------------------------------------------------------------------
        //--  SE DEBE MEJORAR ESTO  --//
        $cuit_n = 'null';
        $id_tributaria = 'null';
        $dato_temporal = json_decode($response);

        if (isset($dato_temporal->resultados[0]->residencia) && $dato_temporal->resultados[0]->residencia != 'AR') {
            $curl = curl_init();

            curl_setopt_array($curl, [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => "{\n \"nombre\": \"$nombre_persona\",\n \"documento\": $cuit_n,\n \"identificacionTributaria\": $id_tributaria,\n \"factorSimilitud\": $factorSimilitud,\n \"factorSimilitudInverso\": $factorSimilitudInverso,\n \"tipoFuente\": \"Todas\",\n }\n",
                CURLOPT_HTTPHEADER => [
                    "Content-Type: application/json"
                ],
            ]);

            $response = curl_exec($curl);
            $err = curl_error($curl);
            $flag = '';
            curl_close($curl);
        }
        //------------------------------------------------------------------------------------------------------
        if ($err) {
            $error = "cURL Error #:" . $err . ' ' . $response;
            if ($err == '' || !is_numeric($err)) {
                $err = -100;
            }
            //--  DESCOMENTAR ESTO PARA PRODUCCION O COMENTAR PARA DEBUG
            $error_llamada = SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_llamados_', array('update', $id_llamada, $cuit, $nombre_persona, $id_padron, 'worldsys', $err, 'CURL Error', $error), 'selectOne');
            //-----------------------------------------------
            return $error;
        }

        $error = 'OK';

        //--  VARIABLE  --//
        $StatusCode = '';
        $Status = 'OK';
        $Reason = '';
        //---------------//

        $array = json_decode($response);
        //echo(var_dump($array)); die();
        if (isset($array->code)) {
            $StatusCode = $array->code;
            $Status = '000';
            $Reason = $array->message;

            if ($StatusCode != '200') {
                $error = $StatusCode;
                //return $error;
                return $datos_finales = array();
            }

        }

        if ($StatusCode == '' || !is_numeric($StatusCode)) {
            $StatusCode = -100;
        }
        //--  DESCOMENTAR TODA ESTA SECCION PARA PRODUCCION O COMENTAR PARA DEBUG

        $error_llamada = SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_llamados_', array('update', $id_llamada, $cuit, $nombre_persona, $id_padron, 'worldsys', $StatusCode, $Status, $Reason), 'selectOne');
        if ($Status == 'OK' && (!isset($array->resultados) || count($array->resultados) == 0)) {
            $id_resultado = SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_',
                array($cuit, $nombre_persona, $id_padron, 'worldsys',
                    $StatusCode,
                    $Status,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    'N'),
                'selectOne');
            $error = array();
            self::$id_resultados[] = $id_resultado->id_resultado;
            return $error;

        }

        //---------------------------------------------  HASTA ACA  ----------------------------------------------------------------
        $rr = array();
        $esultado_final = array();
        $registro_definido = array();
        if ($Status == 'OK' && isset($array->resultados) && count($array->resultados) > 0) {
            if ($id_tributaria == 'null' && $cuit_n == 'null') {
                //echo(var_dump($array->resultados)); die();
                foreach ($array->resultados as $data) {
                    //$res_ws = array();
                    $res_ws = new stdClass();
                    // SAN_UIF_AR
                    //--
                    $array_filtro = [' ', '/', '.', '-' . '_'];
                    $documento_comparacion = str_replace($array_filtro, '', $data->documento);
                    $identificacionTributaria_comparacion = str_replace($array_filtro, '', $data->identificacionTributaria);
                    //--
                    if (($data->residencia == 'AR' && is_null($data->identificacionTributaria) && $data->tipoFuente == 'SAN' && Misc::esElMismoNombre($nombre_persona, $data->nombre)) || ($data->residencia == 'AR' && $data->identificacionTributaria == $cuit) || ($data->residencia == 'AR' && $data->documento == $cuit2 && $data->tipoFuente == 'TER') || ($data->residencia != 'AR' && $data->residencia == $pais && ($documento_comparacion == $cuit || $identificacionTributaria_comparacion == $cuit || (empty($identificacionTributaria_comparacion) && empty($documento_comparacion))))) {
                        $res_ws->index = isset($data->index) ? $data->index : '';
                        $res_ws->id = isset($data->id) ? $data->id : '';
                        $res_ws->score = isset($data->score) ? $data->score : '';
                        $res_ws->fuente = isset($data->fuente) ? $data->fuente : '';
                        $res_ws->tipoFuente = isset($data->tipoFuente) ? $data->tipoFuente : '';
                        $res_ws->descripcionFuente = isset($data->descripcionFuente) ? $data->descripcionFuente : '';
                        $res_ws->sdnId = isset($data->sdnId) ? $data->sdnId : '';
                        $res_ws->fechaNovedad = isset($data->fechaNovedad) ? $data->fechaNovedad : '';
                        $res_ws->nombre = isset($data->nombre) ? $data->nombre : '';
                        $res_ws->documento = isset($data->documento) ? $data->documento : '';
                        $res_ws->identificacionTributaria = isset($data->identificacionTributaria) ? $data->identificacionTributaria : '';
                        $res_ws->institucion = isset($data->institucion) ? $data->institucion : '';
                        $res_ws->cargo = isset($data->cargo) ? $data->cargo : '';
                        $res_ws->relacion = isset($data->relacion) ? $data->relacion : '';
                        $res_ws->domicilio = isset($data->domicilio) ? $data->domicilio : '';
                        $res_ws->residencia = isset($data->residencia) ? $data->residencia : '';
                        $res_ws->descripcionPais = isset($data->descripcionPais) ? $data->descripcionPais : '';
                        $res_ws->url = isset($data->url) ? $data->url : '';
                        $res_ws->evaluacion = isset($data->evaluacion) ? $data->evaluacion : '';
                        $res_ws->existeDocumentacion = isset($data->existeDocumentacion) ? $data->existeDocumentacion : '';

                        $comparador = ($data->relacion != '' && $data->tipoFuente == 'PEP') ? 'RR' : $data->tipoFuente;

                        switch ($comparador) {
                            case 'TER':
                                $res_ws->fidecheck = 'P';  //-> ROJO - P
                                $res_ws->orden = 2;
                                $res_ws->tipoFuente = $data->descripcionFuente;
                                break;

                            case 'PEP':
                                $res_ws->fidecheck = 'E'; //-> NARANJA - E
                                $res_ws->orden = 3;
                                break;

                            case 'SAN':
                                $res_ws->fidecheck = 'P'; //-> ROJO - P
                                $res_ws->orden = 2;
                                $res_ws->tipoFuente = $data->descripcionFuente;
                                break;

                            case 'SO':
                                $res_ws->fidecheck = 'S'; //-> CELESTE - S --## PUEDEN VARIAR
                                $res_ws->orden = 3;
                                $res_ws->tipoFuente = 'sujeto obligado';
                                break;

                            case 'RR':
                                $res_ws->fidecheck = 'R'; //-> AMARILLO - R --## PUEDEN VARIAR
                                $res_ws->orden = 4;
                                break;

                            default:
                                $res_ws->fidecheck = 'N'; //-> VERDE - N
                                $res_ws->orden = 2;
                                break;
                        }
                        //---
                        if (($data->residencia != 'AR' && $data->residencia == $pais) && ($data->documento == $cuit || $data->identificacionTributaria == $cuit) && Misc::esElMismoNombre($nombre_persona, $data->nombre)) {
                            $registro_definido[] = $res_ws;
                            return $registro_definido;
                        }
                        //---
                        $esultado_final[] = $res_ws;
                    }

                }
                //--
                //echo(var_dump($esultado_final)); die();
                return $esultado_final;
            }
            echo ("ingresa 2");
            die();
            foreach ($array->resultados as $data) {
                $error = 'OK';
                $Id = (isset($data->sdnId)) ? $data->sdnId : '';
                $Fuente = (isset($data->fuente)) ? $data->fuente : '';
                $NombreModificado = (isset($data->nombre)) ? $data->nombre : '';
                $DocumentoBuscado = $cuit;//(isset($data->documento)) ? $data->documento : ''; 
                $NombreBuscado = '';
                $Documento = (isset($data->documento)) ? $data->documento : '';
                $TipoFuente = (isset($data->tipoFuente)) ? $data->tipoFuente : '';
                $Residencia = (isset($data->residencia)) ? $data->residencia : '';
                $DescripcionPais = (isset($data->descripcionPais)) ? $data->descripcionPais : '';
                $PaisNoColaborativo = '';
                $Hallazgos = '';
                $ExisteDocumentacion = (isset($data->existeDocumentacion)) ? $data->existeDocumentacion : '';
                $PorcentajeSimilitud = '';
                //--------------------------------------------------------------------------------------------------------------
                $Codigo = isset($data->Codigo) ? $data->Codigo : '';
                $TipoFuente = isset($data->tipoFuente) ? $data->tipoFuente : '';
                $FechaNovedad = isset($data->fechaNovedad) ? $data->fechaNovedad : '';
                $Cargo = isset($data->cargo) ? $data->cargo : '';
                $Institucion = (isset($data->institucion)) ? $data->institucion : '';
                $Domicilio = (isset($data->domicilio)) ? $data->domicilio : '';
                $NumeroDocumento = (isset($data->documento)) ? $data->documento : '';
                $NumeroIdTributaria = (isset($data->identificacionTributaria)) ? $data->identificacionTributaria : '';
                $Url = (isset($data->url)) ? $data->url : '';
                $Relacion = (isset($data->relacion)) ? $data->relacion : '';
                $rr[] = $Relacion;
                $PrincipalLista = $Fuente;
                $PrincipalListaDescripcion = (isset($data->descripcionFuente)) ? $data->descripcionFuente : '';
                $PaisSwift = $Residencia;
                $TipoNovedad = ''; //--> verificar
                $IdOrigRel = ''; //--> verificar
                $PrincipalFuente = ''; //--> verificar
                $Observaciones = ''; //--> verificar
                $Pais = $DescripcionPais;
                $UrlNew = $Url;
                $NormaUif = ''; //--> verificar
                $NormaUifDescripcion = ''; //--> verificar
                $FuenteLista = $Fuente;
                $FuenteActiva = ''; //--> verificar
                $FuenteDescripcion = $PrincipalListaDescripcion;
                $FuenteDescripcionLarga = $PrincipalListaDescripcion;
                $FuenteTipo = $TipoFuente;
                $FuenteImagen = ''; //--> verificar
                $FuenteActualizaxml = ''; //--> verificar

                //--------------------------------------------------------------------------------------------------------------
                $NombreModificado = self::limpiarCaracteresEspeciales(utf8_decode($NombreModificado));
                $NombreBuscado = self::limpiarCaracteresEspeciales(utf8_decode($NombreBuscado));
                $Cargo = self::limpiarCaracteresEspeciales(utf8_decode($Cargo));
                $Institucion = self::limpiarCaracteresEspeciales(utf8_decode($Institucion));
                $Domicilio = self::limpiarCaracteresEspeciales(utf8_decode($Domicilio));
                $Relacion = self::limpiarCaracteresEspeciales(utf8_decode($Relacion));

                //--  DESCOMENTAR ESTE BLOQUE PARA PRODUCCION O COMENTAR PARA DEBUG  --//
                /*$id_resultado = SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_', 
                                                                 array($cuit,$nombre_persona,$id_padron,'worldsys',
                                                                 $StatusCode,
                                                                 $Status              ,
                                                                 $Reason              ,
                                                                 $Id                  ,
                                                                 $Fuente              ,
                                                                 $NombreModificado    ,
                                                                 $DocumentoBuscado    ,
                                                                 $NombreBuscado       ,
                                                                 $Documento           ,
                                                                 $TipoFuente          ,
                                                                 $Residencia          ,
                                                                 $DescripcionPais     ,
                                                                 $PaisNoColaborativo  ,
                                                                 $Hallazgos           ,
                                                                 $ExisteDocumentacion ,
                                                                 $PorcentajeSimilitud,
                                                                 'S'),
                                                                 'selectOne'); 
                self::$id_resultados[] = $id_resultado->id_resultado; */
                /*SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_mas_datos_',   array(
                    $id_resultado, $Id,  
                    $StatusCode          ,
                    $Status              ,
                    $Codigo              ,
                    $TipoFuente          ,
                    $FechaNovedad        ,
                    $Cargo,
                    $Institucion,
                    $Domicilio,
                    $NumeroDocumento     ,
                    $NumeroIdTributaria  ,
                    $Url, 
                    $Relacion,
                    $PrincipalLista,
                    $PrincipalListaDescripcion,
                    $PaisSwift,
                    $TipoNovedad,
                    $IdOrigRel,
                    $PrincipalFuente,
                    $Observaciones,
                    $Pais,
                    $UrlNew,
                    $NormaUif,
                    $NormaUifDescripcion,
                    $FuenteLista,
                    $FuenteActiva,
                    $FuenteDescripcion,
                    $FuenteDescripcionLarga,
                    $FuenteTipo,
                    $FuenteImagen,
                    $FuenteActualizaxml
                    ),'selectOne');*/
                //-------------------  HASTA ACA  ---------------------------------------------------------------//

            }
            for ($i = 0; $i < count($array->resultados); $i++) {
                $comparador = ($array->resultados[$i]->relacion != '' && $array->resultados[$i]->tipoFuente == 'PEP') ? 'RR' : $array->resultados[$i]->tipoFuente;
                $array->resultados[$i]->relacion = $rr[$i];
                //--  SE FORMATEA FECHA  --//
                if ($array->resultados[$i]->fechaNovedad !== null) {
                    $feche_temporal = $array->resultados[$i]->fechaNovedad;
                    $feche_temporal = explode('T', $feche_temporal);
                    $feche_temporal = explode('-', $feche_temporal[0]);
                    $array->resultados[$i]->fechaNovedad = $feche_temporal[2] . '-' . $feche_temporal[1] . '-' . $feche_temporal[0];
                } else {
                    $array->resultados[$i]->fechaNovedad = 'S/F';
                }

                switch ($comparador) {
                    case 'TER':
                        $array->resultados[$i]->fidecheck = 'P';  //-> ROJO - P
                        $array->resultados[$i]->orden = 2;
                        $array->resultados[$i]->tipoFuente = $array->resultados[$i]->descripcionFuente;
                        break;

                    case 'PEP':
                        $array->resultados[$i]->fidecheck = 'E'; //-> NARANJA - E
                        $array->resultados[$i]->orden = 3;
                        break;

                    case 'SAN':
                        $array->resultados[$i]->fidecheck = 'P'; //-> ROJO - P
                        $array->resultados[$i]->orden = 2;
                        /*$array->resultados[$i]->orden = 3;*/
                        $array->resultados[$i]->tipoFuente = $array->resultados[$i]->descripcionFuente;
                        break;

                    case 'SO':
                        $array->resultados[$i]->fidecheck = 'S'; //-> CELESTE - S --## PUEDEN VARIAR
                        $array->resultados[$i]->orden = 3;
                        $array->resultados[$i]->tipoFuente = 'sujeto obligado';
                        break;

                    case 'RR':
                        $array->resultados[$i]->fidecheck = 'R'; //-> AMARILLO - R --## PUEDEN VARIAR
                        $array->resultados[$i]->orden = 4;
                        break;

                    default:
                        $array->resultados[$i]->fidecheck = 'N'; //-> VERDE - N
                        $array->resultados[$i]->orden = 2;
                        break;
                }
            }
            return $array->resultados;
        }
        return $error;
        //--  DEBUG  --//

    }

    //-- Este es un backup temporal 14-07-2022 - claudio
    public static function CurlPEPListas_BackUp($cuit, $nombre_persona, $id_padron, $element, $url, $token, $id_llamada, $pais) {
        $resulado_alterno = array();
        $flag = '';
        //$pais = '';
        //echo($cuit.' - '.$nombre_persona.' - '.$id_padron.' - '.$element.' - '.$url.' - '.$token.' - '.$id_llamada.' - '.$pais); die();

        /* 22/12/2021: Si es de Argentina, id_tributaria es el CUIT, y documento lo del medio 
                    if($cuit[0] != '3') {
                        $cuit2 = (strlen($cuit) == 11) ? substr($cuit, 2, -1) : $cuit;
                        $cuit2 = ($cuit2[0] == '0') ? substr($cuit2, 1) : $cuit2;
                        $id_tributaria = 'null';

                    } else {
                        $id_tributaria = $cuit;
                        $cuit2 = 'null';
                    }
        */
        if ($pais == 'AR') {
            $id_tributaria = $cuit;
            if ($cuit[0] == '3') {
                $cuit2 = 'null';
            } else {
                $cuit2 = (strlen($cuit) == 11) ? substr($cuit, 2, -1) : $cuit;
                $dni = intval($cuit2);
                $cuit2 = $dni;
            }
        } else {
            if ($cuit[0] != '3') {
                $cuit2 = (strlen($cuit) == 11) ? substr($cuit, 2, -1) : $cuit;
                $cuit2 = ($cuit2[0] == '0') ? substr($cuit2, 1) : $cuit2;
                $id_tributaria = $cuit;

            } else {
                $id_tributaria = $cuit;
                $cuit2 = 'null';
            }
        }
        /*
        var_dump($id_tributaria);
        var_dump($cuit2);
        die(); */
        /*$cuit2 = (strlen($cuit) == 11) ? substr($cuit, 2, -1) : $cuit;
        $cuit2 = ($cuit2[0] == '0') ? substr($cuit2, 1) : $cuit2;
        $id_tributaria = 'null';*/

        $factorSimilitud = ($pais == 'AR') ? '100' : '90';
        //if ($pais == 'AR' && !empty($id_tributaria)) { $nombre_persona = '';}
        $factorSimilitudInverso = ($pais == 'AR') ? '30' : '70';
        //echo(var_dump(array('Nombre Persona'=>$nombre_persona,'Cuit2'=>$cuit2,'Id tributaria'=>$id_tributaria,'Pais'=>$pais))); die();
        //------------------------------------------------------------------------------------------------------
        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "{\n \"nombre\": \"$nombre_persona\",\n \"documento\": $cuit2,\n \"identificacionTributaria\": $id_tributaria,\n \"factorSimilitud\": $factorSimilitud,\n \"factorSimilitudInverso\": $factorSimilitudInverso,\n \"tipoFuente\": \"Todas\",\n }\n",
            CURLOPT_HTTPHEADER => [
                "Content-Type: application/json"
            ],
        ]);

        $response = curl_exec($curl);
        //echo(var_dump($response)); die(); 
        $err = curl_error($curl);
        $flag = '1';
        curl_close($curl);
        //------------------------------------------------------------------------------------------------------
        //--  SE DEBE MEJORAR ESTO  --//
        $cuit_n = 'null';
        $id_tributaria = 'null';
        $dato_temporal = json_decode($response);
        //echo(var_dump($dato_temporal)); die();
        if (isset($dato_temporal->resultados[0]->residencia) && $dato_temporal->resultados[0]->residencia != 'AR') {
            $curl = curl_init();

            curl_setopt_array($curl, [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => "{\n \"nombre\": \"$nombre_persona\",\n \"documento\": $cuit_n,\n \"identificacionTributaria\": $id_tributaria,\n \"factorSimilitud\": $factorSimilitud,\n \"factorSimilitudInverso\": $factorSimilitudInverso,\n \"tipoFuente\": \"Todas\",\n }\n",
                CURLOPT_HTTPHEADER => [
                    "Content-Type: application/json"
                ],
            ]);

            $response = curl_exec($curl);
            $err = curl_error($curl);
            $flag = '';
            curl_close($curl);
        }
        //------------------------------------------------------------------------------------------------------
        if ($err) {
            $error = "cURL Error #:" . $err . ' ' . $response;
            if ($err == '' || !is_numeric($err)) {
                $err = -100;
            }
            //--  DESCOMENTAR ESTO PARA PRODUCCION O COMENTAR PARA DEBUG
            $error_llamada = SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_llamados_', array('update', $id_llamada, $cuit, $nombre_persona, $id_padron, 'worldsys', $err, 'CURL Error', $error), 'selectOne');
            //-----------------------------------------------
            return $error;
        }

        $error = 'OK';

        //--  VARIABLE  --//
        $StatusCode = '';
        $Status = 'OK';
        $Reason = '';
        //---------------//

        /*
        EVALUAR SI ESTO SIGUE SIENDO NECESARIO

        $response = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $response);
        $response = str_replace('', '\'', $response);
        
        $xml = new \SimpleXMLElement($response);
        
        $array = json_decode(json_encode((array)$xml), TRUE);*/
        $array = json_decode($response);
        //echo(var_dump($array->resultados)); die();
        if (isset($array->code)) {
            $StatusCode = $array->code;
            $Status = '000';
            $Reason = $array->message;

            if ($StatusCode != '200') {
                $error = $StatusCode;
                //return $error;
                return $datos_finales = array();
            }

        }

        if ($StatusCode == '' || !is_numeric($StatusCode)) {
            $StatusCode = -100;
        }
        //--  DESCOMENTAR TODA ESTA SECCION PARA PRODUCCION O COMENTAR PARA DEBUG
        $error_llamada = SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_llamados_', array('update', $id_llamada, $cuit, $nombre_persona, $id_padron, 'worldsys', $StatusCode, $Status, $Reason), 'selectOne');
        if ($Status == 'OK' && (!isset($array->resultados) || count($array->resultados) == 0)) {
            $id_resultado = SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_',
                array($cuit, $nombre_persona, $id_padron, 'worldsys',
                    $StatusCode,
                    $Status,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    'N'),
                'selectOne');
            $error = array();
            self::$id_resultados[] = $id_resultado->id_resultado;
            return $error;

        }
        //---------------------------------------------  HASTA ACA  ----------------------------------------------------------------
        $rr = array();
        $esultado_final = array();
        $registro_definido = array();
        //echo(var_dump($array->resultados)); die();
        if ($Status == 'OK' && isset($array->resultados) && count($array->resultados) > 0) {
            //echo(var_dump($flag)); die(); // $flag == '1' && 
            if ($id_tributaria == 'null' && $cuit_n == 'null') {
                foreach ($array->resultados as $data) {
                    //$res_ws = array();
                    $res_ws = new stdClass();
                    // SAN_UIF_AR
                    //--
                    $array_filtro = [' ', '/', '.', '-' . '_'];
                    $documento_comparacion = str_replace($array_filtro, '', $data->documento);
                    $identificacionTributaria_comparacion = str_replace($array_filtro, '', $data->identificacionTributaria);
                    //--
                    //if((!isset($data->documento) || $data->documento == $cuit2) && $data->residencia == 'AR') {    
                    if (($data->residencia == 'AR' && is_null($data->identificacionTributaria) && $data->tipoFuente == 'SAN' && Misc::esElMismoNombre($nombre_persona, $data->nombre)) || ($data->residencia == 'AR' && $data->identificacionTributaria == $cuit) || ($data->residencia == 'AR' && $data->documento == $cuit2 && $data->tipoFuente == 'TER') || ($data->residencia != 'AR' && $data->residencia == $pais && ($documento_comparacion == $cuit || $identificacionTributaria_comparacion == $cuit || (empty($identificacionTributaria_comparacion) && empty($documento_comparacion))))) {
                        //if(($data->residencia == 'AR' && is_null($data->identificacionTributaria) && $data->tipoFuente == 'SAN' && Misc::esElMismoNombre($nombre_persona, $data->nombre)) || ($data->residencia == 'AR' && $data->identificacionTributaria == $cuit) || ($data->residencia == 'AR' && $data->documento == $cuit2 && $data->tipoFuente == 'TER') || ( ( $data->residencia != 'AR' && Misc::esElMismoNombre($nombre_persona, $data->nombre)  ) )) {
                        $res_ws->index = isset($data->index) ? $data->index : '';
                        $res_ws->id = isset($data->id) ? $data->id : '';
                        $res_ws->score = isset($data->score) ? $data->score : '';
                        $res_ws->fuente = isset($data->fuente) ? $data->fuente : '';
                        $res_ws->tipoFuente = isset($data->tipoFuente) ? $data->tipoFuente : '';
                        $res_ws->descripcionFuente = isset($data->descripcionFuente) ? $data->descripcionFuente : '';
                        $res_ws->sdnId = isset($data->sdnId) ? $data->sdnId : '';
                        $res_ws->fechaNovedad = isset($data->fechaNovedad) ? $data->fechaNovedad : '';
                        $res_ws->nombre = isset($data->nombre) ? $data->nombre : '';
                        $res_ws->documento = isset($data->documento) ? $data->documento : '';
                        $res_ws->identificacionTributaria = isset($data->identificacionTributaria) ? $data->identificacionTributaria : '';
                        $res_ws->institucion = isset($data->institucion) ? $data->institucion : '';
                        $res_ws->cargo = isset($data->cargo) ? $data->cargo : '';
                        $res_ws->relacion = isset($data->relacion) ? $data->relacion : '';
                        $res_ws->domicilio = isset($data->domicilio) ? $data->domicilio : '';
                        $res_ws->residencia = isset($data->residencia) ? $data->residencia : '';
                        $res_ws->descripcionPais = isset($data->descripcionPais) ? $data->descripcionPais : '';
                        $res_ws->url = isset($data->url) ? $data->url : '';
                        $res_ws->evaluacion = isset($data->evaluacion) ? $data->evaluacion : '';
                        $res_ws->existeDocumentacion = isset($data->existeDocumentacion) ? $data->existeDocumentacion : '';

                        $comparador = ($data->relacion != '' && $data->tipoFuente == 'PEP') ? 'RR' : $data->tipoFuente;

                        switch ($comparador) {
                            case 'TER':
                                $res_ws->fidecheck = 'P';  //-> ROJO - P
                                $res_ws->orden = 2;
                                $res_ws->tipoFuente = $data->descripcionFuente;
                                break;

                            case 'PEP':
                                $res_ws->fidecheck = 'E'; //-> NARANJA - E
                                $res_ws->orden = 3;
                                break;

                            case 'SAN':
                                $res_ws->fidecheck = 'P'; //-> ROJO - P
                                $res_ws->orden = 2;
                                /*$res_ws['orden'] = 3;*/
                                $res_ws->tipoFuente = $data->descripcionFuente;
                                break;

                            case 'SO':
                                $res_ws->fidecheck = 'S'; //-> CELESTE - S --## PUEDEN VARIAR
                                $res_ws->orden = 3;
                                $res_ws->tipoFuente = 'sujeto obligado';
                                break;

                            case 'RR':
                                $res_ws->fidecheck = 'R'; //-> AMARILLO - R --## PUEDEN VARIAR
                                $res_ws->orden = 4;
                                break;

                            default:
                                $res_ws->fidecheck = 'N'; //-> VERDE - N
                                $res_ws->orden = 2;
                                break;
                        }
                        //---
                        if (($data->residencia != 'AR' && $data->residencia == $pais) && ($data->documento == $cuit || $data->identificacionTributaria == $cuit) && Misc::esElMismoNombre($nombre_persona, $data->nombre)) {
                            $registro_definido[] = $res_ws;
                            return $registro_definido;
                        }
                        //---
                        $esultado_final[] = $res_ws;
                    }

                }
                //--
                //echo(var_dump($esultado_final)); die();
                return $esultado_final;
            }
            foreach ($array->resultados as $data) {
                $error = 'OK';
                $Id = (isset($data->sdnId)) ? $data->sdnId : '';
                $Fuente = (isset($data->fuente)) ? $data->fuente : '';
                $NombreModificado = (isset($data->nombre)) ? $data->nombre : '';
                $DocumentoBuscado = $cuit;//(isset($data->documento)) ? $data->documento : ''; 
                $NombreBuscado = '';
                $Documento = (isset($data->documento)) ? $data->documento : '';
                $TipoFuente = (isset($data->tipoFuente)) ? $data->tipoFuente : '';
                $Residencia = (isset($data->residencia)) ? $data->residencia : '';
                $DescripcionPais = (isset($data->descripcionPais)) ? $data->descripcionPais : '';
                $PaisNoColaborativo = '';
                $Hallazgos = '';
                $ExisteDocumentacion = (isset($data->existeDocumentacion)) ? $data->existeDocumentacion : '';
                $PorcentajeSimilitud = '';
                //--------------------------------------------------------------------------------------------------------------
                $Codigo = isset($data->Codigo) ? $data->Codigo : '';
                $TipoFuente = isset($data->tipoFuente) ? $data->tipoFuente : '';
                $FechaNovedad = isset($data->fechaNovedad) ? $data->fechaNovedad : '';
                $Cargo = isset($data->cargo) ? $data->cargo : '';
                $Institucion = (isset($data->institucion)) ? $data->institucion : '';
                $Domicilio = (isset($data->domicilio)) ? $data->domicilio : '';
                $NumeroDocumento = (isset($data->documento)) ? $data->documento : '';
                $NumeroIdTributaria = (isset($data->identificacionTributaria)) ? $data->identificacionTributaria : '';
                $Url = (isset($data->url)) ? $data->url : '';
                $Relacion = (isset($data->relacion)) ? $data->relacion : '';
                $rr[] = $Relacion;
                $PrincipalLista = $Fuente;
                $PrincipalListaDescripcion = (isset($data->descripcionFuente)) ? $data->descripcionFuente : '';
                $PaisSwift = $Residencia;
                $TipoNovedad = ''; //--> verificar
                $IdOrigRel = ''; //--> verificar
                $PrincipalFuente = ''; //--> verificar
                $Observaciones = ''; //--> verificar
                $Pais = $DescripcionPais;
                $UrlNew = $Url;
                $NormaUif = ''; //--> verificar
                $NormaUifDescripcion = ''; //--> verificar
                $FuenteLista = $Fuente;
                $FuenteActiva = ''; //--> verificar
                $FuenteDescripcion = $PrincipalListaDescripcion;
                $FuenteDescripcionLarga = $PrincipalListaDescripcion;
                $FuenteTipo = $TipoFuente;
                $FuenteImagen = ''; //--> verificar
                $FuenteActualizaxml = ''; //--> verificar

                //--------------------------------------------------------------------------------------------------------------
                $NombreModificado = self::limpiarCaracteresEspeciales(utf8_decode($NombreModificado));
                $NombreBuscado = self::limpiarCaracteresEspeciales(utf8_decode($NombreBuscado));
                $Cargo = self::limpiarCaracteresEspeciales(utf8_decode($Cargo));
                $Institucion = self::limpiarCaracteresEspeciales(utf8_decode($Institucion));
                $Domicilio = self::limpiarCaracteresEspeciales(utf8_decode($Domicilio));
                $Relacion = self::limpiarCaracteresEspeciales(utf8_decode($Relacion));

                //--  DESCOMENTAR ESTE BLOQUE PARA PRODUCCION O COMENTAR PARA DEBUG  --//
                /*$id_resultado = SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_', 
                                                                array($cuit,$nombre_persona,$id_padron,'worldsys',
                                                                $StatusCode,
                                                                $Status              ,
                                                                $Reason              ,
                                                                $Id                  ,
                                                                $Fuente              ,
                                                                $NombreModificado    ,
                                                                $DocumentoBuscado    ,
                                                                $NombreBuscado       ,
                                                                $Documento           ,
                                                                $TipoFuente          ,
                                                                $Residencia          ,
                                                                $DescripcionPais     ,
                                                                $PaisNoColaborativo  ,
                                                                $Hallazgos           ,
                                                                $ExisteDocumentacion ,
                                                                $PorcentajeSimilitud,
                                                                'S'),
                                                                'selectOne'); 
                self::$id_resultados[] = $id_resultado->id_resultado; */
                /*SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_mas_datos_',   array(
                    $id_resultado, $Id,  
                    $StatusCode          ,
                    $Status              ,
                    $Codigo              ,
                    $TipoFuente          ,
                    $FechaNovedad        ,
                    $Cargo,
                    $Institucion,
                    $Domicilio,
                    $NumeroDocumento     ,
                    $NumeroIdTributaria  ,
                    $Url, 
                    $Relacion,
                    $PrincipalLista,
                    $PrincipalListaDescripcion,
                    $PaisSwift,
                    $TipoNovedad,
                    $IdOrigRel,
                    $PrincipalFuente,
                    $Observaciones,
                    $Pais,
                    $UrlNew,
                    $NormaUif,
                    $NormaUifDescripcion,
                    $FuenteLista,
                    $FuenteActiva,
                    $FuenteDescripcion,
                    $FuenteDescripcionLarga,
                    $FuenteTipo,
                    $FuenteImagen,
                    $FuenteActualizaxml
                    ),'selectOne');*/
                //-------------------  HASTA ACA  ---------------------------------------------------------------//

                //-->  ESTA LINEA SE USABA ANTERIORMENTE PERO YA NO ES NECESARIA  
                //$estado_mas = self::obtenerMasDatosPEP($id_resultado->id_resultado,$Id,$token);
                //echo("------------------------------------------------------------------------------------- <br>");
                /* echo('Id: '.$Id.' -<br> Fuente: '.$Fuente.' -<br> NombreModificado: '.$NombreModificado.' -<br> DocumentoBuscado:'.$DocumentoBuscado.' -<br> NombreBuscado: '.$NombreBuscado.' -<br> Documento: '.$Documento.
                ' -<br> TipoFuente: '.$TipoFuente.' -<br> Residencia: '.$Residencia.' -<br> DescripcionPais: '.$DescripcionPais.' -<br> ExisteDocumentacion: '.$ExisteDocumentacion.' -<br> Codigo: '.$Codigo.' -<br> TipoFuente: '.$TipoFuente.
                ' -<br> FechaNovedad: '.$FechaNovedad.' -<br> Cargo: '.$Cargo.' -<br> Institucion: '.$Institucion.' -<br> Domicilio: '.$Domicilio.' -<br> NumeroIdTributaria: '.$NumeroIdTributaria.' -<br> Url: '.$Url.' <br> ');*/
            }
            for ($i = 0; $i < count($array->resultados); $i++) {
                $comparador = ($array->resultados[$i]->relacion != '' && $array->resultados[$i]->tipoFuente == 'PEP') ? 'RR' : $array->resultados[$i]->tipoFuente;
                $array->resultados[$i]->relacion = $rr[$i];
                //--  SE FORMATEA FECHA  --//
                if ($array->resultados[$i]->fechaNovedad !== null) {
                    $feche_temporal = $array->resultados[$i]->fechaNovedad;
                    $feche_temporal = explode('T', $feche_temporal);
                    $feche_temporal = explode('-', $feche_temporal[0]);
                    $array->resultados[$i]->fechaNovedad = $feche_temporal[2] . '-' . $feche_temporal[1] . '-' . $feche_temporal[0];
                } else {
                    $array->resultados[$i]->fechaNovedad = 'S/F';
                }

                switch ($comparador) {
                    case 'TER':
                        $array->resultados[$i]->fidecheck = 'P';  //-> ROJO - P
                        $array->resultados[$i]->orden = 2;
                        $array->resultados[$i]->tipoFuente = $array->resultados[$i]->descripcionFuente;
                        break;

                    case 'PEP':
                        $array->resultados[$i]->fidecheck = 'E'; //-> NARANJA - E
                        $array->resultados[$i]->orden = 3;
                        break;

                    case 'SAN':
                        $array->resultados[$i]->fidecheck = 'P'; //-> ROJO - P
                        $array->resultados[$i]->orden = 2;
                        /*$array->resultados[$i]->orden = 3;*/
                        $array->resultados[$i]->tipoFuente = $array->resultados[$i]->descripcionFuente;
                        break;

                    case 'SO':
                        $array->resultados[$i]->fidecheck = 'S'; //-> CELESTE - S --## PUEDEN VARIAR
                        $array->resultados[$i]->orden = 3;
                        $array->resultados[$i]->tipoFuente = 'sujeto obligado';
                        break;

                    case 'RR':
                        $array->resultados[$i]->fidecheck = 'R'; //-> AMARILLO - R --## PUEDEN VARIAR
                        $array->resultados[$i]->orden = 4;
                        break;

                    default:
                        $array->resultados[$i]->fidecheck = 'N'; //-> VERDE - N
                        $array->resultados[$i]->orden = 2;
                        break;
                }
            }
            //echo(var_dump($array->resultados)); die();
            //echo(var_dump(self::$id_resultados)); die();
            return $array->resultados;
        }
        return $error;
        //--  DEBUG  --//

    }

    public static function CurlPEPListasOriginal($cuit, $nombre_persona, $id_padron, $element, $url, $token, $id_llamada, $pais) {
        $resulado_alterno = array();
        $flag = '';
        $pais = '';
        //echo($cuit.' - '.$nombre_persona.' - '.$id_padron.' - '.$element.' - '.$url.' - '.$token.' - '.$id_llamada.' - '.$pais); die();

        /* 22/12/2021: Si es de Argentina, id_tributaria es el CUIT, y documento lo del medio 
                    if($cuit[0] != '3') {
                        $cuit2 = (strlen($cuit) == 11) ? substr($cuit, 2, -1) : $cuit;
                        $cuit2 = ($cuit2[0] == '0') ? substr($cuit2, 1) : $cuit2;
                        $id_tributaria = 'null';

                    } else {
                        $id_tributaria = $cuit;
                        $cuit2 = 'null';
                    }
        */
        if ($pais == 'AR') {
            $id_tributaria = $cuit;
            if ($cuit[0] == '3') {
                $cuit2 = 'null';
            } else {
                $cuit2 = (strlen($cuit) == 11) ? substr($cuit, 2, -1) : $cuit;
                $dni = intval($cuit2);
                $cuit2 = $dni;
            }
        } else {
            if ($cuit[0] != '3') {
                $cuit2 = (strlen($cuit) == 11) ? substr($cuit, 2, -1) : $cuit;
                $cuit2 = ($cuit2[0] == '0') ? substr($cuit2, 1) : $cuit2;
                $id_tributaria = $cuit;

            } else {
                $id_tributaria = $cuit;
                $cuit2 = 'null';
            }
        }
        /*
        var_dump($id_tributaria);
        var_dump($cuit2);
        die(); */
        /*$cuit2 = (strlen($cuit) == 11) ? substr($cuit, 2, -1) : $cuit;
        $cuit2 = ($cuit2[0] == '0') ? substr($cuit2, 1) : $cuit2;
        $id_tributaria = 'null';*/

        $factorSimilitud = ($pais == 'AR') ? '100' : '90';
        //if ($pais == 'AR' && !empty($id_tributaria)) { $nombre_persona = '';}
        $factorSimilitudInverso = ($pais == 'AR') ? '30' : '70';
        //echo(var_dump(array('Nombre Persona'=>$nombre_persona,'Cuit2'=>$cuit2,'Id tributaria'=>$id_tributaria,'Pais'=>$pais))); die();
        //------------------------------------------------------------------------------------------------------
        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "{\n \"nombre\": \"$nombre_persona\",\n \"documento\": $cuit2,\n \"identificacionTributaria\": $id_tributaria,\n \"factorSimilitud\": $factorSimilitud,\n \"factorSimilitudInverso\": $factorSimilitudInverso,\n \"tipoFuente\": \"Todas\",\n }\n",
            CURLOPT_HTTPHEADER => [
                "Content-Type: application/json"
            ],
        ]);

        $response = curl_exec($curl);
        //echo(var_dump($response)); die(); 
        $err = curl_error($curl);
        $flag = '1';
        curl_close($curl);
        //------------------------------------------------------------------------------------------------------
        //--  SE DEBE MEJORAR ESTO  --//
        $cuit_n = 'null';
        $id_tributaria = 'null';
        $dato_temporal = json_decode($response);
        //echo(var_dump($dato_temporal)); die();
        if (isset($dato_temporal->resultados[0]->residencia) && $dato_temporal->resultados[0]->residencia != 'AR') {
            $curl = curl_init();

            curl_setopt_array($curl, [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => "{\n \"nombre\": \"$nombre_persona\",\n \"documento\": $cuit_n,\n \"identificacionTributaria\": $id_tributaria,\n \"factorSimilitud\": $factorSimilitud,\n \"factorSimilitudInverso\": $factorSimilitudInverso,\n \"tipoFuente\": \"Todas\",\n }\n",
                CURLOPT_HTTPHEADER => [
                    "Content-Type: application/json"
                ],
            ]);

            $response = curl_exec($curl);
            $err = curl_error($curl);
            $flag = '';
            curl_close($curl);
        }
        //------------------------------------------------------------------------------------------------------
        if ($err) {
            $error = "cURL Error #:" . $err . ' ' . $response;
            if ($err == '' || !is_numeric($err)) {
                $err = -100;
            }
            //--  DESCOMENTAR ESTO PARA PRODUCCION O COMENTAR PARA DEBUG
            $error_llamada = SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_llamados_', array('update', $id_llamada, $cuit, $nombre_persona, $id_padron, 'worldsys', $err, 'CURL Error', $error), 'selectOne');
            //-----------------------------------------------
            return $error;
        }

        $error = 'OK';

        //--  VARIABLE  --//
        $StatusCode = '';
        $Status = 'OK';
        $Reason = '';
        //---------------//

        /*
        EVALUAR SI ESTO SIGUE SIENDO NECESARIO

        $response = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $response);
        $response = str_replace('', '\'', $response);
        
        $xml = new \SimpleXMLElement($response);
        
        $array = json_decode(json_encode((array)$xml), TRUE);*/
        $array = json_decode($response);
        //echo(var_dump($array->resultados)); die();
        if (isset($array->code)) {
            $StatusCode = $array->code;
            $Status = '000';
            $Reason = $array->message;

            if ($StatusCode != '200') {
                $error = $StatusCode;
                //return $error;
                return $datos_finales = array();
            }

        }

        if ($StatusCode == '' || !is_numeric($StatusCode)) {
            $StatusCode = -100;
        }
        //--  DESCOMENTAR TODA ESTA SECCION PARA PRODUCCION O COMENTAR PARA DEBUG
        $error_llamada = SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_llamados_', array('update', $id_llamada, $cuit, $nombre_persona, $id_padron, 'worldsys', $StatusCode, $Status, $Reason), 'selectOne');
        if ($Status == 'OK' && (!isset($array->resultados) || count($array->resultados) == 0)) {
            $id_resultado = SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_',
                array($cuit, $nombre_persona, $id_padron, 'worldsys',
                    $StatusCode,
                    $Status,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    'N'),
                'selectOne');
            $error = array();
            self::$id_resultados[] = $id_resultado->id_resultado;
            return $error;

        }
        //---------------------------------------------  HASTA ACA  ----------------------------------------------------------------
        $rr = array();
        $esultado_final = array();
        //echo(var_dump($array->resultados)); die();
        if ($Status == 'OK' && isset($array->resultados) && count($array->resultados) > 0) {
            //echo(var_dump($flag)); die(); // $flag == '1' && 
            if ($id_tributaria == 'null' && $cuit_n == 'null') {
                foreach ($array->resultados as $data) {
                    //$res_ws = array();
                    $res_ws = new stdClass();
                    // SAN_UIF_AR
                    //if((!isset($data->documento) || $data->documento == $cuit2) && $data->residencia == 'AR') {    
                    if (($data->residencia == 'AR' && is_null($data->identificacionTributaria) && $data->tipoFuente == 'SAN' && Misc::esElMismoNombre($nombre_persona, $data->nombre)) || ($data->residencia == 'AR' && $data->identificacionTributaria == $cuit) || ($data->residencia == 'AR' && $data->documento == $cuit2 && $data->tipoFuente == 'TER') || ($data->residencia != 'AR' && Misc::esElMismoNombre($nombre_persona, $data->nombre))) {
                        $res_ws->index = isset($data->index) ? $data->index : '';
                        $res_ws->id = isset($data->id) ? $data->id : '';
                        $res_ws->score = isset($data->score) ? $data->score : '';
                        $res_ws->fuente = isset($data->fuente) ? $data->fuente : '';
                        $res_ws->tipoFuente = isset($data->tipoFuente) ? $data->tipoFuente : '';
                        $res_ws->descripcionFuente = isset($data->descripcionFuente) ? $data->descripcionFuente : '';
                        $res_ws->sdnId = isset($data->sdnId) ? $data->sdnId : '';
                        $res_ws->fechaNovedad = isset($data->fechaNovedad) ? $data->fechaNovedad : '';
                        $res_ws->nombre = isset($data->nombre) ? $data->nombre : '';
                        $res_ws->documento = isset($data->documento) ? $data->documento : '';
                        $res_ws->identificacionTributaria = isset($data->identificacionTributaria) ? $data->identificacionTributaria : '';
                        $res_ws->institucion = isset($data->institucion) ? $data->institucion : '';
                        $res_ws->cargo = isset($data->cargo) ? $data->cargo : '';
                        $res_ws->relacion = isset($data->relacion) ? $data->relacion : '';
                        $res_ws->domicilio = isset($data->domicilio) ? $data->domicilio : '';
                        $res_ws->residencia = isset($data->residencia) ? $data->residencia : '';
                        $res_ws->descripcionPais = isset($data->descripcionPais) ? $data->descripcionPais : '';
                        $res_ws->url = isset($data->url) ? $data->url : '';
                        $res_ws->evaluacion = isset($data->evaluacion) ? $data->evaluacion : '';
                        $res_ws->existeDocumentacion = isset($data->existeDocumentacion) ? $data->existeDocumentacion : '';

                        $comparador = ($data->relacion != '' && $data->tipoFuente == 'PEP') ? 'RR' : $data->tipoFuente;

                        switch ($comparador) {
                            case 'TER':
                                $res_ws->fidecheck = 'P';  //-> ROJO - P
                                $res_ws->orden = 2;
                                $res_ws->tipoFuente = $data->descripcionFuente;
                                break;

                            case 'PEP':
                                $res_ws->fidecheck = 'E'; //-> NARANJA - E
                                $res_ws->orden = 3;
                                break;

                            case 'SAN':
                                $res_ws->fidecheck = 'P'; //-> ROJO - P
                                $res_ws->orden = 2;
                                /*$res_ws['orden'] = 3;*/
                                $res_ws->tipoFuente = $data->descripcionFuente;
                                break;

                            case 'SO':
                                $res_ws->fidecheck = 'S'; //-> CELESTE - S --## PUEDEN VARIAR
                                $res_ws->orden = 3;
                                $res_ws->tipoFuente = 'sujeto obligado';
                                break;

                            case 'RR':
                                $res_ws->fidecheck = 'R'; //-> AMARILLO - R --## PUEDEN VARIAR
                                $res_ws->orden = 4;
                                break;

                            default:
                                $res_ws->fidecheck = 'N'; //-> VERDE - N
                                $res_ws->orden = 2;
                                break;
                        }
                        $esultado_final[] = $res_ws;
                    }

                }
                //echo(var_dump($esultado_final)); die();
                return $esultado_final;
            }
            foreach ($array->resultados as $data) {
                $error = 'OK';
                $Id = (isset($data->sdnId)) ? $data->sdnId : '';
                $Fuente = (isset($data->fuente)) ? $data->fuente : '';
                $NombreModificado = (isset($data->nombre)) ? $data->nombre : '';
                $DocumentoBuscado = $cuit;//(isset($data->documento)) ? $data->documento : ''; 
                $NombreBuscado = '';
                $Documento = (isset($data->documento)) ? $data->documento : '';
                $TipoFuente = (isset($data->tipoFuente)) ? $data->tipoFuente : '';
                $Residencia = (isset($data->residencia)) ? $data->residencia : '';
                $DescripcionPais = (isset($data->descripcionPais)) ? $data->descripcionPais : '';
                $PaisNoColaborativo = '';
                $Hallazgos = '';
                $ExisteDocumentacion = (isset($data->existeDocumentacion)) ? $data->existeDocumentacion : '';
                $PorcentajeSimilitud = '';
                //--------------------------------------------------------------------------------------------------------------
                $Codigo = isset($data->Codigo) ? $data->Codigo : '';
                $TipoFuente = isset($data->tipoFuente) ? $data->tipoFuente : '';
                $FechaNovedad = isset($data->fechaNovedad) ? $data->fechaNovedad : '';
                $Cargo = isset($data->cargo) ? $data->cargo : '';
                $Institucion = (isset($data->institucion)) ? $data->institucion : '';
                $Domicilio = (isset($data->domicilio)) ? $data->domicilio : '';
                $NumeroDocumento = (isset($data->documento)) ? $data->documento : '';
                $NumeroIdTributaria = (isset($data->identificacionTributaria)) ? $data->identificacionTributaria : '';
                $Url = (isset($data->url)) ? $data->url : '';
                $Relacion = (isset($data->relacion)) ? $data->relacion : '';
                $rr[] = $Relacion;
                $PrincipalLista = $Fuente;
                $PrincipalListaDescripcion = (isset($data->descripcionFuente)) ? $data->descripcionFuente : '';
                $PaisSwift = $Residencia;
                $TipoNovedad = ''; //--> verificar
                $IdOrigRel = ''; //--> verificar
                $PrincipalFuente = ''; //--> verificar
                $Observaciones = ''; //--> verificar
                $Pais = $DescripcionPais;
                $UrlNew = $Url;
                $NormaUif = ''; //--> verificar
                $NormaUifDescripcion = ''; //--> verificar
                $FuenteLista = $Fuente;
                $FuenteActiva = ''; //--> verificar
                $FuenteDescripcion = $PrincipalListaDescripcion;
                $FuenteDescripcionLarga = $PrincipalListaDescripcion;
                $FuenteTipo = $TipoFuente;
                $FuenteImagen = ''; //--> verificar
                $FuenteActualizaxml = ''; //--> verificar

                //--------------------------------------------------------------------------------------------------------------
                $NombreModificado = self::limpiarCaracteresEspeciales(utf8_decode($NombreModificado));
                $NombreBuscado = self::limpiarCaracteresEspeciales(utf8_decode($NombreBuscado));
                $Cargo = self::limpiarCaracteresEspeciales(utf8_decode($Cargo));
                $Institucion = self::limpiarCaracteresEspeciales(utf8_decode($Institucion));
                $Domicilio = self::limpiarCaracteresEspeciales(utf8_decode($Domicilio));
                $Relacion = self::limpiarCaracteresEspeciales(utf8_decode($Relacion));

                //--  DESCOMENTAR ESTE BLOQUE PARA PRODUCCION O COMENTAR PARA DEBUG  --//
                /*$id_resultado = SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_', 
                                                                 array($cuit,$nombre_persona,$id_padron,'worldsys',
                                                                 $StatusCode,
                                                                 $Status              ,
                                                                 $Reason              ,
                                                                 $Id                  ,
                                                                 $Fuente              ,
                                                                 $NombreModificado    ,
                                                                 $DocumentoBuscado    ,
                                                                 $NombreBuscado       ,
                                                                 $Documento           ,
                                                                 $TipoFuente          ,
                                                                 $Residencia          ,
                                                                 $DescripcionPais     ,
                                                                 $PaisNoColaborativo  ,
                                                                 $Hallazgos           ,
                                                                 $ExisteDocumentacion ,
                                                                 $PorcentajeSimilitud,
                                                                 'S'),
                                                                 'selectOne'); 
                self::$id_resultados[] = $id_resultado->id_resultado; */
                /*SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_mas_datos_',   array(
                    $id_resultado, $Id,  
                    $StatusCode          ,
                    $Status              ,
                    $Codigo              ,
                    $TipoFuente          ,
                    $FechaNovedad        ,
                    $Cargo,
                    $Institucion,
                    $Domicilio,
                    $NumeroDocumento     ,
                    $NumeroIdTributaria  ,
                    $Url, 
                    $Relacion,
                    $PrincipalLista,
                    $PrincipalListaDescripcion,
                    $PaisSwift,
                    $TipoNovedad,
                    $IdOrigRel,
                    $PrincipalFuente,
                    $Observaciones,
                    $Pais,
                    $UrlNew,
                    $NormaUif,
                    $NormaUifDescripcion,
                    $FuenteLista,
                    $FuenteActiva,
                    $FuenteDescripcion,
                    $FuenteDescripcionLarga,
                    $FuenteTipo,
                    $FuenteImagen,
                    $FuenteActualizaxml
                    ),'selectOne');*/
                //-------------------  HASTA ACA  ---------------------------------------------------------------//

                //-->  ESTA LINEA SE USABA ANTERIORMENTE PERO YA NO ES NECESARIA  
                //$estado_mas = self::obtenerMasDatosPEP($id_resultado->id_resultado,$Id,$token);
                //echo("------------------------------------------------------------------------------------- <br>");
                /* echo('Id: '.$Id.' -<br> Fuente: '.$Fuente.' -<br> NombreModificado: '.$NombreModificado.' -<br> DocumentoBuscado:'.$DocumentoBuscado.' -<br> NombreBuscado: '.$NombreBuscado.' -<br> Documento: '.$Documento.
             ' -<br> TipoFuente: '.$TipoFuente.' -<br> Residencia: '.$Residencia.' -<br> DescripcionPais: '.$DescripcionPais.' -<br> ExisteDocumentacion: '.$ExisteDocumentacion.' -<br> Codigo: '.$Codigo.' -<br> TipoFuente: '.$TipoFuente.
             ' -<br> FechaNovedad: '.$FechaNovedad.' -<br> Cargo: '.$Cargo.' -<br> Institucion: '.$Institucion.' -<br> Domicilio: '.$Domicilio.' -<br> NumeroIdTributaria: '.$NumeroIdTributaria.' -<br> Url: '.$Url.' <br> ');*/
            }
            for ($i = 0; $i < count($array->resultados); $i++) {
                $comparador = ($array->resultados[$i]->relacion != '' && $array->resultados[$i]->tipoFuente == 'PEP') ? 'RR' : $array->resultados[$i]->tipoFuente;
                $array->resultados[$i]->relacion = $rr[$i];
                //--  SE FORMATEA FECHA  --//
                if ($array->resultados[$i]->fechaNovedad !== null) {
                    $feche_temporal = $array->resultados[$i]->fechaNovedad;
                    $feche_temporal = explode('T', $feche_temporal);
                    $feche_temporal = explode('-', $feche_temporal[0]);
                    $array->resultados[$i]->fechaNovedad = $feche_temporal[2] . '-' . $feche_temporal[1] . '-' . $feche_temporal[0];
                } else {
                    $array->resultados[$i]->fechaNovedad = 'S/F';
                }

                switch ($comparador) {
                    case 'TER':
                        $array->resultados[$i]->fidecheck = 'P';  //-> ROJO - P
                        $array->resultados[$i]->orden = 2;
                        $array->resultados[$i]->tipoFuente = $array->resultados[$i]->descripcionFuente;
                        break;

                    case 'PEP':
                        $array->resultados[$i]->fidecheck = 'E'; //-> NARANJA - E
                        $array->resultados[$i]->orden = 3;
                        break;

                    case 'SAN':
                        $array->resultados[$i]->fidecheck = 'P'; //-> ROJO - P
                        $array->resultados[$i]->orden = 2;
                        /*$array->resultados[$i]->orden = 3;*/
                        $array->resultados[$i]->tipoFuente = $array->resultados[$i]->descripcionFuente;
                        break;

                    case 'SO':
                        $array->resultados[$i]->fidecheck = 'S'; //-> CELESTE - S --## PUEDEN VARIAR
                        $array->resultados[$i]->orden = 3;
                        $array->resultados[$i]->tipoFuente = 'sujeto obligado';
                        break;

                    case 'RR':
                        $array->resultados[$i]->fidecheck = 'R'; //-> AMARILLO - R --## PUEDEN VARIAR
                        $array->resultados[$i]->orden = 4;
                        break;

                    default:
                        $array->resultados[$i]->fidecheck = 'N'; //-> VERDE - N
                        $array->resultados[$i]->orden = 2;
                        break;
                }
            }
            //echo(var_dump($array->resultados)); die();
            //echo(var_dump(self::$id_resultados)); die();
            return $array->resultados;
        }
        return $error;
        //--  DEBUG  --//

    }


    //-----------------------------------------------------------------------------------------------------------------------------------//
    /*
    FUNCION ADAPTADA, RESTA VERIFICAR
    */
    public static function obtenerPEPSCliente() {
        $cliente = Request::input('cliente');
        $familia = Request::input('familia') ?? null;
        $contraparte = Request::input('contraparte') ?? null;

        if ($contraparte !== null) {
            $contrapartes = DB::select("select contraparte from LN_contrapartes where contraparte = " . $contraparte);
        } else {
            $contrapartes = SQLConnection::backendStoreProcedure('ln_contrapartes_fidecheck', array($cliente, $familia), 'select');
        }
        $c = 0;
        foreach ($contrapartes as $cont) {
            $c += 1;
            $id = $cont->contraparte;
            $registros = SQLConnection::backendStoreProcedure('LN_completa_fidecheck', array($id), 'select');
            $i = 0;
            foreach ($registros as $cuits) {
                $i += 1;
                $buscar_afip = self::CURLCall(env('URL_FRONTEND') . '/api/local/v1/afip/obtener-padron/' . $cuits->tax_id, 'GET');
                $cuit = $cuits->tax_id;
                $nombre_persona = $cuits->nombre;
                $id_padron = 0;
                $seccion = $cuits->seccion;
                //$datos_finales = self::procesar_pep($cuit, $nombre_persona, $id_padron);
                /* 04/11/2022, lo cambiamos por la consultApiWsNueva */
                $pais = $cuits->country_code;
                // $datos_finales = self::consultApiWsNueva($cuit, $nombre_persona, $pais);
                $datos_finales = ($pais=='AR') ? self::consultApiWsNueva($cuit, $nombre_persona, $pais) : self::consultApiWsNueva(null, $nombre_persona, null);
                /**/
                if (isset($datos_finales['error'])) {
                    $resp = $datos_finales['error'];
                    $error = 'ERROR';
                    break;
                }

                $detalle = '';
                $cargo = (isset($datos_finales[0]->cargo)) ? $datos_finales[0]->cargo : '';
                $institucion = (isset($datos_finales[0]->institucion)) ? $datos_finales[0]->institucion : '';
                $relacion = (isset($datos_finales[0]->relacion)) ? $datos_finales[0]->relacion : '';
                $lista = (isset($datos_finales[0]->descripcionFuente)) ? $datos_finales[0]->descripcionFuente : '';
                $fidecheck = (isset($datos_finales[0]->fidecheck)) ? $datos_finales[0]->fidecheck : 'N';
                $pais = (isset($datos_finales[0]->descripcionPais)) ? $datos_finales[0]->descripcionPais : '';

                if ($lista != '') {
                    $detalle .= 'Integrante de listas ' . $lista;
                }
                if ($detalle == '' && $pais != '') {
                    $detalle = 'Integrante de listas';
                }
                if ($pais != '') {
                    $detalle .= ' ' . $pais;
                }
                if ($detalle != '') {
                    $detalle .= ':';
                }
                if ($cargo != '') {
                    $detalle .= ' ' . $cargo;
                }
                if ($institucion != '') {
                    $detalle .= ' de ' . $institucion;
                }
                if ($relacion != '') {
                    $detalle .= ' - Relacionado: ' . $relacion;
                }
                //$idr         = $datos_finales[0];
                $idr = 0;
                /*if ($contraparte !== null)
                {
                    var_dump($cuit);
                    var_dump($seccion);
                    var_dump($fidecheck);
                    var_dump($detalle);
                }*/
                $actualizo = SQLConnection::backendStoreProcedure('LN_actualiza_fidecheck', array($id, $cuit, $seccion, $fidecheck, $detalle, $idr), 'select');
                $insert_queue = SQLConnection::backendStoreProcedure('LN_contrapartes_queue_', array('insert', NULL, $id), 'selectOne');

                //-----------------------------------------------------------------------------------------
                usleep(15000000);
            }

        }

        echo ("\r\nCantidad de contrapartes = " . $c);

    }

    //-----------------------------------------------------------------------------------------------------------------------------------//
    /*
    FUNCION AUXILIAR PARA HACER CURL A 'N' URL
    */
    public static function CURLCall($url, $type) {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 240,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => $type,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_SSL_VERIFYPEER => false,
            //CURLOPT_POSTFIELDS => $params,
            CURLOPT_HTTPHEADER => array(
                "cache-control: no-cache",
                "content-type: application/x-www-form-urlencoded"
            ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);

        if (env('BACKEND') !== 'BACKEND') {
            $mensajeCurl = 'CURLCall Error:' . $err . ' - Response:' . $response;
        }

        if ($err) {
            return json_encode(array('error' => true));
        } else {
            return $response;
        }
    }
    //--  LLAMADA API WS NUEVA FIDELITAS  --//
    public static function consultApiWsNueva($tax_id, $full_name, $country_code) {
        //echo($tax_id.'-'.$full_name.'-'.$country_code); die();
        $token = env('PEP_NV_TOKEN_FIDECHECK_AUTOMATICO');
        $data = array("apikey" => $token, "tax_id" => $tax_id, "full_name" => $full_name, "country_code" => $country_code);
        $url = env('PEP_NV_URL_CONSUMO_INTERNO');


        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $data,
        ));

        $response = curl_exec($curl);
        //var_dump('1712'); 
        //var_dump($response);  die();
        /*

        Estos son ejemplos de lo que devuelve WS:
        Cuando es argentino en NumeroIdTributaria: devuelve el cuit, pero en otros paises lo devuelve vacio, entonces tomamos el campo NumeroDocumento o Documento
        
        string(769) "{"Params":{"full_name":"GUANUCO DIEGO GUSTAVO","tax_id":"20221129874","country_code":"AR","count":1,"status_code":200,"status":"Ok","transaction_id":"29281182"},"response":[{"tipoFuente":"","relacion":"","FechaNovedad":"","cuit":"20221129874","nombre_persona":"GUANUCO DIEGO GUSTAVO","StatusCode":"200","Status":"OK","Reason":"","Id":"","Fuente":"","NombreModificado":"","DocumentoBuscado":"20221129874","NombreBuscado":"GUANUCO DIEGO GUSTAVO","Documento":"","Residencia":"","DescripcionPais":"","PorcentajeSimilitud":"","fidecheck":"N","Codigo":"","FechaNovedaddmy":"","Cargo":"","Institucion":"","Domicilio":"","NumeroDocumento":"","NumeroIdTributaria":"20221129874","Url":"","Relacion":"","orden":"","TipoFuente":"","DescripcionFuente":"","fecha":"","visible":"1"}]}"

        string(1012) "{"Params":{"full_name":"SOTO GONZALEZ GERARDO","tax_id":"SOGG800715674","country_code":"MX","count":1,"status_code":200,"status":"Ok","transaction_id":"29281224"},"response":[{"cuit":"","nombre_persona":"SOTO GONZALEZ GERARDO ADRIAN","StatusCode":"200","Status":"OK","Reason":"Sancionado","Id":"107599501","Fuente":"SAN_SAT_MEXICO","NombreModificado":"SOTO GONZALEZ GERARDO ADRIAN","DocumentoBuscado":"SOGG800715674","NombreBuscado":"SOTO GONZALEZ GERARDO","Documento":"SOGG9005064C4","Residencia":"MX","DescripcionPais":"M\u00e9xico","PorcentajeSimilitud":"88","fidecheck":"P","Codigo":"SAN_SAT_MEXICO-20230512-00000000000107599501","FechaNovedad":"2024-07-30","FechaNovedaddmy":"30\/07\/2024","Cargo":"","Institucion":"","Domicilio":"CHIHUAHUA","NumeroDocumento":"SOGG9005064C4","NumeroIdTributaria":"","Url":"http:\/\/info.pld.global\/Base\/Index?referencia=U0FOX1NBVF9NRVhJQ098MTA3NTk5NTAx","Relacion":"","orden":"2","TipoFuente":"SAN","DescripcionFuente":"Listas SAT","fecha":"30\/07\/2024","visible":"1"}]}"

        */


        curl_close($curl);
        //return json_decode($response)->response;
        $datos = json_decode($response)->response;
        $datos_finales = array();
        /*var_dump('1721'); 
        var_dump($datos); 
        var_dump('1723');*/
        foreach ($datos as $key) {
            $persona = new \stdClass;
            $persona->id = $key->Id;
            $persona->score = $key->PorcentajeSimilitud;
            $persona->fuente = $key->Fuente;
            $persona->tipoFuente = $key->TipoFuente;
            $persona->descripcionFuente = $key->DescripcionFuente;
            $persona->sdnId = $key->Id;
            $persona->fechaNovedad = $key->FechaNovedad;
            $persona->fechaNovedaddmy = $key->FechaNovedaddmy;
            $persona->nombre = $key->nombre_persona;
            $persona->dcumento = $key->Documento;
            $persona->identificacionTributaria = $key->NumeroIdTributaria;
            if (strlen($persona->identificacionTributaria < 2)) {
                $persona->identificacionTributaria = $key->NumeroDocumento;
            }
            if (strlen($persona->identificacionTributaria < 2)) {
                $persona->identificacionTributaria = $key->Documento;
            }

            if (strtoupper($key->Institucion) == 'NAN') {
                $persona->institucion = '';
            } else {
                $persona->institucion = $key->Institucion;
            }
            if (strtoupper($key->Cargo) == 'NAN') {
                $persona->cargo = '';
            } else {
                $persona->cargo = $key->Cargo;
            }
            $persona->relacion = $key->Relacion;
            $persona->domicilio = $key->Domicilio;
            $persona->residencia = '';
            if (isset($key->Residencia)) {
                $persona->residencia = $key->Residencia;
            }
            if (isset($key->Recidencia)) {
                $persona->residencia = $key->Recidencia;
            }

            $persona->descripcionPais = $key->DescripcionPais;
            $persona->url = $key->Url;
            $persona->fidecheck = $key->fidecheck;
            $persona->orden = ($key->fidecheck == 'P') ? 2 : $key->orden;
            $persona->fechaUltimaConsulta = $key->fecha;
            $hoy = new DateTime();
            if ($key->fecha !== '') {
                $fecha_consulta = date_create_from_format('d/m/Y', $key->fecha);
                $fecha_consulta->modify('+' . env('PEP_NV_TOPE_DIAS') . ' day');
                $persona->debeConultar = $hoy > $fecha_consulta;
            } else {
                $persona->debeConultar = true;
            }
            /* 30/08/2024: Antes si WS no tenia datos, los completaba con los nuestros... eso lo sacamos 
            if ($persona->nombre=='') { $persona->nombre =  $full_name;}
            if ($persona->dcumento=='') { $persona->dcumento =  $tax_id;}
            if ($persona->identificacionTributaria=='') { $persona->identificacionTributaria =  $tax_id;}
            if ($persona->residencia=='') { $persona->residencia =  'AR';}*/
            if ($persona->fechaNovedaddmy == '') {
                $persona->fechaNovedaddmy = date_format($hoy, 'd/m/Y');
            }

            $datos_finales[] = $persona;
        }
        //var_dump($datos_finales); die(); 

        return $datos_finales;
    }
    //-----------------------------------------------------------------------------------------------------------------------------------//
    /*
    FUNCIONES ADAPTADAS, SE MODIFICO SECCION PARA QUE MUESTRE ACORDE LOS RESULTADOS  --//
    */
    public static function completarFidecheck() {
        $cl = Request::input('cliente');
        //$cl = 2046807993;
        $id = Request::input('contraparte');
        //$id = 32103;
        $error = '';
        $inicio = (null !== Request::input('inicio')) ? Request::input('inicio') : 'inicio';
        
        if ($inicio == 'inicio') {
            $registros = SQLConnection::backendStoreProcedure('LN_completa_fidecheck', array($id), 'select');
            $i = 0;
            if (env('PEP_FIDECHECK_AUTOMATICO_VA_A_WORLDSYS') !== 'NO') {
                foreach ($registros as $cuits) {
                    $i += 1;
                    $buscar_afip = self::CURLCall(env('URL_FRONTEND') . '/api/local/v1/afip/obtener-padron/' . $cuits->tax_id, 'GET');
                    $cuit = $cuits->tax_id;
                    $nombre_persona = $cuits->nombre;
                    $id_padron = 0;
                    $seccion = $cuits->seccion;
                    //-- se obtiene el pais codigo ej: AR
                    $pais_code = (isset($cuits->country_code)) ? $cuits->country_code : 'AR';
                    //-- aca hace la consulta a ws.
                    // $datos_finales = self::consultApiWsNueva($cuit, $nombre_persona, $pais_code);
                    $datos_finales = ($pais_code=='AR') ? self::consultApiWsNueva($cuit, $nombre_persona, $pais_code) : self::consultApiWsNueva(null, $nombre_persona, null);
                    $detalle = '';
                    $cargo = (isset($datos_finales[0]->cargo)) ? $datos_finales[0]->cargo : '';
                    $institucion = (isset($datos_finales[0]->institucion)) ? $datos_finales[0]->institucion : '';
                    $relacion = (isset($datos_finales[0]->relacion)) ? $datos_finales[0]->relacion : '';
                    $lista = (empty($lista) && isset($datos_finales[0]->fuente)) ? $datos_finales[0]->fuente : '';
                    $descripcion_corta = (isset($datos_finales[0]->descripcionFuente)) ? $datos_finales[0]->descripcionFuente : '';
                    $fidecheck = (isset($datos_finales[0]->fidecheck)) ? $datos_finales[0]->fidecheck : 'N';
                    $pais = (isset($datos_finales[0]->descripcionPais)) ? $datos_finales[0]->descripcionPais : '';

                    if ($lista != '') {
                        $detalle .= 'Integrante de listas ' . $lista;
                    }
                    if ($detalle == '' && $pais != '') {
                        $detalle = 'Integrante de listas';
                    }
                    if ($pais != '') {
                        $detalle .= ' ' . $pais;
                    }
                    if ($detalle != '' && $cargo != '' && $institucion != '' && $relacion != '') {
                        $detalle .= ':';
                    }
                    if ($cargo != '') {
                        $detalle .= ' ' . $cargo;
                    }
                    if ($institucion != '') {
                        $detalle .= ' de ' . $institucion;
                    }
                    if ($relacion != '') {
                        $detalle .= ' - Relacionado: ' . $relacion;
                    }
                    if ( $descripcion_corta != '' ){
                        $detalle .= ' '. $descripcion_corta;
                    }
                    $idr = 0;
                    $actualizo = SQLConnection::backendStoreProcedure('LN_actualiza_fidecheck', array($id, $cuit, $seccion, $fidecheck, $detalle, $idr), 'select');
                    usleep(1000000);
                    //-----------------------------  NUEVO  ----------------------------------------------------------------//
                }
            }
        }
        $insert_queue = SQLConnection::backendStoreProcedure('LN_contrapartes_queue_', array('insert', NULL, $id), 'selectOne');
        $cliente = SQLConnection::backendStoreProcedure('LED_Clientes', array('select', $cl, NULL, NULL, NULL), 'selectOne');
        $sesion_id = isset(Session::get('usuario')->user_id) ? Session::get('usuario')->user_id : 15342812;
        $contrap = SQLConnection::backendStoreProcedure('LN_contrapartes_', array('select', $id, null, null, null, null, null, null, null, null, null, null, null, null, $sesion_id), 'selectOne');
        $socios = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'S'), 'select');
        $relac = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'R'), 'select');
        $direct = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'D'), 'select');
        $propio = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'P'), 'selectOne');
        return view('/led/led_fidecheckdemo2')->with(compact(['cliente', 'contrap', 'socios', 'relac', 'direct', 'propio', 'error', 'inicio']));

    }

    public static function completarFidecheck_Original() {
        $cl = Request::input('cliente');
        //$cl = 2046807993; 
        $id = Request::input('contraparte');
        //$id = 32103; 
        $error = '';
        $inicio = (null !== Request::input('inicio')) ? Request::input('inicio') : 'inicio';
        if ($inicio == 'inicio') {
            $registros = SQLConnection::backendStoreProcedure('LN_completa_fidecheck', array($id), 'select');
            $i = 0;
            if (env('PEP_FIDECHECK_AUTOMATICO_VA_A_WORLDSYS') !== 'NO') {
                foreach ($registros as $cuits) {
                    $i += 1;
                    $buscar_afip = self::CURLCall(env('URL_FRONTEND') . '/api/local/v1/afip/obtener-padron/' . $cuits->tax_id, 'GET');
                    $cuit = $cuits->tax_id;
                    $nombre_persona = $cuits->nombre;
                    $id_padron = 0;
                    $seccion = $cuits->seccion;
                    $datos_finales = self::procesar_pep($cuit, $nombre_persona, $id_padron);
                    if (isset($datos_finales['error'])) {
                        $resp = $datos_finales['error'];
                        $error = 'ERROR';
                        break;
                    }
                    //-----------------------------  NUEVO  ----------------------------------------------------------------//
                    /*if(count($datos_finales) == 0){
                        $fidecheck  = 'N';
                    }*/
                    $fidecheck = 'N';

                    if ($fidecheck !== null) {
                        $detalle = '';
                        $cargo = (isset($datos_finales[0]->cargo)) ? $datos_finales[0]->cargo : '';
                        $institucion = (isset($datos_finales[0]->institucion)) ? $datos_finales[0]->institucion : '';
                        $relacion = (isset($datos_finales[0]->relacion)) ? $datos_finales[0]->relacion : '';
                        $lista = (isset($datos_finales[0]->tipoFuente)) ? $datos_finales[0]->tipoFuente : '';
                        //--  SECCION AGREGADA  --//
                        $marcador = (strlen($lista) > 3) ? explode('_', $datos_finales[0]->fuente)[0] : '';
                        $pais = (isset($datos_finales[0]->descripcionPais)) ? $datos_finales[0]->descripcionPais : '';
                        $comparador = ($relacion != '' && $lista == 'PEP') ? 'RR' : $lista;
                        if (strlen($comparador) > 3) {
                            if ($marcador == 'SAN') {
                                $comparador = $marcador;
                            } else {
                                $comparador = 'SO';
                            }
                        }
                        //--  FIN SECCION AGREGADA  --//
                        switch ($comparador) {
                            case 'TER':
                                $fidecheck = 'P';  //-> ROJO - P
                                break;

                            case 'PEP':
                                $fidecheck = 'E'; //-> NARANJA - E
                                break;

                            case 'SAN':
                                $fidecheck = 'P'; //-> ROJO - P
                                break;

                            case 'SO':
                                $fidecheck = 'S'; //-> CELESTE - S --## PUEDEN VARIAR
                                break;

                            case 'RR':
                                $fidecheck = 'R'; //-> AMARILLO - R --## PUEDEN VARIAR
                                break;

                            default:
                                $fidecheck = 'N'; //-> VERDE - N
                                break;
                        }

                        if ($lista != '') {
                            $detalle .= 'Integrante de listas ' . $lista;
                        }
                        if ($detalle == '' && $pais != '') {
                            $detalle = 'Integrante de listas';
                        }
                        if ($pais != '') {
                            $detalle .= ' ' . $pais;
                        }
                        if ($detalle != '') {
                            $detalle .= ':';
                        }
                        if ($cargo != '') {
                            $detalle .= ' ' . $cargo;
                        }
                        if ($institucion != '') {
                            $detalle .= ' de ' . $institucion;
                        }
                        if ($relacion != '') {
                            $detalle .= ' - Relacionado: ' . $relacion;
                        }

                        $idr = 0;
                        $actualizo = SQLConnection::backendStoreProcedure('LN_actualiza_fidecheck', array($id, $cuit, $seccion, $fidecheck, $detalle, $idr), 'select');
                    }
                    usleep(1000000);
                }
            }
        }

        $insert_queue = SQLConnection::backendStoreProcedure('LN_contrapartes_queue_', array('insert', NULL, $id), 'selectOne');
        $cliente = SQLConnection::backendStoreProcedure('LED_Clientes', array('select', $cl, NULL, NULL, NULL), 'selectOne');
        $sesion_id = isset(Session::get('usuario')->user_id) ? Session::get('usuario')->user_id : 15342812;
        $contrap = SQLConnection::backendStoreProcedure('LN_contrapartes_', array('select', $id, null, null, null, null, null, null, null, null, null, null, null, null, $sesion_id), 'selectOne');
        $socios = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'S'), 'select');
        $relac = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'R'), 'select');
        $direct = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'D'), 'select');
        $propio = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'P'), 'selectOne');
        return view('/led/led_fidecheckdemo2')->with(compact(['cliente', 'contrap', 'socios', 'relac', 'direct', 'propio', 'error', 'inicio']));

    }

    //-----------------------------------------------------------------------------------------------------------------------------------//
    // FUNCION ENCARGADA DE HACER EL FIDECHECK AUTOMATICO E DEVOLVERLO

    public static function completarFidecheckNueva() {
        $cl = Request::input('cliente');
        $id = Request::input('contraparte');
        //
        $error = '';
        $inicio = (null !== Request::input('inicio')) ? Request::input('inicio') : 'inicio';
        //
        if ($inicio == 'inicio') {
            $registros = SQLConnection::backendStoreProcedure('LN_completa_fidecheck', array($id), 'select');
            $i = 0;
            //
            if (env('PEP_FIDECHECK_AUTOMATICO_VA_A_WORLDSYS') !== 'NO') {
                foreach ($registros as $cuits) {
                    $i += 1;
                    $buscar_afip = self::CURLCall(env('URL_FRONTEND') . '/api/local/v1/afip/obtener-padron/' . $cuits->tax_id, 'GET');
                    $cuit = $cuits->tax_id;
                    $nombre_persona = $cuits->nombre;
                    $id_padron = 0;
                    $seccion = $cuits->seccion;

                    //-- se obtiene el pais codigo ej: AR
                    $pais_code = (isset($cuits->country_code)) ? $cuits->country_code : 'AR';
                    //-- aca hace la consulta a ws.
                    $datos_finales = ($pais_code=='AR') ? self::consultApiWsNueva($cuit, $nombre_persona, $pais_code) : self::consultApiWsNueva(null, $nombre_persona, null) ;
                    $detalle = '';
                    $cargo = (isset($datos_finales[0]->cargo)) ? $datos_finales[0]->cargo : '';
                    $institucion = (isset($datos_finales[0]->institucion)) ? $datos_finales[0]->institucion : '';
                    $relacion = (isset($datos_finales[0]->relacion)) ? $datos_finales[0]->relacion : '';
                    $lista = (empty($lista) && isset($datos_finales[0]->fuente)) ? $datos_finales[0]->fuente : '';
                    $descripcion_corta = (isset($datos_finales[0]->descripcionFuente)) ? $datos_finales[0]->descripcionFuente : '';
                    $fidecheck = (isset($datos_finales[0]->fidecheck)) ? $datos_finales[0]->fidecheck : 'N';
                    $pais = (isset($datos_finales[0]->descripcionPais)) ? $datos_finales[0]->descripcionPais : '';
                    //
                    if ($lista != '') {
                        $detalle .= 'Integrante de listas ' . $lista;
                    }
                    if ($detalle == '' && $pais != '') {
                        $detalle = 'Integrante de listas';
                    }
                    if ($pais != '') {
                        $detalle .= ' ' . $pais;
                    }
                    if ($detalle != '') {
                        $detalle .= ':';
                    }
                    if ($cargo != '') {
                        $detalle .= ' ' . $cargo;
                    }
                    if ($institucion != '') {
                        $detalle .= ' de ' . $institucion;
                    }
                    if ($relacion != '') {
                        $detalle .= ' - Relacionado: ' . $relacion;
                    }
                    if ( $descripcion_corta != '' ){
                        $detalle .= ' '. $descripcion_corta;
                    }
                    $idr = 0;
                    $actualizo = SQLConnection::backendStoreProcedure('LN_actualiza_fidecheck', array($id, $cuit, $seccion, $fidecheck, $detalle, $idr), 'select');
                    usleep(1000000);
                }
            }
        }
        //
        $insert_queue = SQLConnection::backendStoreProcedure('LN_contrapartes_queue_', array('insert', NULL, $id), 'selectOne');
        $cliente = SQLConnection::backendStoreProcedure('LED_Clientes', array('select', $cl, NULL, NULL, NULL), 'selectOne');
        $nombre_cliente = $cliente->nombre_cliente;
        $cli_codigo = $cliente->cli_codigo;
        $cli_cuit = $cliente->numero;
        $sesion_id = isset(Session::get('usuario')->user_id) ? Session::get('usuario')->user_id : 15342812;
        $contrap = SQLConnection::backendStoreProcedure('LN_contrapartes_', array('select', $id, null, null, null, null, null, null, null, null, null, null, null, null, $sesion_id), 'selectOne');
        $socios = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'S'), 'select');
        $relac = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'R'), 'select');
        $direct = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'D'), 'select');
        $propio = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'P'), 'selectOne');
        //
        $temp = SQLConnection::backendStoreProcedure('LN_DASHBOARD_CLIENTE', array('FIDECHECK', NULL, null, null, $id), 'selectOne');
        $servicio = $contrap->servicio_contratado;
        //
        $desde_contrapartes_genericos = 0;
        //
        if (Request::input('desde_contrapartes_genericos') == '1') {
            $nombre_servicio = Request::input('nombre_servicio');
            $tiene_api = Request::input('tieneApi');
            //
            $desde_contrapartes_genericos = Request::input('desde_contrapartes_genericos');
            $datos_redireccion = (object) ['nombre_servicio' => $nombre_servicio, 'tieneApi' => $tiene_api];
        } else {
            // DATOS PARA REDIRECCION
            $tipo_paquete = Request::input('tipo_paquete_cliente');
            $nombre_producto = Request::input('prod_nombre_cliente');
            $limite_consumo = Request::input('limite_consumo_cliente');
            $fecha_desde = Request::input('fecha_desde');
            $fecha_hasta = Request::input('fecha_hasta');
            $bloquea = Request::input('estado_bloquea_cliente');
            $estado_producto = Request::input('estado_producto_cliente');
            $modalidad_de_pago = Request::input('modalidad_de_pago');
            $impe_doc = Request::input('impe_doc');
            $impe_acceso = Request::input('impe_acceso');
            $desde_panel_clientes = Request::input('desde_panel_clientes') ?? 0;
            $servicio = $contrap->servicio_contratado;
            // DATOS PARA EL FORMULARIO DE REDIRECCIONAMIENTO
            $datos_redireccion = (object) ['tipo_paquete' => $tipo_paquete, 'nombre_producto' => $nombre_producto, 'limite' => $limite_consumo, 'desde' => $fecha_desde, 'hasta' => $fecha_hasta, 'bloquea' => $bloquea, 'estado_producto' => $estado_producto, 'modalidad_de_pago' => $modalidad_de_pago, 'impe_acceso' => $impe_acceso, 'impe_doc' => $impe_doc, 'desde_panel_clientes' => $desde_panel_clientes];
        }
        return view('/blue/servicios_cliente/fidecheck/fidecheck_automatico')->with(compact(['cliente', 'contrap', 'socios', 'relac', 'direct', 'propio', 'error', 'inicio', 'datos_redireccion', 'servicio', 'desde_contrapartes_genericos', 'nombre_cliente', 'cli_codigo', 'cli_cuit']));
    }

    public static function completarFidecheckNuevaOLD() {
        $cl = Request::input('cliente');
        $id = Request::input('contraparte');
        //
        $error = '';
        $inicio = (null !== Request::input('inicio')) ? Request::input('inicio') : 'inicio';
        //
        if ($inicio == 'inicio') {
            $registros = SQLConnection::backendStoreProcedure('LN_completa_fidecheck', array($id), 'select');
            $i = 0;
            //
            if (env('PEP_FIDECHECK_AUTOMATICO_VA_A_WORLDSYS') !== 'NO') {
                foreach ($registros as $cuits) {
                    $i += 1;
                    $buscar_afip = self::CURLCall(env('URL_FRONTEND') . '/api/local/v1/afip/obtener-padron/' . $cuits->tax_id, 'GET');
                    $cuit = $cuits->tax_id;
                    $nombre_persona = $cuits->nombre;
                    $id_padron = 0;
                    $seccion = $cuits->seccion;
                    $datos_finales = self::procesar_pep($cuit, $nombre_persona, $id_padron);
                    if (isset($datos_finales['error'])) {
                        $resp = $datos_finales['error'];
                        $error = 'ERROR';
                        break;
                    }
                    //-----------------------------  NUEVO  ----------------------------------------------------------------//
                    /*if(count($datos_finales) == 0){
                        $fidecheck  = 'N';
                    }*/
                    $fidecheck = 'N';
                    //
                    if ($fidecheck !== null) {
                        $detalle = '';
                        $cargo = (isset($datos_finales[0]->cargo)) ? $datos_finales[0]->cargo : '';
                        $institucion = (isset($datos_finales[0]->institucion)) ? $datos_finales[0]->institucion : '';
                        $relacion = (isset($datos_finales[0]->relacion)) ? $datos_finales[0]->relacion : '';
                        $lista = (isset($datos_finales[0]->descripcionFuente)) ? $datos_finales[0]->descripcionFuente : '';
                        //--  SECCION AGREGADA  --//
                        $marcador = (strlen($lista) > 3) ? explode('_', $datos_finales[0]->fuente)[0] : '';
                        $pais = (isset($datos_finales[0]->descripcionPais)) ? $datos_finales[0]->descripcionPais : '';
                        $comparador = ($relacion != '' && $lista == 'PEP') ? 'RR' : $lista;
                        if (strlen($comparador) > 3) {
                            if ($marcador == 'SAN') {
                                $comparador = $marcador;
                            } else {
                                $comparador = 'SO';
                            }
                        }
                        //--  FIN SECCION AGREGADA  --//
                        switch ($comparador) {
                            case 'TER':
                                $fidecheck = 'P';  //-> ROJO - P
                                break;
                            case 'PEP':
                                $fidecheck = 'E'; //-> NARANJA - E
                                break;
                            case 'SAN':
                                $fidecheck = 'P'; //-> ROJO - P
                                break;
                            case 'SO':
                                $fidecheck = 'S'; //-> CELESTE - S --## PUEDEN VARIAR
                                break;
                            case 'RR':
                                $fidecheck = 'R'; //-> AMARILLO - R --## PUEDEN VARIAR
                                break;
                            default:
                                $fidecheck = 'N'; //-> VERDE - N
                                break;
                        }
                        //
                        if ($lista != '') {
                            $detalle .= 'Integrante de listas ' . $lista;
                        }
                        if ($detalle == '' && $pais != '') {
                            $detalle = 'Integrante de listas';
                        }
                        if ($pais != '') {
                            $detalle .= ' ' . $pais;
                        }
                        if ($detalle != '') {
                            $detalle .= ':';
                        }
                        if ($cargo != '') {
                            $detalle .= ' ' . $cargo;
                        }
                        if ($cargo != '' && $institucion != '') {
                            $detalle .= ' de';
                        }
                        if ($institucion != '') {
                            $detalle .= ' ' . $institucion;
                        }
                        if ($relacion != '') {
                            $detalle .= ' - Relacionado: ' . $relacion;
                        }
                        //
                        $idr = 0;
                        $actualizo = SQLConnection::backendStoreProcedure('LN_actualiza_fidecheck', array($id, $cuit, $seccion, $fidecheck, $detalle, $idr), 'select');

                    }
                    usleep(1000000);
                }
            }
        }
        //
        $insert_queue = SQLConnection::backendStoreProcedure('LN_contrapartes_queue_', array('insert', NULL, $id), 'selectOne');
        $cliente = SQLConnection::backendStoreProcedure('LED_Clientes', array('select', $cl, NULL, NULL, NULL), 'selectOne');
        $nombre_cliente = $cliente->nombre_cliente;
        $cli_codigo = $cliente->cli_codigo;
        $cli_cuit = $cliente->numero;
        $sesion_id = isset(Session::get('usuario')->user_id) ? Session::get('usuario')->user_id : 15342812;
        $contrap = SQLConnection::backendStoreProcedure('LN_contrapartes_', array('select', $id, null, null, null, null, null, null, null, null, null, null, null, null, $sesion_id), 'selectOne');
        $socios = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'S'), 'select');
        $relac = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'R'), 'select');
        $direct = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'D'), 'select');
        $propio = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'P'), 'selectOne');
        //
        $temp = SQLConnection::backendStoreProcedure('LN_DASHBOARD_CLIENTE', array('FIDECHECK', NULL, null, null, $id), 'selectOne');
        $servicio = $contrap->servicio_contratado;
        //
        $desde_contrapartes_genericos = 0;
        //
        if (Request::input('desde_contrapartes_genericos') == '1') {
            $nombre_servicio = Request::input('nombre_servicio');
            $tiene_api = Request::input('tieneApi');
            //
            $desde_contrapartes_genericos = Request::input('desde_contrapartes_genericos');
            $datos_redireccion = (object) ['nombre_servicio' => $nombre_servicio, 'tieneApi' => $tiene_api];
        } else {
            // DATOS PARA REDIRECCION
            $tipo_paquete = Request::input('tipo_paquete_cliente');
            $nombre_producto = Request::input('prod_nombre_cliente');
            $limite_consumo = Request::input('limite_consumo_cliente');
            $fecha_desde = Request::input('fecha_desde');
            $fecha_hasta = Request::input('fecha_hasta');
            $bloquea = Request::input('estado_bloquea_cliente');
            $estado_producto = Request::input('estado_producto_cliente');
            $modalidad_de_pago = Request::input('modalidad_de_pago');
            $impe_doc = Request::input('impe_doc');
            $impe_acceso = Request::input('impe_acceso');
            $desde_panel_clientes = Request::input('desde_panel_clientes') ?? 0;
            $servicio = $contrap->servicio_contratado;
            // DATOS PARA EL FORMULARIO DE REDIRECCIONAMIENTO
            $datos_redireccion = (object) ['tipo_paquete' => $tipo_paquete, 'nombre_producto' => $nombre_producto, 'limite' => $limite_consumo, 'desde' => $fecha_desde, 'hasta' => $fecha_hasta, 'bloquea' => $bloquea, 'estado_producto' => $estado_producto, 'modalidad_de_pago' => $modalidad_de_pago, 'impe_acceso' => $impe_acceso, 'impe_doc' => $impe_doc, 'desde_panel_clientes' => $desde_panel_clientes];
        }
        return view('/blue/servicios_cliente/fidecheck/fidecheck_automatico')->with(compact(['cliente', 'contrap', 'socios', 'relac', 'direct', 'propio', 'error', 'inicio', 'datos_redireccion', 'servicio', 'desde_contrapartes_genericos', 'nombre_cliente', 'cli_codigo', 'cli_cuit']));
    }

    public static function completarFidecheckNuevaORG() {
        $cl = Request::input('cliente');
        $id = Request::input('contraparte');
        //
        $error = '';
        $inicio = (null !== Request::input('inicio')) ? Request::input('inicio') : 'inicio';
        //
        if ($inicio == 'inicio') {
            $registros = SQLConnection::backendStoreProcedure('LN_completa_fidecheck', array($id), 'select');
            $i = 0;
            //
            if (env('PEP_FIDECHECK_AUTOMATICO_VA_A_WORLDSYS') !== 'NO') {
                foreach ($registros as $cuits) {
                    $i += 1;
                    $buscar_afip = self::CURLCall(env('URL_FRONTEND') . '/api/local/v1/afip/obtener-padron/' . $cuits->tax_id, 'GET');
                    $cuit = $cuits->tax_id;
                    $nombre_persona = $cuits->nombre;
                    $id_padron = 0;
                    $seccion = $cuits->seccion;
                    $datos_finales = self::procesar_pep($cuit, $nombre_persona, $id_padron);
                    if (isset($datos_finales['error'])) {
                        $resp = $datos_finales['error'];
                        $error = 'ERROR';
                        break;
                    }
                    //-----------------------------  NUEVO  ----------------------------------------------------------------//
                    /*if(count($datos_finales) == 0){
                        $fidecheck  = 'N';
                    }*/
                    $fidecheck = 'N';
                    //
                    if ($fidecheck !== null) {
                        $detalle = '';
                        $cargo = (isset($datos_finales[0]->cargo)) ? $datos_finales[0]->cargo : '';
                        $institucion = (isset($datos_finales[0]->institucion)) ? $datos_finales[0]->institucion : '';
                        $relacion = (isset($datos_finales[0]->relacion)) ? $datos_finales[0]->relacion : '';
                        $lista = (isset($datos_finales[0]->tipoFuente)) ? $datos_finales[0]->tipoFuente : '';
                        //--  SECCION AGREGADA  --//
                        $marcador = (strlen($lista) > 3) ? explode('_', $datos_finales[0]->fuente)[0] : '';
                        $pais = (isset($datos_finales[0]->descripcionPais)) ? $datos_finales[0]->descripcionPais : '';
                        $comparador = ($relacion != '' && $lista == 'PEP') ? 'RR' : $lista;
                        if (strlen($comparador) > 3) {
                            if ($marcador == 'SAN') {
                                $comparador = $marcador;
                            } else {
                                $comparador = 'SO';
                            }
                        }
                        //--  FIN SECCION AGREGADA  --//
                        switch ($comparador) {
                            case 'TER':
                                $fidecheck = 'P';  //-> ROJO - P
                                break;
                            case 'PEP':
                                $fidecheck = 'E'; //-> NARANJA - E
                                break;
                            case 'SAN':
                                $fidecheck = 'P'; //-> ROJO - P
                                break;
                            case 'SO':
                                $fidecheck = 'S'; //-> CELESTE - S --## PUEDEN VARIAR
                                break;
                            case 'RR':
                                $fidecheck = 'R'; //-> AMARILLO - R --## PUEDEN VARIAR
                                break;
                            default:
                                $fidecheck = 'N'; //-> VERDE - N
                                break;
                        }
                        //
                        if ($lista != '') {
                            $detalle .= 'Integrante de listas ' . $lista;
                        }
                        if ($detalle == '' && $pais != '') {
                            $detalle = 'Integrante de listas';
                        }
                        if ($pais != '') {
                            $detalle .= ' ' . $pais;
                        }
                        if ($detalle != '') {
                            $detalle .= ':';
                        }
                        if ($cargo != '') {
                            $detalle .= ' ' . $cargo;
                        }
                        if ($institucion != '') {
                            $detalle .= ' de ' . $institucion;
                        }
                        if ($relacion != '') {
                            $detalle .= ' - Relacionado: ' . $relacion;
                        }
                        //
                        $idr = 0;
                        $actualizo = SQLConnection::backendStoreProcedure('LN_actualiza_fidecheck', array($id, $cuit, $seccion, $fidecheck, $detalle, $idr), 'select');
                    }
                    usleep(1000000);
                }
            }
        }
        //
        $insert_queue = SQLConnection::backendStoreProcedure('LN_contrapartes_queue_', array('insert', NULL, $id), 'selectOne');
        $cliente = SQLConnection::backendStoreProcedure('LED_Clientes', array('select', $cl, NULL, NULL, NULL), 'selectOne');
        $nombre_cliente = $cliente->nombre_cliente;
        $cli_codigo = $cliente->cli_codigo;
        $cli_cuit = $cliente->numero;
        $sesion_id = isset(Session::get('usuario')->user_id) ? Session::get('usuario')->user_id : 15342812;
        $contrap = SQLConnection::backendStoreProcedure('LN_contrapartes_', array('select', $id, null, null, null, null, null, null, null, null, null, null, null, null, $sesion_id), 'selectOne');
        $socios = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'S'), 'select');
        $relac = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'R'), 'select');
        $direct = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'D'), 'select');
        $propio = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'P'), 'selectOne');
        //
        $servicio = $contrap->servicio_contratado;
        //
        $desde_contrapartes_genericos = 0;
        //
        if (Request::input('desde_contrapartes_genericos') == '1') {
            $nombre_servicio = Request::input('nombre_servicio');
            $tiene_api = Request::input('tieneApi');
            //
            $desde_contrapartes_genericos = Request::input('desde_contrapartes_genericos');
            $datos_redireccion = (object) ['nombre_servicio' => $nombre_servicio, 'tieneApi' => $tiene_api];
        } else {
            // DATOS PARA REDIRECCION
            $tipo_paquete = Request::input('tipo_paquete_cliente');
            $nombre_producto = Request::input('prod_nombre_cliente');
            $limite_consumo = Request::input('limite_consumo_cliente');
            $fecha_desde = Request::input('fecha_desde');
            $fecha_hasta = Request::input('fecha_hasta');
            $bloquea = Request::input('estado_bloquea_cliente');
            $estado_producto = Request::input('estado_producto_cliente');
            $modalidad_de_pago = Request::input('modalidad_de_pago');
            $impe_doc = Request::input('impe_doc');
            $impe_acceso = Request::input('impe_acceso');
            $servicio = $contrap->servicio_contratado;
            // DATOS PARA EL FORMULARIO DE REDIRECCIONAMIENTO
            $datos_redireccion = (object) ['tipo_paquete' => $tipo_paquete, 'nombre_producto' => $nombre_producto, 'limite' => $limite_consumo, 'desde' => $fecha_desde, 'hasta' => $fecha_hasta, 'bloquea' => $bloquea, 'estado_producto' => $estado_producto, 'modalidad_de_pago' => $modalidad_de_pago, 'impe_acceso' => $impe_acceso, 'impe_doc' => $impe_doc];
        }
        return view('/blue/servicios_cliente/fidecheck/fidecheck_automatico')->with(compact(['cliente', 'contrap', 'socios', 'relac', 'direct', 'propio', 'error', 'inicio', 'datos_redireccion', 'servicio', 'desde_contrapartes_genericos', 'nombre_cliente', 'cli_codigo', 'cli_cuit']));
    }

    //-----------------------------------------------------------------------------------------------------------------------------------//
    /*
    FUNCIONES ADAPTADAS, RESTA VERIFICAR
    */
    public static function grabarFidecheckPEP() {
        $contraparte = Request::input('contraparte');
        $cuit = Request::input('cuit');
        $detalle = Request::input('detalle');
        $fidecheck = Request::input('fidecheck');
        /* if ($fidecheck == 'S') {
            $fidecheck = 'R';
        } */
        $upd = SQLConnection::backendStoreProcedure('LN_demo_Fidecheck_update', array($contraparte, $cuit, $fidecheck, $detalle), 'selectOne');
        return 'ok';
    }

    //-----------------------------------------------------------------------------------------------------------------------------------//
    /*
    FUNCIONES ADAPTADAS, RESTA VERIFICAR
    */
    public static function obtenerPEPSListaCuits_Anterior() {
        // Los cuits a buscar se cargan en la tabla fidecheck_cuits, con una fecha determinada
        // Para procesarlos https://backend.fidelitas.com.ar/obtener-pep-cuit?fecha=aaaa-mm-dd (se pasa como parámetro esa fecha)
        $fecha = Request::input('fecha');
        $registros = DB::select("select cuit from fidecheck_cuits where (fidecheck is null or fidecheck = 'E') and fecha = '" . $fecha . "' order by cuit");

        foreach ($registros as $key => $cuits) {
            $cuit = $cuits->cuit;
            $nombre_persona = '';
            $id_padron = 0;
            $datos_finales = self::procesar_pep($cuit, $nombre_persona, $id_padron);
            if (isset($datos_finales['error'])) {
                $resp = $datos_finales['error'];
                $error = 'ERROR';
                echo "ERROR -> " . $cuit;
                break;
            }
            //------------------------------------  NUEVO  --------------------------------------------------------------------//
            /*if(count($datos_finales) == 0){
                $fidecheck  = 'N';
            }*/
            $fidecheck = 'N';

            if ($fidecheck !== null) {
                $detalle = '';
                $cargo = (isset($datos_finales[0]->cargo)) ? $datos_finales[0]->cargo : '';
                $institucion = (isset($datos_finales[0]->institucion)) ? $datos_finales[0]->institucion : '';
                $relacion = (isset($datos_finales[0]->relacion)) ? $datos_finales[0]->relacion : '';
                $lista = (isset($datos_finales[0]->tipoFuente)) ? $datos_finales[0]->tipoFuente : '';
                $pais = (isset($datos_finales[0]->descripcionPais)) ? $datos_finales[0]->descripcionPais : '';
                $comparador = ($relacion != '' && $lista == 'PEP') ? 'RR' : $lista;

                switch ($comparador) {
                    case 'TER':
                        $fidecheck = 'P';  //-> ROJO - P
                        break;

                    case 'PEP':
                        $fidecheck = 'E'; //-> NARANJA - E
                        break;

                    case 'SAN':
                        $fidecheck = 'P'; //-> ROJO - P
                        break;

                    case 'SO':
                        $fidecheck = 'S'; //-> CELESTE - S --## PUEDEN VARIAR
                        break;

                    case 'RR':
                        $fidecheck = 'R'; //-> AMARILLO - R --## PUEDEN VARIAR
                        break;

                    default:
                        $fidecheck = 'N'; //-> VERDE - N
                        break;
                }

                if ($lista != '') {
                    $detalle .= 'Integrante de listas ' . $lista;
                }
                if ($detalle == '' && $pais != '') {
                    $detalle = 'Integrante de listas';
                }
                if ($pais != '') {
                    $detalle .= ' ' . $pais;
                }
                if ($detalle != '') {
                    $detalle .= ':';
                }
                if ($cargo != '') {
                    $detalle .= ' ' . $cargo;
                }
                if ($institucion != '') {
                    $detalle .= ' de ' . $institucion;
                }
                if ($relacion != '') {
                    $detalle .= ' - Relacionado: ' . $relacion;
                }
                //$actualizo = SQLConnection::backendStoreProcedure('SP_actualiza_fidecheck_cuits', array($fecha,$cuit,$fidecheck,$detalle),'select');
                echo ($fecha . ' - ' . $cuit . ' - ' . $fidecheck . ' - ' . $detalle . '<br>');
            }

            usleep(2000000);
        }
        die();
    }

    public static function obtenerPEPSListaCuits() {
        // Los cuits a buscar se cargan en la tabla fidecheck_cuits, con una fecha determinada
        // Para procesarlos https://backend.fidelitas.com.ar/obtener-pep-cuit?fecha=aaaa-mm-dd (se pasa como parámetro esa fecha)
        $fecha = Request::input('fecha');
        $registros = DB::select("select f.cuit, p.nombre_persona, i.country_code from fidecheck_cuits f inner join padrones p on p.identificacion = f.cuit inner join identificadores i on i.identificador = p.identificador where f.fidecheck is null and f.fecha = '" . $fecha . "' order by f.cuit");

        foreach ($registros as $key => $cuits) {
            $cuit = $cuits->cuit;
            $nombre_persona = $cuits->nombre_persona;
            $id_padron = 0;
            //$datos_finales = self::procesar_pep($cuit, $nombre_persona, $id_padron);
            /* 04/11/2022, lo cambiamos por la consultApiWsNueva */
            $pais = $cuits->country_code;
            $datos_finales = ($pais=='AR') ? self::consultApiWsNueva($cuit, $nombre_persona, $pais) : self::consultApiWsNueva(null, $nombre_persona, null);
            /**/
            if (isset($datos_finales['error'])) {
                $resp = $datos_finales['error'];
                $error = 'ERROR';
                echo "ERROR -> " . $cuit;
                break;
            }

            $detalle = '';
            $cargo = (isset($datos_finales[0]->cargo)) ? $datos_finales[0]->cargo : '';
            $institucion = (isset($datos_finales[0]->institucion)) ? $datos_finales[0]->institucion : '';
            $relacion = (isset($datos_finales[0]->relacion)) ? $datos_finales[0]->relacion : '';
            $lista = (isset($datos_finales[0]->descripcionFuente)) ? $datos_finales[0]->descripcionFuente : '';
            $pais = (isset($datos_finales[0]->descripcionPais)) ? $datos_finales[0]->descripcionPais : '';
            $fidecheck = (isset($datos_finales[0]->fidecheck)) ? $datos_finales[0]->fidecheck : 'N';

            if ($lista != '') {
                $detalle .= 'Integrante de listas ' . $lista;
            }
            if ($detalle == '' && $pais != '') {
                $detalle = 'Integrante de listas';
            }
            if ($pais != '') {
                $detalle .= ' ' . $pais;
            }
            if ($detalle != '') {
                $detalle .= ':';
            }
            if ($cargo != '') {
                $detalle .= ' ' . $cargo;
            }
            if ($institucion != '') {
                $detalle .= ' de ' . $institucion;
            }
            if ($relacion != '') {
                $detalle .= ' - Relacionado: ' . $relacion;
            }
            $actualizo = SQLConnection::backendStoreProcedure('SP_actualiza_fidecheck_cuits', array($fecha, $cuit, $fidecheck, $detalle), 'select');
            echo ($fecha . ' - ' . $cuit . ' - ' . $fidecheck . ' - ' . $detalle . '<br>');

            usleep(2000000);
        }
        die();
    }
    //-----------------------------------------------------------------------------------------------------------------------------------//
    /*
    ESTA FUNCION SE EMPLEA PARA LA API '/fidecheck/json2' -> 'ApiControllerV1@obtenerApiPEP2'
    */
    public static function obtenerPEPApi() {
        $cuit = Request::input('cuit');
        $nombre_persona = Request::input('nombre_persona');
        $pais = Request::input('pais') ?? 'AR';
        $datos = SQLConnection::backendStoreProcedure('api_buscar_padron', array($pais, $cuit), 'selectOne');
        $nombre_persona = $datos->nombre_persona ?? $nombre_persona;
        //echo(var_dump(self::procesar_pep('20278185983', 'claudio arguello','0','Argentina'))); die();
        $datos_finales = self::procesar_pep($cuit, $nombre_persona, '0', $pais);
        $respuesta = [];
        $respuesta['error'] = 'OK';
        $respuesta['taxid'] = $cuit;//(isset($datos_finales[0]->documento)) ? $datos_finales[0]->documento : (isset($datos_finales[0]->identificacionTributaria)) ? $datos_finales[0]->identificacionTributaria : ''; //--> identificacionTributaria
        $respuesta['nombre'] = $nombre_persona;
        $respuesta['fidecheck'] = 'NEGATIVO';
        $respuesta['descripcion'] = (isset($datos_finales[0]->descripcionFuente)) ? $datos_finales[0]->descripcionFuente : '';
        $respuesta['lista'] = (isset($datos_finales[0]->tipoFuente)) ? $datos_finales[0]->tipoFuente : '';
        $respuesta['pais'] = (isset($datos_finales[0]->descripcionPais)) ? $datos_finales[0]->descripcionPais : '';
        $respuesta['cargo'] = (isset($datos_finales[0]->cargo)) ? $datos_finales[0]->cargo : '';
        $respuesta['institucion'] = (isset($datos_finales[0]->institucion)) ? $datos_finales[0]->institucion : '';
        $respuesta['relacion'] = (isset($datos_finales[0]->relacion)) ? $datos_finales[0]->relacion : '';
        $comparador = ($respuesta['relacion'] != '' && $respuesta['lista'] == 'PEP') ? 'RR' : $respuesta['lista'];

        if (isset($datos_finales['error'])) {
            $respuesta['error'] = $datos_finales['error'];
            $error = 'ERROR';
        } else {
            if (count($datos_finales) == 0) {
                $fidecheck = 'NEGATIVO';
            } else {
                switch ($comparador) {
                    case 'TER':
                        $respuesta['fidecheck'] = 'TERRORISTA';  //-> ROJO - P
                        break;

                    case 'PEP':
                        $respuesta['fidecheck'] = 'PEP'; //-> NARANJA - E
                        break;

                    case 'SAN':
                        $respuesta['fidecheck'] = 'SANCIONADO'; //-> ROJO - P
                        break;

                    case 'SO':
                        $respuesta['fidecheck'] = 'SUJETO OBLIGADO'; //-> CELESTE - S --## PUEDEN VARIAR
                        break;

                    case 'RR':
                        $respuesta['fidecheck'] = 'RELACIONADO'; //-> AMARILLO - R --## PUEDEN VARIAR
                        break;

                    case 'sujeto obligado':
                        $respuesta['fidecheck'] = 'SUJETO OBLIGADO'; //-> AMARILLO - R --## PUEDEN VARIAR
                        $respuesta['lista'] = 'SO';
                        break;

                    default:
                        $respuesta['fidecheck'] = 'NEGATIVO'; //-> VERDE - N
                        break;
                }
            }
        }
        return json_encode([$respuesta]);
    }

    //-----------------------------------------------------------------------------------------------------------------------------------//

    public static function obtenerPEPApi_full() {
        $cuit = Request::input('cuit');
        $nombre_persona = Request::input('nombre_persona');
        $datos_finales = self::procesar_pep_full($nombre_persona, $cuit);

        if (isset($datos_finales->error) && $datos_finales->error == 'No ha podido establecer la conexion con Worldsys') {
            return json_encode('ERROR DE CONEXIÓN');
        }

        return $datos_finales;

        //echo(var_dump($array->resultados)); die();
        $respuesta = [];
        $respuesta['error'] = 'OK';
        $respuesta['taxid'] = $cuit;//(isset($datos_finales[0]->documento)) ? $datos_finales[0]->documento : (isset($datos_finales[0]->identificacionTributaria)) ? $datos_finales[0]->identificacionTributaria : ''; //--> identificacionTributaria
        $respuesta['nombre'] = $nombre_persona;
        $respuesta['fidecheck'] = 'NEGATIVO';
        $respuesta['descripcion'] = (isset($datos_finales[0]->descripcionFuente)) ? $datos_finales[0]->descripcionFuente : '';
        $respuesta['lista'] = (isset($datos_finales[0]->tipoFuente)) ? $datos_finales[0]->tipoFuente : '';
        $respuesta['pais'] = (isset($datos_finales[0]->descripcionPais)) ? $datos_finales[0]->descripcionPais : '';
        $respuesta['cargo'] = (isset($datos_finales[0]->cargo)) ? $datos_finales[0]->cargo : '';
        $respuesta['institucion'] = (isset($datos_finales[0]->institucion)) ? $datos_finales[0]->institucion : '';
        $respuesta['relacion'] = (isset($datos_finales[0]->relacion)) ? $datos_finales[0]->relacion : '';
        $comparador = ($respuesta['relacion'] != '' && $respuesta['lista'] == 'PEP') ? 'RR' : $respuesta['lista'];

        if (isset($datos_finales->error)) {
            $respuesta['error'] = $datos_finales['error'];
            $error = 'ERROR';
        } else {
            if (count($datos_finales) == 0) {
                $fidecheck = 'NEGATIVO';
            } else {
                switch ($comparador) {
                    case 'TER':
                        $respuesta['fidecheck'] = 'TERRORISTA';  //-> ROJO - P
                        break;

                    case 'PEP':
                        $respuesta['fidecheck'] = 'PEP'; //-> NARANJA - E
                        break;

                    case 'SAN':
                        $respuesta['fidecheck'] = 'SANCIONADO'; //-> ROJO - P
                        break;

                    case 'SO':
                        $respuesta['fidecheck'] = 'SUJETO OBLIGADO'; //-> CELESTE - S --## PUEDEN VARIAR
                        break;

                    case 'RR':
                        $respuesta['fidecheck'] = 'RELACIONADO'; //-> AMARILLO - R --## PUEDEN VARIAR
                        break;

                    case 'sujeto obligado':
                        $respuesta['fidecheck'] = 'SUJETO OBLIGADO'; //-> AMARILLO - R --## PUEDEN VARIAR
                        $respuesta['lista'] = 'SO';
                        break;

                    default:
                        $respuesta['fidecheck'] = 'NEGATIVO'; //-> VERDE - N
                        break;
                }
            }
        }
        return json_encode([$respuesta]);
    }

    private static function procesar_pep_full($nombre_persona, $cuit) {
        $id_padron = '0';
        self::$id_resultados = [];
        $datos_finales = [];
        $resp = '';

        /*$ids =  SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_control', array($cuit,env('PEP_TOPE_DIAS')),'select');
        foreach($ids as $id){
            self::$id_resultados[] = $id->id_resultado;
            $resp = 'OK';   
        }*/
        //
        if (empty(self::$id_resultados) || !empty(self::$id_resultados)) {
            $id_llamadas = SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_llamados_', array('insert', '0', '', $nombre_persona, $id_padron, 'worldsys', null, null, null), 'selectOne');
            //$forzar_login = 'S'; 
            $forzar_login = 'N';

            $resp = '401'; // No hay token valido

            while ($resp == '401') {
                $resp = '0';
                $datos = self::obtenerDatosLogin(env('PEP_SERVICIO'), $forzar_login);
                $final_response = '';
                if (isset($datos->error)) {
                    $error_llamada = SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_llamados_', array('update', $id_llamadas->id, '', $nombre_persona, $id_padron, 'worldsys', '500', 'Error Login', $datos->error), 'selectOne');
                    $final_response = new stdClass();
                    $final_response->error = $datos->error;
                    $resp = $final_response->error;
                    //break; 
                    return $final_response;
                }

                if (isset($datos->token)) {
                    $resp = self::obtenerDatosPEP_full($nombre_persona, $id_padron, $datos->token, $id_llamadas->id, $cuit);
                    $forzar_login = 'S';
                    foreach ($resp as $i) {
                        if (isset($i->fechaNovedad)) {
                            $i->fechaNovedad = self::getFecha();
                        }
                    }
                    return $resp;
                }
            }
        }
        $datos_finales = [];
        if (!empty(self::$id_resultados)) {
            $ids = '';
            foreach (self::$id_resultados as $key => $id) {
                $ids .= ',' . $id;
            }

            $datos_finales = SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_select', array($ids), 'select');
        } else {
            $datos_finales['error'] = $resp;
        }

        //return $datos_finales;
        $res_temp = new stdClass();

        $res_temp->nombre = (isset($datos_finales[0]->nombre_persona)) ? $datos_finales[0]->nombre_persona : '';
        $res_temp->identificacionTributaria = (isset($datos_finales[0]->cuit)) ? $datos_finales[0]->cuit : '';
        $res_temp->fidecheck = (isset($datos_finales[0]->fidecheck)) ? $datos_finales[0]->fidecheck : '';
        $res_temp->cargo = (isset($datos_finales[0]->Cargo)) ? $datos_finales[0]->Cargo : '';
        $res_temp->institucion = (isset($datos_finales[0]->Institucion)) ? $datos_finales[0]->Institucion : '';
        if (isset($datos_finales[0]->TipoFuente) && $datos_finales[0]->TipoFuente == 'SO') {
            $res_temp->tipoFuente = 'sujeto obligado';
        }/* else if(isset($datos_finales[0]->TipoFuente) && $datos_finales[0]->TipoFuente == 'SAN') {
           $res_temp->tipoFuente = 'sujeto obligado';
       }*/ else {
            $res_temp->tipoFuente = '';
        }
        //$res_temp->tipoFuente = (isset($datos_finales[0]->TipoFuente) && $datos_finales[0]->TipoFuente == 'SO') ? 'sujeto obligado' : '';
        $res_temp->orden = (isset($datos_finales[0]->orden)) ? $datos_finales[0]->orden : '';
        $res_temp->descripcionPais = (isset($datos_finales[0]->DescripcionPais)) ? $datos_finales[0]->DescripcionPais : '';
        $res_temp->relacion = (isset($datos_finales[0]->Relacion)) ? $datos_finales[0]->Relacion : '';
        //$res_temp->contraparte = (isset($datos_finales[0]->cuit)) ? $datos_finales[0]->cuit : '';
        $res_temp->fechaNovedad = (isset($datos_finales[0]->fecha)) ? $datos_finales[0]->fecha : '';
        return array($res_temp);
    }

    private static function obtenerDatosPEP_full($nombre_persona, $id_padron, $token, $id_llamada, $cuit) {
        $url = env('PEP_LISTA_N') . $token;
        //--> ESTA LINEA DEBERIA QUEDAR, YA QUE SE ESPERAN LOS DATOS 
        $resp = self::CurlPEPListas_full($nombre_persona, $id_padron, $element = '', $url, $token, $id_llamada, $cuit);
        return $resp;

        //--> ESTA LINEA ES SOLO PARA DEBUG
        /*$element = (!isset($element)) ? '' : $element;
        self::CurlPEPListas($cuit,$nombre_persona,$id_padron,$element,$url,$token,$id_llamada,$pais);*/
    }

    public static function CurlPEPListas_full($nombre_persona, $id_padron, $element, $url, $token, $id_llamada, $cuit) {
        $resulado_alterno = array();
        $flag = '';
        $cuit_consultado = $cuit;
        $pais = ($cuit !== 'null' && strlen($cuit) == 11) ? 'AR' : 'null';
        $factorSimilitud = 75;//'90';
        $factorSimilitudInverso = 30;//'70';

        if ($cuit[0] != '3') {
            $cuit = (strlen($cuit) == 11) ? substr($cuit, 2, -1) : $cuit;
            $cuit = ($cuit[0] == '0') ? substr($cuit, 1) : $cuit;
            $id_tributaria = 'null';
        } else {
            $id_tributaria = $cuit;
            $cuit = 'null';
        }
        //------------------------------------------------------------------------------------------------------
        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "{\n \"nombre\": \"$nombre_persona\",\n \"documento\": $cuit,\n \"identificacionTributaria\": $id_tributaria,\n \"factorSimilitud\": $factorSimilitud,\n \"factorSimilitudInverso\": $factorSimilitudInverso,\n \"tipoFuente\": \"Todas\",\n }\n",
            CURLOPT_HTTPHEADER => [
                "Content-Type: application/json"
            ],
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);
        $flag = '1';
        //var_dump($response); die(); 
        curl_close($curl);

        //------------------------------------------------------------------------------------------------------
        if ($err) {
            $error = "cURL Error #:" . $err . ' ' . $response;
            if ($err == '' || !is_numeric($err)) {
                $err = -100;
            }
            //--  DESCOMENTAR ESTO PARA PRODUCCION O COMENTAR PARA DEBUG
            $error_llamada = SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_llamados_', array('update', $id_llamada, '', $nombre_persona, $id_padron, 'worldsys', $err, 'CURL Error', $error), 'selectOne');
            //-----------------------------------------------
            return $error;
        }
        $error = 'OK';

        //--  VARIABLE  --//
        $StatusCode = '';
        $Status = 'OK';
        $Reason = '';
        //---------------//

        /*
        EVALUAR SI ESTO SIGUE SIENDO NECESARIO

        $response = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $response);
        $response = str_replace('', '\'', $response);
        
        $xml = new \SimpleXMLElement($response);
        
        $array = json_decode(json_encode((array)$xml), TRUE);*/
        $array = json_decode($response);
        //echo(var_dump($array->resultados)); die();
        if (isset($array->code)) {
            $StatusCode = $array->code;
            $Status = '000';
            $Reason = $array->message;

            if ($StatusCode != '200') {
                $error = $StatusCode;
                //return $error;
                return $datos_finales = array();
            }

        }
        if ($StatusCode == '' || !is_numeric($StatusCode)) {
            $StatusCode = -100;
        }
        //--  DESCOMENTAR TODA ESTA SECCION PARA PRODUCCION O COMENTAR PARA DEBUG
        $error_llamada = SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_llamados_', array('update', $id_llamada, '', $nombre_persona, $id_padron, 'worldsys', $StatusCode, $Status, $Reason), 'selectOne');
        if ($Status == 'OK' && (!isset($array->resultados) || count($array->resultados) == 0)) {
            $id_resultado = SQLConnection::backendStoreProcedure('LN_Fidecheck_ws_',
                array('', $nombre_persona, $id_padron, 'worldsys',
                    $StatusCode,
                    $Status,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    'N'),
                'selectOne');
            $error = array();
            self::$id_resultados[] = $id_resultado->id_resultado;
            $clon = new stdClass;
            $clon->error = 'ok';
            $clon->taxid = $cuit_consultado;
            $clon->nombre = $nombre_persona;
            $clon->fidecheck = 'NEGATIVO';
            $clon->descripcion = '';
            $clon->lista = '';
            $clon->pais = '';
            $clon->cargo = '';
            $clon->institucion = '';
            $clon->relacion = '';
            return [$clon];
            //return $error; //--> aca

        }
        //---------------------------------------------  HASTA ACA  ----------------------------------------------------------------
        $rr = array();
        //return [$array->resultados];
        $esultado_final = array();
        if ($Status == 'OK' && isset($array->resultados) && count($array->resultados) > 0) {
            for ($i = 0; $i < count($array->resultados); $i++) {
                $clon = new stdClass;
                $clon->error = 'ok';
                $clon->index = isset($array->resultados[$i]->index) ? $array->resultados[$i]->index : '';
                $clon->id = isset($array->resultados[$i]->id) ? $array->resultados[$i]->id : '';
                $clon->score = isset($array->resultados[$i]->score) ? $array->resultados[$i]->score : '';
                $clon->fuente = isset($array->resultados[$i]->fuente) ? $array->resultados[$i]->fuente : '';
                $clon->taxid = isset($array->resultados[$i]->identificacionTributaria) ? $array->resultados[$i]->identificacionTributaria : '';
                $clon->nombre = $array->resultados[$i]->nombre;

                $comparador = ($array->resultados[$i]->relacion != '' && $array->resultados[$i]->tipoFuente == 'PEP') ? 'RR' : $array->resultados[$i]->tipoFuente;
                //$array->resultados[$i]->relacion = $rr[$i];
                //--  SE FORMATEA FECHA  --//
                if ($array->resultados[$i]->fechaNovedad !== null) {
                    $feche_temporal = $array->resultados[$i]->fechaNovedad;
                    $feche_temporal = explode('T', $feche_temporal);
                    $feche_temporal = explode('-', $feche_temporal[0]);
                    $array->resultados[$i]->fechaNovedad = $feche_temporal[2] . '-' . $feche_temporal[1] . '-' . $feche_temporal[0];
                } else {
                    $array->resultados[$i]->fechaNovedad = 'S/F';
                }

                switch ($comparador) {
                    case 'TER':
                        $array->resultados[$i]->fidecheck = 'P';  //-> ROJO - P
                        $clon->fidecheck = 'SANCIONADO';
                        $array->resultados[$i]->orden = 2;
                        $array->resultados[$i]->tipoFuente = $array->resultados[$i]->descripcionFuente;
                        break;

                    case 'PEP':
                        $array->resultados[$i]->fidecheck = 'E'; //-> NARANJA - E
                        $clon->fidecheck = 'PEP';
                        $array->resultados[$i]->orden = 3;
                        break;

                    case 'SAN':
                        $array->resultados[$i]->fidecheck = 'P'; //-> ROJO - P
                        $clon->fidecheck = 'SANCIONADO';
                        $array->resultados[$i]->orden = 2;
                        /*$array->resultados[$i]->orden = 3;*/
                        $array->resultados[$i]->tipoFuente = $array->resultados[$i]->descripcionFuente;
                        break;

                    case 'SO':
                        $array->resultados[$i]->fidecheck = 'S'; //-> CELESTE - S --## PUEDEN VARIAR
                        $clon->fidecheck = 'SUJETO OBLIGADO';
                        $array->resultados[$i]->orden = 3;
                        $array->resultados[$i]->tipoFuente = 'sujeto obligado';
                        break;

                    case 'RR':
                        $array->resultados[$i]->fidecheck = 'R'; //-> AMARILLO - R --## PUEDEN VARIAR
                        $clon->fidecheck = 'RELACIONADO';
                        $array->resultados[$i]->orden = 4;
                        break;

                    default:
                        $array->resultados[$i]->fidecheck = 'N'; //-> VERDE - N
                        $clon->fidecheck = 'NEGATIVO';
                        $array->resultados[$i]->orden = 2;
                        break;
                }
                $clon->descripcion = (isset($array->resultados[$i]->descripcionFuente)) ? $array->resultados[$i]->descripcionFuente : '';
                $clon->lista = (isset($array->resultados[$i]->tipoFuente)) ? $array->resultados[$i]->tipoFuente : '';
                $clon->pais = (isset($array->resultados[$i]->descripcionPais)) ? $array->resultados[$i]->descripcionPais : '';
                $clon->cargo = (isset($array->resultados[$i]->cargo)) ? $array->resultados[$i]->cargo : '';
                $clon->institucion = (isset($array->resultados[$i]->institucion)) ? $array->resultados[$i]->institucion : '';
                $clon->relacion = (isset($array->resultados[$i]->relacion)) ? $array->resultados[$i]->relacion : '';
                $clon->url = (isset($array->resultados[$i]->url)) ? $array->resultados[$i]->url : '';
                if ($array->resultados[$i]->identificacionTributaria == $cuit_consultado) {
                    return [$clon];
                }
                $esultado_final[$i] = $clon;
            }
            //echo(var_dump(self::$id_resultados)); die();
            //return $array->resultados;

            return $esultado_final;
        }

        return $error;
        //--  DEBUG  --//

    }

    public function ContraparteFidecheckautomaticoNuevo_ledOrg() {
        $cl = Request::input('cliente');
        $id = Request::input('contraparte');
        //
        $error = '';
        //
        $registros = SQLConnection::backendStoreProcedure('LN_completa_fidecheck', array($id), 'select');
        if (count($registros) > 0) {

            $i = 0;
            //
            if (env('PEP_FIDECHECK_AUTOMATICO_VA_A_WORLDSYS') !== 'NO') {
                foreach ($registros as $cuits) {
                    $i += 1;
                    $buscar_afip = self::CURLCall(env('URL_FRONTEND') . '/api/local/v1/afip/obtener-padron/' . $cuits->tax_id, 'GET');
                    $cuit = $cuits->tax_id;
                    $nombre_persona = $cuits->nombre;
                    $id_padron = 0;
                    $seccion = $cuits->seccion;

                    //-- se obtiene el pais codigo ej: AR
                    $pais_code = (isset($cuits->country_code)) ? $cuits->country_code : 'AR';
                    //-- aca hace la consulta a ws.
                    $datos_finales = ($pais_code=='AR') ? self::consultApiWsNueva($cuit, $nombre_persona, $pais_code) : self::consultApiWsNueva(null, $nombre_persona, null);
                    $detalle = '';
                    $cargo = (isset($datos_finales[0]->cargo)) ? $datos_finales[0]->cargo : '';
                    $institucion = (isset($datos_finales[0]->institucion)) ? $datos_finales[0]->institucion : '';
                    $relacion = (isset($datos_finales[0]->relacion)) ? $datos_finales[0]->relacion : '';
                    $lista = (empty($lista) && isset($datos_finales[0]->fuente)) ? $datos_finales[0]->fuente : '';
                    $descripcion_corta = (isset($datos_finales[0]->descripcionFuente)) ? $datos_finales[0]->descripcionFuente : '';
                    $fidecheck = (isset($datos_finales[0]->fidecheck)) ? $datos_finales[0]->fidecheck : 'N';
                    $pais = (isset($datos_finales[0]->descripcionPais)) ? $datos_finales[0]->descripcionPais : '';

                    if ($lista != '') {
                        $detalle .= 'Integrante de listas ' . $lista;
                    }
                    if ($detalle == '' && $pais != '') {
                        $detalle = 'Integrante de listas';
                    }
                    if ($pais != '') {
                        $detalle .= ' ' . $pais;
                    }
                    if ($detalle != '') {
                        $detalle .= ':';
                    }
                    if ($cargo != '') {
                        $detalle .= ' ' . $cargo;
                    }
                    if ($institucion != '') {
                        $detalle .= ' de ' . $institucion;
                    }
                    if ($relacion != '') {
                        $detalle .= ' - Relacionado: ' . $relacion;
                    }
                    if ( $descripcion_corta != '' ){
                        $detalle .= ' '. $descripcion_corta;
                    }
                    $idr = 0;
                    $actualizo = SQLConnection::backendStoreProcedure('LN_actualiza_fidecheck', array($id, $cuit, $seccion, $fidecheck, $detalle, $idr), 'select');
                    usleep(1000000);
                }
            }
        }
        //
        $insert_queue = SQLConnection::backendStoreProcedure('LN_contrapartes_queue_', array('insert', NULL, $id), 'selectOne');
        $temp = SQLConnection::backendStoreProcedure('LN_DASHBOARD_CLIENTE', array('FIDECHECK', NULL, null, null, $id), 'selectOne');

        $desde_contrapartes_genericos = 0;
        echo json_encode(array("error" => 0));
    }

    public function ContraparteFidecheckautomaticoNuevo_led() {
        try {
            $cl = Request::input('cliente');
            $id = Request::input('contraparte');
            $datos_finales_array = [];
            $duplicado = false;
    
            $registros = SQLConnection::backendStoreProcedure('LN_completa_fidecheck', [$id], 'select');
            if (count($registros) > 0 && env('PEP_FIDECHECK_AUTOMATICO_VA_A_WORLDSYS') !== 'NO') {
                foreach ($registros as $cuits) {
                    // Obtener datos de la API
                    $buscar_afip = self::CURLCall(env('URL_FRONTEND') . '/api/local/v1/afip/obtener-padron/' . $cuits->tax_id, 'GET');
                    $cuit = $cuits->tax_id;
                    $nombre_persona = $cuits->nombre;
                    $pais_code = $cuits->country_code ?? 'AR';
                    $datos_finales = ($pais_code == 'AR') ? self::consultApiWsNueva($cuit, $nombre_persona, $pais_code) : self::consultApiWsNueva(null, $nombre_persona, null);
                
                    $detalle = '';

                    $cargo = (isset($datos_finales[0]->cargo)) ? $datos_finales[0]->cargo : '';
                    $institucion = (isset($datos_finales[0]->institucion)) ? $datos_finales[0]->institucion : '';
                    $relacion = (isset($datos_finales[0]->relacion)) ? $datos_finales[0]->relacion : '';
                    $lista = (isset($datos_finales[0]->descripcionFuente)) ? $datos_finales[0]->descripcionFuente : '';
                    $lista = (empty($lista)) ? $datos_finales[0]->tipoFuente : $lista;
                    $fidecheck = (isset($datos_finales[0]->fidecheck)) ? $datos_finales[0]->fidecheck : 'N';
                    $pais = (isset($datos_finales[0]->descripcionPais)) ? $datos_finales[0]->descripcionPais : '';
                    $seccion = $cuits->seccion;
                    if ($lista != '') {
                        $detalle .= 'Integrante de listas ' . $lista;
                    }
                    if ($detalle == '' && $pais != '') {
                        $detalle = 'Integrante de listas';
                    }
                    if ($pais != '') {
                        $detalle .= ' ' . $pais;
                    }
                    if ($detalle != '' && $cargo != '' && $institucion != '' && $relacion != '') {
                        $detalle .= ':';
                    }
                    if ($cargo != '') {
                        $detalle .= ' ' . $cargo;
                    }
                    if ($institucion != '') {
                        $detalle .= ' de ' . $institucion;
                    }
                    if ($relacion != '') {
                        $detalle .= ' - Relacionado: ' . $relacion;
                    }
                    $idr = 0;   
                    $duplicado = (count($datos_finales) > 1);
                    if (count($datos_finales) < 1) {
                        continue;
                    }
                    
                    if ( $duplicado ){
                        foreach ($datos_finales as $df) {
                            $fidecheck = $df->fidecheck ?? 'N';
                           // dd($df);
                            $datos_finales_array["$cuit-$seccion"][] = [
                                'id' => $id,
                                'nombre' => $nombre_persona,
                                'fidecheck' => $fidecheck,
                                'seccion' => $seccion,
                                'detalle' => $detalle,
                                'fuente' => $df->fuente ?? '',
                                'tipo_fuente' => $df->tipoFuente ?? '',
                                'documento_e' => $df->documento ?? '',
                                'residencia' => $df->residencia ?? '',
                                'descripcion_p' => $df->descripcionPais ?? '',
                                'fecha_novedad' => $df->fechaNovedad ?? '',
                                'cargo' => $df-> cargo ?? '',
                                'institucion' => $df -> institucion ?? '',
                                'domicilio' => $df -> domicilio ?? '' ,
                                'relacion' => $df -> relacion ?? '',
                                'url' => $df -> url ?? '', 
                                'score' => $df -> score ?? ''
    
                            ];
                        }
                        $fidecheck = '';
                        $detalle = '';
                    }
                    // Guardar en base de datos
                    $actualizo = SQLConnection::backendStoreProcedure('LN_actualiza_fidecheck', array($id, $cuit, $seccion, $fidecheck, $detalle, $idr), 'select');
                 
    
                    usleep(1000000); // Pausa para evitar sobrecarga
                }
            }
            //
            // Cargar datos adicionales para la vista
            $cliente = SQLConnection::backendStoreProcedure('LED_Clientes', ['select', $cl, NULL, NULL, NULL], 'selectOne');
            $contrap = SQLConnection::backendStoreProcedure('LN_contrapartes_', ['select', $id, null, null, null, null, null, null, null, null, null, null, null, null, Session::get('usuario')->user_id], 'selectOne');
            
            $socios = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', ['searchall', null, $id, null, 'S'], 'select');
            $relac = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', ['searchall', null, $id, null, 'R'], 'select');
            $direct = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', ['searchall', null, $id, null, 'D'], 'select');
            $propio = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', ['searchall', null, $id, null, 'P'], 'selectOne');
            //  dd($datos_finales);
            $insert_queue = SQLConnection::backendStoreProcedure('LN_contrapartes_queue_', array('insert', NULL, $id), 'selectOne');
            $temp = SQLConnection::backendStoreProcedure('LN_DASHBOARD_CLIENTE', array('FIDECHECK', NULL, null, null, $id), 'selectOne');   
             
            $desde_contrapartes_genericos = 0;
              //  echo json_encode(array("error" => 0));
            //dd($datos_finales);
            return view('/informes-blue/fidecheck/fidecheck_automatico')->with(compact(['cliente', 'contrap', 'socios', 'relac', 'direct', 'propio', 'datos_finales_array']));
             //echo json_encode(array("error" => 0));
        
        } catch (\Exception $e) {
            // Manejo de excepciones
            \Log::error('Error en ContraparteFidecheckautomaticoNuevo_led: ' . $e->getMessage());
            return response()->json(['error' => 'Hubo un problema al procesar los datos.'], 500);
        }
    }

    public function guardarDatosModalFidecheck() {
        // Lógica para guardar los datos
        $id = Request::input('id');
        $cuit = Request::input('cuit');
        $seccion = Request::input('seccion');
        $fidecheck	 = Request::input('fidecheck');
        $detalle = Request::input('detalle');

        $idr= 0;
        // Guardar en base de datos
        $actualizo = SQLConnection::backendStoreProcedure('LN_actualiza_fidecheck',  array($id, $cuit, $seccion, $fidecheck, $detalle, $idr), 'select');
        usleep(1000000);
    }

    public function fidecheckseccionaparte() {
        $cl = Request::input('cliente');
        $id = Request::input('contraparte');
        $cliente = SQLConnection::backendStoreProcedure('LED_Clientes', array('select', $cl, NULL, NULL, NULL), 'selectOne');
        $nombre_cliente = $cliente->nombre_cliente;
        $cli_codigo = $cliente->cli_codigo;
        $cli_cuit = $cliente->numero;
        $sesion_id = Session::get('usuario')->user_id;
        $contrap = SQLConnection::backendStoreProcedure('LN_contrapartes_', array('select', $id, null, null, null, null, null, null, null, null, null, null, null, null, $sesion_id), 'selectOne');
        $socios = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'S'), 'select');
        $relac = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'R'), 'select');
        $direct = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'D'), 'select');
        $propio = SQLConnection::backendStoreProcedure('LN_demo_fidecheck_', array('searchall', null, $id, null, 'P'), 'selectOne');
        //
        $servicio = $contrap->servicio_contratado;
        //
        $desde_contrapartes_genericos = 0;
        //
        return view('/informes-blue/fidecheck/fidecheck_automatico')->with(compact(['cliente', 'contrap', 'socios', 'relac', 'direct', 'propio', 'desde_contrapartes_genericos', 'nombre_cliente', 'cli_codigo', 'cli_cuit']));
    }

    //FUNCION PARA EL BACKUP DE AMX, POR EL MOMENTO LO PONGO EN ESTE CONTROLADOR - TB
    public function backupAmx() {
        // Para procesarlos http://backend.fidelitas.test/backup-documentos?cliente_cod=5546348 (se pasa como parámetro un codigo de cliente)
        $cliente_cod = Request::input('cliente_cod');

        /*  
            $logo = env('RUTA_CSS_PDF_ICNEW').'/public/'.Session::get('webdata')['uri_logo'];
            $css = Session::get('webdata')['uri_css2'];
            $fecha_create = (new DateTime('now'))->format('Y-m-d'); 

            [LN_backups_gestiones]
            @cliente int, 
            @nombre varchar(500) = ''
        */

        $contrapartes = SQLConnection::backendStoreProcedure('LN_backups_gestiones', array($cliente_cod, ""));
        foreach ($contrapartes as &$item) {
            $primer_contraparte = $contrapartes[0]->contraparte;
            $pais_contraparte = $contrapartes[0]->country_code;

            if ($item->contraparte == $primer_contraparte) {

                //if(!is_dir(ENV('PATH_BACKUP_AMX').'/'.$cliente_cod)){
                //    mkdir(ENV('PATH_BACKUP_AMX').'/'.$cliente_cod, 0777,true);
                //}

                $file = env('PATH_BACKUP_AMX') . '/' . $cliente_cod . '/' . $pais_contraparte . '/' . $item->taxid . '_' . $item->nombre_tipo_doc . '_' . $item->contraparte . '_' . $item->gestion;
                $file_2 = env('PATH_BACKUP_AMX') . '/' . $cliente_cod . '/' . $pais_contraparte . '/' . $item->taxid . '_' . $item->nombre_tipo_doc . '_' . $item->contraparte . '_' . $item->gestion . '.pdf';
                dd($file, $file_2);

            } else if ($item->contraparte !== $primer_contraparte) {
                $primer_contraparte = $item->contraparte;
            }

            if ($item->contraparte == $primer_contraparte) {
                var_dump($item->nombre_tipo_doc);
            }
        }
    }
}
