<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Custom\Misc;
use App\Custom\SQLConnection;

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

use Datetime;

class Proceso extends Model {

    public static $raiz_dir;
    public static $archivos_src_dir;
    public static $archivos_des_dir;
    public static $directorio_log;
    public static $directorio_fuente;
    public static $directorio_destino;
    public static $archivos;
    public static $consultar_errores;
    public static $fuentes;
    public static $fuente;
    public static $fuente_key;
    public static $fuente_fecha;
    public static $impo_expo;
    public static $fields;
    public static $linea;
    public static $store_procedure;
    public static $separador_campos;
    public static $log;
    public static $log_url;
    public static $errorlog;
    public static $juicios_bt;
    public static $procesar_bajas;
    public static $juicios_csv_fields_arr;
    public static $cantidad_lineas;
    public static $cantidad_lineas_procesadas;

    public static function inicializarRutas() {
        self::$raiz_dir = ENV('RUTA_PROCESOS');
        self::$archivos_src_dir = realpath(ENV('RUTA_PROCESOS_ARCHIVOS'));
        self::$archivos_des_dir = realpath(ENV('RUTA_PROCESOS_PROCESADOS'));
        self::$directorio_log = realpath(ENV('RUTA_PROCESOS_LOGS'));

    }

    public static function asignarDatosInicialesDeFuente($fuente) {
        self::$fuentes = Proceso::obtenerFuentes();
        self::$fuente_key = $fuente;
        self::$juicios_bt = Request::input('juicios_bt');

        self::$linea = Request::input('linea');
        self::$fuente = self::$fuentes[self::$fuente_key];

        self::$fuente_fecha = Request::input('fuente_fecha');

        self::$impo_expo = Request::input('impo_expo');

        self::$store_procedure = self::$fuente['store_procedure'];
        self::$separador_campos = self::$fuente['separador_campos'];
        if (self::$juicios_bt) {
            // self::$store_procedure = str_replace('_insertar', '_'.self::$juicios_bt.'_insertar', self::$store_procedure);
            if (self::$juicios_bt == 'tucumanyconcepcion') {
                self::$separador_campos = "\t";
            }
        }
        self::$procesar_bajas = !(empty($_FILES["bajas"]['name'])); // true solo si existe un archivo de procesar bajas

        // set logs filesnames
        $logbasename = preg_replace("/%timestamp%/", date("Ymd_His"), strtoupper(self::$fuente_key) . "_%timestamp%.html");
        self::$log_url = ENV('RUTA_PROCESOS_LOGS') . DIRECTORY_SEPARATOR . $logbasename;
        self::$log = self::$directorio_log . DIRECTORY_SEPARATOR . $logbasename;
        $errorlogbasename = preg_replace("/%timestamp%/", date("Ymd_His"), strtoupper(self::$fuente_key) . "_errores_%timestamp%.log");
        self::$errorlog = self::$directorio_log . DIRECTORY_SEPARATOR . $errorlogbasename;
        // buscar $archivos


        self::$directorio_fuente = self::$archivos_src_dir . DIRECTORY_SEPARATOR . self::$fuente['folder'];
        self::$directorio_destino = self::$archivos_des_dir . DIRECTORY_SEPARATOR . self::$fuente['folder'];

        list($res, $data) = self::obtenerArchivos(self::$directorio_fuente);
        if ($res === 0) {
            self::$archivos = [];
        } else {
            self::$archivos = $data;
            self::$consultar_errores = 0;
            // start procesamiento
            Misc::Log("<strong>Importando " . strtoupper(self::$fuente_key) . "...</strong>", self::$log, "html");
        }
        $log_url = self::$log_url;
        // Cargar la vista con la barra de progreso
        echo view('procesos.progress', compact('log_url'))->render();

        return 0;
    }

    // hace foreach de cada archivo y envia cada linea a funcion especifica fuente
    public static function procesarArchivos($params = []) {

        foreach (self::$archivos as $filename) {
            //PROCESO SOLAMENTE DE LA FUENTE CYQ DE Bustos Thames.
            $file = file($filename);
            self::$cantidad_lineas_procesadas = 0;

            if (file_exists($filename)) {
                if (!self::validarFechaFuente()) {
                    continue;
                }
                if (self::$fuente_key == 'cyq_bt') {
                    $cantidad = count($file);
                    $i = 0;
                    foreach ($file as $key => $value) {


                        $sindico = '';
                        $demandado = '';
                        $cuit_demandado = '';
                        $actual = $file[$key];
                        $actual_exp = explode('|', $actual);

                        if (isset($file[$key + 1])) {
                            $siguiente = $file[$key + 1];
                            $siguiente_exp = explode('|', $siguiente);
                        } else {
                            $siguiente_exp[0] = '';
                        }

                        if (isset($file[$key + 2])) {
                            $ter = $file[$key + 2];
                            $ter_exp = explode('|', $ter);
                        } else {
                            $ter_exp[0] = '';
                        }

                        if (isset($file[$key - 1])) {
                            $ant = $file[$key - 1];
                            $ant_exp = explode('|', $ant);
                        } else {
                            $ant_exp[0] = '';
                        }

                        //dd($actual_exp);
                        if ($actual_exp[0] == $siguiente_exp[0]) {

                            if (($actual_exp[13] != 'SINDICO' || $actual_exp[13] != 'SÍNDICO') && ($siguiente_exp[13] == 'SINDICO' || $siguiente_exp[13] == 'SÍNDICO')) {

                                if (isset($file[$key + 2])) {
                                    $tercero = $file[$key + 2];
                                    $tercero_exp = explode('|', $tercero);
                                } else {
                                    $tercero_exp[0] = '';
                                }

                                if (($actual_exp[0] == $siguiente_exp[0]) && ($tercero_exp[0] == $actual_exp[0])) {
                                    $sindico = $siguiente_exp[14] . '-' . $tercero_exp[14];
                                } else {
                                    $sindico = $siguiente_exp[14];
                                }

                                $demandado = $actual_exp[14];
                                $cuit_demandado = $actual_exp[15];
                            }


                            if (($actual_exp[13] == 'SINDICO' || $actual_exp[13] == 'SÍNDICO') && ($siguiente_exp[13] == 'SINDICO' || $siguiente_exp[13] == 'SÍNDICO')) {

                                if (isset($file[$key - 1])) {
                                    $anterior = $file[$key - 1];
                                    $anterior_exp = explode('|', $anterior);
                                } else {
                                    $anterior_exp[0] = '';
                                }

                                $demandado = $anterior_exp[14];
                                $sindico = $siguiente_exp[14] . '-' . $actual_exp[14];
                                $cuit_demandado = $anterior_exp[15];
                            }
                        } elseif ($actual_exp[0] == $ant_exp[0]) {
                            if (($actual_exp[13] == 'SÍNDICO') && ($ant_exp[13] == 'SÍNDICO')) {
                                if (isset($file[$key - 2])) {
                                    $anterior = $file[$key - 2];
                                    $anterior_exp = explode('|', $anterior);
                                }

                                $demandado = $anterior_exp[14];
                                $sindico = $actual_exp[14];
                                $cuit_demandado = $anterior_exp[15];
                            }

                            if (($actual_exp[13] == 'SÍNDICO') && ($ant_exp[13] != 'SÍNDICO')) {
                                $demandado = $ant_exp[14];
                                $sindico = $actual_exp[14];
                                $cuit_demandado = $ant_exp[15];
                            }

                        }

                        // if($key == 9) {
                        // 	$datos = self::parsearLineaCYQBT($value,'','',$sindico,$demandado,$cuit_demandado);	
                        // 	Misc::ddd($datos);
                        // }

                        $datos = self::parsearLineaCYQBT($value, '', '', $sindico, $demandado, $cuit_demandado);
                        SQLConnection::cargaFuenteCyQbt($datos);
                        $i = $i + 1;
                        self::porcentajeBarraProgreso($i, $cantidad);
                    }
                    return;
                }
                if (self::$fuente_key == 'juicios_bt') {
                    $valido_juiciosbt = self::esValidoArchivoJuiciosBT($filename);
                    if (!$valido_juiciosbt) {
                        self::$consultar_errores = 1;
                        continue;
                    }
                }
                // cantidad de lineas a procesar para mostrar en barra de progreso
                $array_of_lines = file($filename);
                $cantidad = count($array_of_lines);
                self::$cantidad_lineas = $cantidad;
                $i = $n_linea = 1;
                $lineas_ok = $lineas_error = 0;
                $file = fopen($filename, "r");
                $nombre_file = ltrim(str_replace(self::$directorio_fuente, "", $filename), "/");

                while (($LINE = fgets($file)) !== FALSE) { // PROCESAR LINEAS ------------------------------------------------

                    // Misc::Log(memory_get_usage()." Memoria empezando la linea $i", self::$log, "html");
                    if (!preg_match('!!u', $LINE)) {
                        $try_utf8 = TRUE;
                        if (mb_detect_encoding($LINE) === FALSE) {
                            try {
                                $try_utf8 = FALSE;
                                $LINE = iconv("windows-1252", "UTF-8", $LINE);
                            } catch (\Exception $e) {
                                self::$consultar_errores = 1;
                                Misc::Log("Error en la conversion con iconv(). [" . $nombre_file . ":" . $n_linea . "]", self::$errorlog);
                                $try_utf8 = TRUE;
                            }

                        } elseif ($try_utf8) {
                            try {
                                $LINE = mb_convert_encoding($LINE, 'UTF-8', 'ISO-8859-1');
                            } catch (\Exception $e) {
                                self::$consultar_errores = 1;
                                Misc::Log("Error en la conversion con utf8_encode(). [" . $nombre_file . ":" . $n_linea . "]", self::$errorlog);
                                $n_linea++;
                                continue;
                            }
                        }
                    }

                    /* parse line */
                    $values_arr = []; // array de arrays: puede haber mas de una linea para insertar 
                    if (self::$fuente_key == 'juicios_bt') {
                        // tomo la primera linea para identificar los campos que se utilizaran
                        if ($n_linea == 1) {
                            $LINE = rtrim(trim($LINE), self::$separador_campos);
                            self::$juicios_csv_fields_arr = array_map("trim", explode(self::$separador_campos, $LINE));
                            $n_linea++;
                            $cantidad--;
                            self::$cantidad_lineas = $cantidad;
                            continue;
                        }
                    } elseif ((self::$fuente_key == 'juicios_jurad' || self::$fuente_key == 'juicios_myf') && ($n_linea == 1)) {
                        // primera linea con nombres campos
                        $n_linea++;
                        $cantidad--;
                        self::$cantidad_lineas = $cantidad;
                        continue;
                    }
                    // obtener metodo por tipo de fuente
                    $nombre_metodo = 'parsearLinea' . self::obtenerNombreMetodo();
                    // ejecutar parsear linea dinámico
                    // Misc::Log(memory_get_usage()." - Antes de funcion parse linea $i", self::$log, "html");
                    $values_arr = self::$nombre_metodo($LINE, $nombre_file, $n_linea, $params);
                    // Misc::Log(memory_get_usage()." - Luego de funcion parse linea $i", self::$log, "html");
                    $n_linea++;
                    if ($values_arr === 0) {
                        $lineas_error++;
                        self::$consultar_errores = 1;
                        continue;
                    }
                    /* insert via store procedure */
                    $ok = 0;
                    if (!self::$linea) {
                        self::$linea = 0;
                    }
                    foreach ($values_arr as $values) {
                        if ($n_linea >= self::$linea) {
                            try {
                                //dd(array_values($values)); 
                                // Misc::Log(memory_get_usage()." - Antes de SQL insertar linea $i", self::$log, "html");
                                $res = SQLConnection::backendStoreProcedure(self::$store_procedure, array_values($values));
                                // Misc::Log(memory_get_usage()." - Luego de SQL insertar linea $i", self::$log, "html");
                                self::$cantidad_lineas_procesadas++;
                                $ok++;
                            } catch (\Exception $e) {
                                self::$consultar_errores = 1;
                                Misc::Log("[ERROR SP " . self::$store_procedure . "][" . $nombre_file . ":" . $n_linea . "] VALUES: " . implode(",", $values) . "| SQLError: " . $e->getMessage(), self::$errorlog);
                            }
                            if ($ok < count($values_arr)) {
                                self::$consultar_errores = 1;
                            }
                            $lineas_ok++;
                        }
                    }

                    self::porcentajeBarraProgreso($i, $cantidad);
                    // Misc::Log(memory_get_usage()." Memoria terminando la linea $i <br>", self::$log, "html");

                    $i = $i + 1;
                } //END WHILE PROCESAR LINEAS ----------------------------------------------------------------------------------

                Misc::Log("Procesado " . $filename, self::$log, "html");
                Misc::Log("Lineas procesadas: <strong>" . $lineas_ok . "</strong>", self::$log, "html");
                if ($lineas_error > 0) {
                    Misc::Log("<span style='color:red;'>Lineas no procesadas: <strong>" . $lineas_error . "</strong></span>", self::$log, "html");
                }

                fclose($file);

                //muevo file
                //$fileinfo = pathinfo($filename);
                //$destfile = self::$directorio_destino.DIRECTORY_SEPARATOR.$fileinfo["basename"];
                $destfile = str_replace(self::$directorio_fuente, self::$directorio_destino, $filename);
                $res = Misc::moverArchivo($filename, $destfile);
                if ($res == 1) {
                    Misc::Log("Muevo $filename a " . self::$directorio_destino, self::$log, "html");
                } else {
                    Misc::Log("No se pudo mover el file $filename a " . self::$directorio_destino . ": $res", self::$log, "html");
                    self::$consultar_errores = 1;
                    Misc::Log("No se pudo mover el file $filename a " . self::$directorio_destino . ": $res", self::$errorlog);
                }

            } else {
                Misc::Log("No se pudo abrir el archivo $filename", self::$log, "html");
                self::$consultar_errores = 1;
                Misc::Log("No se pudo abrir el archivo $filename", self::$errorlog);
            }

            echo '
			<script language="javascript">
				$("#information").html("Proceso completado <br>Se procesaron ' . ($i - 1) . ' registros de ' . $cantidad . '");
			</script>';

        } // end FOREACH (file)

        if (self::$procesar_bajas) {
            echo '
			<script language="javascript">
				$("#archivo_2").removeClass("hidden");
			</script>';
            self::ProcesarChequesBajas();
        } else {
            echo '
			<script language="javascript">
				$(function(){
					$("#btn_regreso").removeAttr("style");
				});
			</script>';

        }

        // -------------FUENTES PROCESADAS

        $observaciones = "";
        if ((self::$cantidad_lineas_procesadas > 0) && (self::$cantidad_lineas_procesadas < self::$cantidad_lineas)) {
            $link = (self::$consultar_errores == 1) ? self::$errorlog : self::$log;
            $observaciones = "Se procesó la fuente incompleta, consultar los detalles en el log de errores: " . $link;
            $values = array(self::$fuente_fecha, self::$fuente['fuente_procesada'], $observaciones);
            $res = SQLConnection::backendStoreProcedure("backend_modificar_fuentes_procesadas", $values);
        } elseif (self::$cantidad_lineas_procesadas > 0) {
            if (self::$consultar_errores == 1) {
                $observaciones = "Se procesó la fuente completamente pero el log arrojó errores, consultar los detalles en el log: " . self::$errorlog;
            }
            $values = array(self::$fuente_fecha, self::$fuente['fuente_procesada'], $observaciones);
            $res = SQLConnection::backendStoreProcedure("backend_modificar_fuentes_procesadas", $values);
        }

        // -----------------fin de FUENTES PROCESADAS---------------------------

        if (self::$consultar_errores) {
            Misc::Log("<span style='color:red;'><strong>ATENCION:</strong></span> Consultar log de errores " . self::$errorlog, self::$log, "html");
            $error_information_lines = file(self::$errorlog);
            $error_information_lines = array_map("trim", $error_information_lines);
        } else {
            Misc::Log("<strong>Procesamiento " . strtoupper(self::$fuente_key) . " finalizado.</strong>", self::$log, "html");
            $error_information_lines = false;
        }

        echo view('procesos.error', compact('error_information_lines'))->render();

    }

    // GAFIP
    public static function procesarGafip() {
        // set logs filesnames
        $logbasename = preg_replace("/%timestamp%/", date("Ymd_His"), strtoupper(self::$fuente_key) . "_%timestamp%.html");
        self::$log_url = ENV('RUTA_PROCESOS_LOGS') . DIRECTORY_SEPARATOR . $logbasename;
        self::$log = self::$directorio_log . DIRECTORY_SEPARATOR . $logbasename;
        $errorlogbasename = preg_replace("/%timestamp%/", date("Ymd_His"), strtoupper(self::$fuente_key) . "_errores_%timestamp%.log");
        self::$errorlog = self::$directorio_log . DIRECTORY_SEPARATOR . $errorlogbasename;
        // buscar $archivos

        $log_url = self::$log_url;
        // Cargar la vista con la barra de progreso
        echo view('procesos.progress', compact('log_url'))->render();
        self::$fuentes = Proceso::obtenerFuentes();
        $user_id = Session::get("usuario")->user_id;
        $archivo = file_get_contents($_FILES['archivo']['tmp_name']);
        $datos = json_decode($archivo, TRUE);
        $i = 0;
        $cantidad = count($datos);
        self::$cantidad_lineas_procesadas = 0;
        $errores = 0;
        if (self::validarFechaFuente()) {
            foreach ($datos as $key => $registros) {

                if (!empty($registros['data'])) {

                    $padron = SQLConnection::backendStoreProcedure('afip_padrones', array($registros['cuit'], $registros['data']['nombre_persona'], $registros['data']['estado']), 'selectOne');

                    if (!empty($registros['data']['fecha_inscripcion']) || !empty($registros['data']['fecha_contrato_social'])) {
                        $padron_fechas = SQLConnection::backendStoreProcedure('afip_padron_datos_sociedad', array($registros['cuit'], $registros['data']['fecha_inscripcion'], $registros['data']['fecha_contrato_social'], $user_id), 'selectOne');
                    }

                    if (!empty($registros['data']['impuestos'])) {
                        foreach ($registros['data']['impuestos'] as $key => $imp) {
                            $afip_impuestos = SQLConnection::backendStoreProcedure('afip_impuestos', array($key, $imp), 'selectOne');
                            $padron_impuestos = SQLConnection::backendStoreProcedure('afip_padron_impuestos', array($registros['cuit'], $key, $user_id), 'selectOne');
                        }
                    }

                    if (!empty($registros['data']['caracterizaciones'])) {
                        foreach ($registros['data']['caracterizaciones'] as $key => $carac) {
                            $afip_caracterizaciones = SQLConnection::backendStoreProcedure('afip_caracterizaciones', array($key, $carac), 'selectOne');
                            $padron_caracterizaciones = SQLConnection::backendStoreProcedure('afip_padron_caracterizaciones', array($registros['cuit'], $key, $user_id), 'selectOne');
                        }
                    }

                    if (!empty($registros['data']['actividades'])) {
                        foreach ($registros['data']['actividades'] as $key => $act) {
                            $afip_actividades = SQLConnection::backendStoreProcedure('afip_actividades', array($key, $act), 'selectOne');
                            $padron_actividades = SQLConnection::backendStoreProcedure('afip_padron_actividades', array($registros['cuit'], $key, $user_id), 'selectOne');
                        }
                    }

                    if (!empty($registros['data']['domicilioFiscal'])) {
                        $padron_domicilio = SQLConnection::backendStoreProcedure('afip_padron_domicilios',
                            array($registros['cuit'],
                                $registros['data']['domicilioFiscal']['direccion'],
                                $registros['data']['domicilioFiscal']['localidad'],
                                $registros['data']['domicilioFiscal']['codigo_postal'],
                                $registros['data']['domicilioFiscal']['provincia'],
                                $user_id),
                            'selectOne');
                    }

                    if (!empty($registros['data']['dependencia'])) {
                        $afip_dependencia = SQLConnection::backendStoreProcedure('afip_dependencias',
                            array($registros['data']['dependencia']['id_dependencia'],
                                $registros['data']['dependencia']['descripcion'],
                                $registros['data']['dependencia']['direccion'],
                                $registros['data']['dependencia']['localidad'],
                                $registros['data']['dependencia']['codigo_postal'],
                                $registros['data']['dependencia']['id_provincia'],
                                $registros['data']['dependencia']['provincia'],
                                $registros['data']['dependencia']['latitud'],
                                $registros['data']['dependencia']['longitud']),
                            'selectOne');
                        $padron_dependencia = SQLConnection::backendStoreProcedure('afip_padron_dependencias', array($registros['cuit'], $registros['data']['dependencia']['id_dependencia'], $user_id), 'selectOne');
                    }
                    $procesado_errores = SQLConnection::backendStoreProcedure('afip_procesados_errores', array($registros['cuit'], '1'), 'selectOne');
                    self::$cantidad_lineas_procesadas++;
                } else {
                    $procesado_errores = SQLConnection::backendStoreProcedure('afip_procesados_errores', array($registros['cuit'], '0'), 'selectOne');
                    $errores++;
                }

                $i = $i + 1;
                self::porcentajeBarraProgreso($i, $cantidad);
            }
            echo '
			<script language="javascript">
				$(function(){
						$("#btn_regreso").removeAttr("style");
				});
				$("#information").html("Proceso completado <br>Se procesaron ' . $i . ' registros de ' . $cantidad . '");
			</script>';
        }

        // -------------FUENTES PROCESADAS

        $observaciones = "";
        if (self::$cantidad_lineas_procesadas > 0) {
            if ($errores > 0) {
                $observaciones = "Se procesó la fuente pero se encontraron $errores errores en los registros";
            }
            $values = array(self::$fuente_fecha, 'afip', $observaciones);
            $res = SQLConnection::backendStoreProcedure("backend_modificar_fuentes_procesadas", $values);
        }

        // -----------------fin de FUENTES PROCESADAS---------------------------

        if (self::$consultar_errores) {
            Misc::Log("<span style='color:red;'><strong>ATENCION:</strong></span> Consultar log de errores " . self::$errorlog, self::$log, "html");
            $error_information_lines = file(self::$errorlog);
            $error_information_lines = array_map("trim", $error_information_lines);
        } else {
            Misc::Log("<strong>Procesamiento " . strtoupper(self::$fuente_key) . " finalizado.</strong>", self::$log, "html");
            $error_information_lines = false;
        }

        echo view('procesos.error', compact('error_information_lines'))->render();

    }

    // ------------- METODOS DE PARSEO DE DATOS ---------------------------

    /*** ADUANA ** --------------------------------*/
    private static function parsearLineaAduana($LINE, $nombre_file, $n_linea = null, $params) {

        $LINE = trim($LINE);
        //$valores = explode(self::$separador_campos, $LINE);

        $resultado[0]['cuit'] = trim((string) substr($LINE, 0, 11));
        $resultado[0]['periodo'] = trim((string) substr($LINE, 84, 24));
        $resultado[0]['consumo'] = trim(str_replace(',', '.', (string) substr($LINE, 11, 18)));
        $resultado[0]['temporal'] = trim(str_replace(',', '.', (string) substr($LINE, 30, 18)));
        $resultado[0]['deposito'] = trim(str_replace(',', '.', (string) substr($LINE, 48, 18)));
        $resultado[0]['zona_franca'] = trim(str_replace(',', '.', (string) substr($LINE, 66, 18)));
        $resultado[0]['nombre_file'] = $nombre_file;

        return $resultado;
    }

    private static function parsearLineaCYQBT($LINE, $nombre_file, $n_linea = null, $sindico, $demandado, $cuit_demandado) {
        //dd($LINE);
        $LINE = trim($LINE);
        $valores = explode("|", $LINE);
        $valores[24] = str_replace(array('.', ','), array('', ''), $sindico);
        $valores[25] = str_replace(array('.', ','), array('', ''), $demandado);
        $valores[26] = $cuit_demandado;
        $valores[14] = str_replace(array('.', ','), array('', ''), $valores[14]);
        $contenidos_texto = $_FILES['archivos_textos_bt']['name'];
        //dd($contenidos_texto);
        $nombre_archivo_a_procesar = $_FILES['archivo']['name'];
        $ruta_archivo = self::$archivos_src_dir . '/cyq_bt/' . $nombre_archivo_a_procesar;
        $valores[21] = $ruta_archivo;
        $num_registro = $valores[0];
        $tipo_parte_registro = $valores[13];
        //recorro el contenido del texto de cada uno de, ej, 'A8000003.txt'
        foreach ($contenidos_texto as $key => $value) {
            //Limpio texto
            $value = str_ireplace(".txt", "", $value);
            $contenido_texto[$value] = file_get_contents(self::$archivos_src_dir . '/cyq_bt/_textos/' . $value . ".txt", true);
            $contenido_texto = array_map('trim', $contenido_texto);
            //agrego el contenido del texto que corresponda con su nro_archivo
            $numero_texto = str_ireplace(".TXT", "", $valores[19]);

            if ($numero_texto == $value) {
                $valores[20] = trim($contenido_texto[$value]);
                /*
                            $palabra_encontrada = Misc::busquedaPalabrasCyQbT($valores[19]);
                            if ($palabra_encontrada == 'CONCURSO') {
                                    $proceso = 'NOVEDAD CONCURSO PREVENTIVO';
                                    $tipo_de_proceso = '22';
                            }elseif ($palabra_encontrada == 'QUIEBRA') {
                                    $proceso = 'DECRETO DE QUIEBRA';
                                    $tipo_de_proceso = '60';
                            }else{
                                    $proceso = 'NODATA';
                                    $tipo_de_proceso = 'ND';
                            }
                            */
            }
        }
        switch ($valores[17]) {
            //"proceso" y "tipo_de_proceso", equivalencias usadas para BCO FRANCES
            //"N-S" = No hay dato concreto
            //$valores[17] = campo : proceso en juicios2
            case 'APERTURA DE CONCURSO':
                if ($valores[13] == 'SINDICO' || $valores[13] == 'SÍNDICO') {
                    $valores[17] = 'NOVEDAD CONCURSO PREVENTIVO';
                    $valores[23] = '22';
                } else {
                    $valores[17] = 'APERTURA CONCURSO PREVENTIVO'; // "proceso" en juicios2
                    $valores[23] = '20'; 													 // tipo_de_proceso (equivalencias p/ bco. frances)
                }
                $valores[22] = 'CRC'; 												 // "id_tipo_causa" en juicios2
                break;
            case 'PRESENTACIÓN DE PROYECTO DE DISTRIBUCIÓN FINAL':
            case 'PRESENTACION DE PROYECTO DE DISTRIBUCION FINAL':
                $valores[17] = 'NOVEDAD DECRETO DE QUIEBRA';
                $valores[22] = 'DF';
                $valores[23] = '62';
                break;
            case 'DECLARACIÓN DE QUIEBRA':
            case 'DECLARACION DE QUIEBRA':
                //tipo_de_parte SINDICO
                if ($valores[2] == 'QUIEBRA' && ($valores[13] == 'SÍNDICO' || $valores[13] == 'SINDICO')) {
                    $valores[17] = 'NOVEDAD DECRETO DE QUIEBRA';
                    $valores[22] = 'QDC';
                    $valores[23] = '62';
                    break;
                }

                if ($valores[2] == 'CONCURSO' && ($valores[13] == 'SÍNDICO' || $valores[13] == 'SINDICO')) {
                    $valores[17] = 'NOVEDAD CONCURSO PREVENTIVO';
                    $valores[22] = 'NCP';
                    $valores[23] = '60';
                    break;
                }

                if ($valores[2] == 'QUIEBRA' && ($valores[13] != 'SÍNDICO' || $valores[13] != 'SINDICO')) {
                    $valores[17] = 'DECRETO DE QUIEBRA';
                    $valores[22] = 'QDC';
                    $valores[23] = '60';
                    break;
                }

                if ($valores[2] == 'CONCURSO' && ($valores[13] != 'SÍNDICO' || $valores[13] != 'SINDICO')) {
                    $valores[17] = 'DECRETO DE QUIEBRA';
                    $valores[22] = 'QDC';
                    $valores[23] = '60';
                    break;
                }
                break;

            case 'VARIOS':
                if ($valores[2] == 'QUIEBRA') {
                    $valores[17] = 'NOVEDAD DECRETO DE QUIEBRA';
                    $valores[22] = 'QUI';
                    $valores[23] = '62';
                } elseif ($valores[2] == 'CONCURSO') {
                    $valores[17] = 'NOVEDAD CONCURSO PREVENTIVO';
                    $valores[22] = 'NCP';
                    $valores[23] = '22';
                }
                break;
            case 'PRESENTACIÓN DE INFORMES':
            case 'PRESENTACION DE INFORMES':
                if ($valores[2] == 'QUIEBRA') {
                    $valores[17] = 'NOVEDAD DECRETO DE QUIEBRA';
                    $valores[22] = 'QUI';
                    $valores[23] = '62';
                } elseif ($valores[2] == 'CONCURSO') {
                    $valores[17] = 'NOVEDAD CONCURSO PREVENTIVO';
                    $valores[22] = 'NCP';
                    $valores[23] = '22';
                }
                break;
            case 'FINALIZACIÓN DE CONCURSO':
            case 'FINALIZACION DE CONCURSO':
                $valores[17] = 'NOVEDAD CONCURSO PREVENTIVO';
                $valores[22] = 'CC2';
                $valores[23] = '22';
                break;
            case 'LIQUIDACIÓN DE BIENES':
            case 'LIQUIDACION DE BIENES':
                if ($valores[2] == 'QUIEBRA') {
                    $valores[17] = 'NOVEDAD DECRETO DE QUIEBRA';
                    $valores[22] = 'QUI';
                    $valores[23] = '62';
                } elseif ($valores[2] == 'CONCURSO') {
                    $valores[17] = 'NOVEDAD CONCURSO PREVENTIVO';
                    $valores[22] = 'NCP';
                    $valores[23] = '22';
                }
                break;
            case 'SINDICO':
            case 'SÍNDICO':
                if ($valores[3] == 'QUIEBRA') {
                    $valores[17] = 'NOVEDAD DECRETO DE QUIEBRA';
                    $valores[21] = 'DS';
                    $valores[22] = '62';
                } else {
                    $valores[17] = 'NOVEDAD CONCURSO PREVENTIVO';
                    $valores[21] = 'DS';
                    $valores[22] = '22';
                }
                break;
            case 'INCIDENCIA':
                if ($valores[2] == 'QUIEBRA') {
                    $valores[17] = 'NOVEDAD DECRETO DE QUIEBRA';
                    $valores[22] = 'QUI';
                    $valores[23] = '62';
                } elseif ($valores[2] == 'CONCURSO') {
                    $valores[17] = 'NOVEDAD CONCURSO PREVENTIVO';
                    $valores[22] = 'NCP';
                    $valores[23] = '22';
                }
                break;
            case 'FINALIZACIÓN DE QUIEBRA':
            case 'FINALIZACION DE QUIEBRA':
                $valores[17] = 'DECRETO DE QUIEBRA'; //PROCESO
                $valores[21] = 'QDC'; //id_tipo_causa
                $valores[22] = '60';//TIPO_PROCESO  
                break;

            default:
                break;
        }

        //Parseo de fechas resultado = YY-MM-DD
        $array_fechas[] = '';
        $array_fechas[0] = $valores[1];  //fecha_publicacion
        $fecha_fuente = str_replace('-', '', self::$fuente_fecha);
        $array_fechas[1] = $valores[9] ? $valores[9] : $fecha_fuente;  //fecha_decreto
        $array_fechas[2] = $valores[10]; //fecha_verificacion
        $array_fechas[3] = $valores[11]; //fecha_individual
        $array_fechas[4] = $valores[12]; //fecha_inf_gral
        $array_fechas[5] = $valores[18]; //fecha_presentación
        $fechas_formateadas = Misc::formatFecha($array_fechas);
        $valores[1] = $fechas_formateadas[0];
        $valores[9] = $fechas_formateadas[1];
        $valores[10] = $fechas_formateadas[2];
        $valores[11] = $fechas_formateadas[3];
        $valores[18] = $fechas_formateadas[5];
        //Limpio de guiones el campo 'documento'
        if ($valores[15] != '') {
            str_replace("-", "", $valores[15]);
            $valores[15] = str_replace(array('-', ' ', '/'), array('', '', ''), $valores[15]);
            $size_valores = strlen($valores[15]);
            if ($size_valores < 11) {
                $cuit_completo = '';
                $nombre_parse = self::parsearBusquedaPadron($valores[14]);
                $cuit_completo = SQLConnection::buscarCuitFuenteCyQBt($valores[14], $valores[15], $nombre_parse);
                $valores[15] = $cuit_completo->cuit;
            }
        }
        //Limpio de guiones el campo 'cuit_demandado'
        if ($valores[26] != '') {
            $valores[26] = str_replace(array('-', ' '), array('', ''), $valores[26]);
            $size_valores = strlen($valores[26]);

            if ($size_valores < 11) {
                //store se le pasa: nombre , documento y nombre_parseado
                $cuit_completo = '';
                $nombre_parse = self::parsearBusquedaPadron($valores[14]);
                $cuit_completo = SQLConnection::buscarCuitFuenteCyQBt($valores[25], $valores[26], $nombre_parse);
                $valores[26] = $cuit_completo->cuit;
            }
        }
        //id_boletin - contenido_archivo (primer registro ingresa "?" antes del numero), contenido de archivo 
        $valores[0] = str_ireplace('?', '', $valores[0]);
        $valores[19] = str_ireplace('"', '', $valores[19]);
        $valores[8] = str_ireplace('"', '', $valores[8]);

        $resultado[0]['id_boletin'] = (isset($valores[0]) && ($valores[0] != '')) ? $valores[0] : NULL;
        $resultado[0]['fecha_publicacion'] = (isset($valores[1]) && ($valores[1] != '')) ? $valores[1] : NULL;
        $resultado[0]['tipo_de_publicacion'] = (isset($valores[2]) && ($valores[2] != '')) ? $valores[2] : NULL;
        $resultado[0]['localidad_juzgado'] = (isset($valores[3]) && ($valores[3] != '')) ? $valores[3] : NULL;
        $resultado[0]['tipo_de_juzgado'] = (isset($valores[4]) && ($valores[4] != '')) ? $valores[4] : NULL;
        $resultado[0]['nro_juzgado'] = (isset($valores[5]) && ($valores[5] != '')) ? $valores[5] : NULL;
        $resultado[0]['nro_secretaria'] = (isset($valores[6]) && ($valores[6] != '')) ? $valores[6] : NULL;
        $resultado[0]['nro_expediente'] = (isset($valores[7]) && ($valores[7] != '')) ? $valores[7] : NULL;
        $resultado[0]['autos'] = (isset($valores[8]) && ($valores[8] != '')) ? $valores[8] : NULL;
        $resultado[0]['fecha_decreto'] = (isset($valores[9]) && ($valores[9] != '')) ? $valores[9] : NULL;
        $resultado[0]['fecha_verificacion'] = (isset($valores[10]) && ($valores[10] != '')) ? $valores[10] : NULL;
        $resultado[0]['fecha_individual'] = (isset($valores[11]) && ($valores[11] != '')) ? $valores[11] : NULL;
        $resultado[0]['fecha_inf_gral'] = (isset($valores[12]) && ($valores[12] != '')) ? $valores[12] : NULL;
        $resultado[0]['tipo_entidad'] = (isset($valores[13]) && ($valores[13] != '')) ? $valores[13] : NULL; //@p_tipo_de_parte en STORE
        $resultado[0]['nombre'] = (isset($valores[14]) && ($valores[14] != '')) ? $valores[14] : NULL;
        $resultado[0]['documento'] = (isset($valores[15]) && ($valores[15] != '')) ? $valores[15] : NULL;
        $resultado[0]['provincia'] = (isset($valores[16]) && ($valores[16] != '')) ? $valores[16] : NULL;
        $resultado[0]['novedad'] = (isset($valores[17]) && ($valores[17] != '')) ? $valores[17] : NULL; //@p_proceso en STORE 
        //cambiado para que tome la nueva fecha
        $resultado[0]['fecha_presentacion'] = (isset($valores[18]) && ($valores[18] != '')) ? $valores[18] : NULL;
        $resultado[0]['nombre_file'] = (isset($valores[19]) && ($valores[19] != '')) ? $valores[19] : NULL;
        $resultado[0]['contenido_archivo'] = (isset($valores[20]) && ($valores[20] != '')) ? $valores[20] : NULL;
        $resultado[0]['ruta_archivo'] = (isset($valores[21]) && ($valores[21] != '')) ? $valores[21] : NULL;
        $resultado[0]['id_tipo_causa'] = (isset($valores[22]) && ($valores[22] != '')) ? $valores[22] : NULL;
        $resultado[0]['tipo_de_proceso'] = (isset($valores[23]) && ($valores[23] != '')) ? $valores[23] : NULL;
        $resultado[0]['sindico'] = (isset($valores[24]) && ($valores[24] != '')) ? $valores[24] : NULL;
        $resultado[0]['demandado'] = (isset($valores[25]) && ($valores[25] != '')) ? $valores[25] : NULL;
        $resultado[0]['cuit_demandado'] = (isset($valores[26]) && ($valores[26] != '')) ? $valores[26] : NULL;
        return $resultado;
    }

    private static function parsearLineaAduanaImpo($LINE, $nombre_file, $n_linea = null, $params) {

        $LINE = trim($LINE);
        $valores = explode(self::$separador_campos, $LINE);

        $resultado[0]['cuit'] = (string) $valores[0];
        $resultado[0]['procedencia'] = (string) $valores[1];
        $resultado[0]['fobusd'] = (string) str_replace(',', '.', $valores[2]);
        $resultado[0]['posicion'] = (string) $valores[3];
        $fecha_expo = explode('/', $valores[4]);
        $dt = new DateTime();

        $dt->setDate($fecha_expo[2], $fecha_expo[1], $fecha_expo[0]); // returns DateTime object and not false although this date does not exist
        $resultado[0]['fecofi'] = $dt->format('Y-m-d'); // output: 2012-12-01

        /*dd($resultado);*/

        return $resultado;

    }

    private static function parsearLineaAduanaExpo($LINE, $nombre_file, $n_linea = null, $params) {

        $LINE = trim($LINE);
        $valores = explode(self::$separador_campos, $LINE);

        $resultado[0]['cuit'] = $valores[0];
        $resultado[0]['procedencia'] = $valores[1];
        $resultado[0]['fobusd'] = (string) str_replace(',', '.', $valores[2]);
        $resultado[0]['posicion'] = (string) $valores[3];
        $fecha_expo = explode('/', $valores[4]);
        $dt = new DateTime();

        $dt->setDate($fecha_expo[2], $fecha_expo[1], $fecha_expo[0]); // returns DateTime object and not false although this date does not exist
        $resultado[0]['fecofi'] = $dt->format('Y-m-d'); // output: 2012-12-01


        return $resultado;

    }



    /*** ARBA ** --------------------------------*/
    private static function parsearLineaArba($LINE, $nombre_file, $n_linea = null, $params = []) {
        $LINE = trim($LINE);
        $LINE = str_replace("‹", "Ñ", $LINE);
        $LINE = str_replace("¬", "Ñ", $LINE);
        $LINE = str_replace("#", "Ñ", $LINE);

        $values_arr = [];
        $lineArr = [];

        $lineArr[0] = trim(mb_substr($LINE, 0, 1, "UTF-8"));     //#0	tipo_movimiento Tipo Movimiento
        $lineArr[1] = trim(mb_substr($LINE, 1, 1, "UTF-8"));     //#1	motivo_baja Motivo Baja
        $lineArr[2] = trim(mb_substr($LINE, 2, 10, "UTF-8"));    //#2	nro_identificacion_arba Nro Identificación Arba
        $lineArr[3] = trim(mb_substr($LINE, 12, 80, "UTF-8"));   //#3	razon_social Razón Social
        $lineArr[4] = trim(mb_substr($LINE, 92, 11, "UTF-8"));   //#4	numero_cuit Número Cuit
        $lineArr[5] = trim(mb_substr($LINE, 103, 1, "UTF-8"));   //#5	tipo_documento Tipo Documento
        $lineArr[6] = trim(mb_substr($LINE, 104, 8, "UTF-8"));   //#6	numero_documento Número Documento
        $lineArr[7] = trim(mb_substr($LINE, 112, 2, "UTF-8"));   //#7	impuesto Impuesto
        $lineArr[8] = trim(mb_substr($LINE, 114, 16, "UTF-8"));  //#8	objeto Objeto
        $lineArr[9] = trim(mb_substr($LINE, 130, 10, "UTF-8"));   //#9	numero_interno_de_juicio Número Interno de Juicio
        $lineArr[10] = trim(mb_substr($LINE, 140, 8, "UTF-8"));   //#10	fecha_de_inicio_de_juicio Fecha de Inicio de Juicio
        $lineArr[11] = trim(mb_substr($LINE, 148, 15, "UTF-8"));  //#11	importe_deuda_del_juicio Importe Deuda del Juicio-Objeto
        $lineArr[12] = trim(mb_substr($LINE, 163, 2, "UTF-8"));   //#12	departamento_judicial Departamento Judicial
        $lineArr[13] = trim(mb_substr($LINE, 165, 2, "UTF-8"));   //#13	numero_de_juzgado Número de Juzgado
        $lineArr[14] = trim(mb_substr($LINE, 167, 2, "UTF-8"));   //#14	secretaria Secretaria
        $lineArr[15] = trim(mb_substr($LINE, 169, 35, "UTF-8"));  //#15	domicilio_calle Domicilio-Calle
        $lineArr[16] = trim(mb_substr($LINE, 204, 6, "UTF-8"));   //#16	domicilio_numero Domicilio-Número
        $lineArr[17] = trim(mb_substr($LINE, 210, 3, "UTF-8"));   //#17	domicilio_sin_numero Domicilio-Sin Número
        $lineArr[18] = trim(mb_substr($LINE, 213, 3, "UTF-8"));   //#18	domicilio_piso Domicilio-Piso
        $lineArr[19] = trim(mb_substr($LINE, 216, 4, "UTF-8"));   //#19	domicilio_departamento Domicilio-Departamento
        $lineArr[20] = trim(mb_substr($LINE, 220, 35, "UTF-8"));  //#20	domicilio_localidad Domicilio-Localidad
        $lineArr[21] = trim(mb_substr($LINE, 255, 8, "UTF-8"));   //#21	domicilio_codigo_postal Domicilio-Código-Postal
        $lineArr[22] = trim(mb_substr($LINE, 263, 1, "UTF-8"));   //#22	estado_de_medida_cautelar Estado de Medida Cautelar
        $lineArr[23] = trim(mb_substr($LINE, 264, 1, "UTF-8"));   //#23	estado_de_plan_de_pagos Estado de Plan de Pagos
        $lineArr[24] = trim(mb_substr($LINE, 265, 8, "UTF-8"));   //#24	fecha_de_plan_de_pagos Fecha de Plan de Pagos
        $lineArr[25] = trim(mb_substr($LINE, 273, 1, "UTF-8"));   //#25	cancelacion_del_juicio Cancelación del Juicio

        $lineArr[26] = trim(mb_substr($LINE, 274, 8, "UTF-8"));   //#26	fecha_de_cancelacion Fecha de Cancelación
        $lineArr[27] = trim(mb_substr($LINE, 282, 10, "UTF-8"));   //#27	fecha_de_proceso_arba Fecha de Proceso

        //#11 -> ultimos dos digitos decimales
        $lineArr[11] = preg_replace("/0*(\d+)(\d\d)/u", "$1.$2", $lineArr[11]);

        //#[10-24-26] -> date or NULL
        $regex_date = "/(\d{4})(\d{2})(\d{2})/u"; // yyyymmdd
        $fields = [10, 24, 26];
        foreach ($fields as $k) { //foreach array index
            $res = preg_match($regex_date, $lineArr[$k]);
            if ($res === 0 or $res === FALSE or $lineArr[$k] == "00000000")
                $lineArr[$k] = null;
            else
                $lineArr[$k] = preg_replace($regex_date, "$1-$2-$3", $lineArr[$k]); //fecha
        }

        //#[27] -> smalldatetime or NULL
        $k = 27;
        $regex_date = "/(\d{4})(\d{2})(\d{2})(\d{2})/u"; // yyyymmdd
        $res = preg_match($regex_date, $lineArr[$k]);
        if ($res === 0 or $res === FALSE or $lineArr[$k] == "0000000000")
            $lineArr[$k] = null; //NULL
        else
            $lineArr[$k] = preg_replace($regex_date, "$1-$2-$3 $4:00:00", $lineArr[$k]); //fecha

        //END parsing

        /* Agrego campo filename con path relativo */
        $lineArr[] = $nombre_file;
        $values_arr = array($lineArr);
        return $values_arr;
    }

    /*** CHEQUES ** --------------------------------*/
    private static function parsearLineaCheques($LINE, $nombre_file, $n_linea = null, $params = []) {

        $LINE = trim($LINE);
        $values_arr = [];
        $lineArr = [];

        $lineArr[0] = trim(mb_substr($LINE, 0, 11, "UTF-8"));  //#0 cuit_firmante
        $lineArr[1] = trim(mb_substr($LINE, 11, 10, "UTF-8")); //#1 nro_cheque
        $lineArr[2] = trim(mb_substr($LINE, 21, 8, "UTF-8"));  //#2 fecha_rechazo
        $lineArr[3] = trim(mb_substr($LINE, 29, 15, "UTF-8")); //#3 importe
        $lineArr[4] = trim(mb_substr($LINE, 44, 1, "UTF-8"));  //#4 id_causa
        $lineArr[5] = trim(mb_substr($LINE, 45, 8, "UTF-8"));  //#5 fecha_levantamiento
        //$lineArr[6] = trim(mb_substr($LINE,53,1,"UTF-8"));  //#6 art16
        //$lineArr[7] = trim(mb_substr($LINE,54,1,"UTF-8"));  //#7 art38
        $lineArr[6] = trim(mb_substr($LINE, 55, 11, "UTF-8")); //#8 Cuit_relacionado
        $lineArr[7] = trim(mb_substr($LINE, 66, 15, "UTF-8")); //#9 fecha_pago

        //comilla a doble comilla
        foreach ($lineArr as $k => $v) {
            $v = preg_replace("/'/u", "''", trim($v));
            //$v = iconv('windows-1252', 'utf-8', $v);
            $lineArr[$k] = $v;
        }

        //#3 -> importe: ultimos dos digitos decimales
        $lineArr[3] = preg_replace("/(\d+)(\d\d)/u", "$1.$2", $lineArr[3]);

        //#2, #5, #9 -> check dates
        $regex_date_1 = "/(\d{4})(\d{2})(\d{2})/u"; // yyyymmdd
        $regex_date_2 = "/(\d{2})\/(\d{2})\/(\d{4})/u"; // dd/mm/yyyy

        //#2 date or NULL
        $res = preg_match($regex_date_1, $lineArr[2]);
        if ($res === 0 or $res === FALSE)
            $lineArr[2] = null;
        else
            $lineArr[2] = preg_replace($regex_date_1, "$1-$2-$3", $lineArr[2]); //fecha

        //#5 date or NULL
        $res = preg_match($regex_date_1, $lineArr[5]);
        if ($res === 0 or $res === FALSE)
            $lineArr[5] = null;
        else
            $lineArr[5] = preg_replace($regex_date_1, "$1-$2-$3", $lineArr[5]); //fecha

        //#9 date or NULL (or string IMPAGO SUSPENDIDO)
        $res = preg_match($regex_date_2, $lineArr[7]);
        if ($res === 0 or $res === FALSE)
            $lineArr[7] = null; //"'".$lineArr[9]."'";
        //$lineArr[7] = "'".$lineArr[9]."'";
        else
            $lineArr[7] = preg_replace($regex_date_2, "$3-$2-$1", $lineArr[7]); //fecha

        //END parsing

        /* Agrego campo filename con path relativo */
        $lineArr[] = $nombre_file;

        $values_arr = array($lineArr);

        return $values_arr;
    }

    private static function ProcesarChequesBajas() {

        Misc::Log("<strong>Procesando bajas.</strong>", self::$log, "html");
        // get archivo bajas
        $dir_src_bajas = self::$archivos_src_dir . DIRECTORY_SEPARATOR . self::$fuente['folder_bajas'];
        $dir_des_bajas = self::$archivos_des_dir . DIRECTORY_SEPARATOR . self::$fuente['folder_bajas'];
        $archivobajas = $dir_src_bajas . DIRECTORY_SEPARATOR . basename($_FILES["bajas"]["name"]);
        $archivobajas_dest = $dir_des_bajas . DIRECTORY_SEPARATOR . basename($_FILES["bajas"]["name"]);
        $res = move_uploaded_file($_FILES["bajas"]["tmp_name"], $archivobajas);

        if (!$res) {
            Misc::Log("No se pudo subir el archivo " . $_FILES["bajas"]["name"] . ". $res", self::$errorlog);
            self::$consultar_errores = 1;
            return false;
        }

        // procesar archivo
        $file = fopen($archivobajas, "r");
        $nros_cheques = [];
        $i = 0;

        if ($file) {
            $array_of_lines = file($archivobajas);
            // cantidad de lineas a procesar para mostrar en barra de progreso
            $cantidad = count($array_of_lines);

            while (($line = fgets($file)) !== FALSE) {
                if (count($nros_cheques) >= 1000) { // WHERE ... IN (!!!MAX 1000!!!)
                    // mando de a 1000 porque de a 1 tarda mucho mas
                    $procesar[0] = implode(',', $nros_cheques);
                    self::ejecutarStoreProcedure('CHEQUES_update_bajas_exec', $archivobajas, $i + 1, $procesar);
                    $nros_cheques = [];
                }
                $nros_cheques[] = trim($line);
                $i++;
                self::porcentajeBarraProgreso($i, $cantidad, '_archivo_2');
            }
            // ultimos
            if (count($nros_cheques) >= 0) {
                $procesar[0] = implode(',', $nros_cheques);
                self::ejecutarStoreProcedure('CHEQUES_update_bajas_exec', $archivobajas, $i + 1, $procesar);
                self::porcentajeBarraProgreso($i, $cantidad, "_archivo_2");
            }
            Misc::Log("$i bajas actualizadas.", self::$log);
            fclose($file);

            echo '
			<script language="javascript">
				$(function(){
					$("#btn_regreso").removeAttr("style");
				});
			</script>';

            //muevo file
            $res = Misc::moverArchivo($archivobajas, $archivobajas_dest);
            if ($res == 1) {
                Misc::Log("Muevo $archivobajas a $archivobajas_dest.", self::$log);
            } else {
                Misc::Log("No se pudo mover el file $archivobajas a $archivobajas_dest: $res", self::$errorlog);
                self::$consultar_errores = 1;
            }

        } else {
            Misc::Log("No se pudo abrir el archivo de bajas " . $archivobajas, self::$errorlog);
            self::$consultar_errores = 1;
        }
    }

    /*** DEFUNCIONES - COMENTADO TEMPORALMENTE PORQUE NO SERA IMPLEMENTADO AUN***/
    /*
       private function parsearLineaDefunciones($LINE, $nombre_file, $n_linea, $params = []) {
           // print_r($LINE);die();
           $LINE = trim($LINE);
           $values_arr = [];
           $lineArr = [];
           $lineArr = explode(self::$separador_campos,$LINE);
           $n_campos = count($lineArr);

           if ($n_campos!=5) {
               //Numero de campos equivocado
               Misc::Log("Error en los numeros de campos (".$n_campos."), linea:".$n_linea.", file: ".$nombre_file , self::$errorlog);
               return 0;
           } 

           // parse cada campo
           foreach ($lineArr as $k => $v) {

               //$v = iconv('windows-1252', 'utf-8', $v);
               //escape quote
               $v = trim($v);
               $v = str_replace("'", "''", $v);
               
               // campos fecha #0, #3 
               if ( in_array($k, [5,29,30,31,34,36,38]) ) {
                   $reg = "/(\d\d?)\/(\d\d?)\/(\d{4})/u";
                   $res = preg_match($reg, $v);
                   if ($res===0 or $res===FALSE or $v=="00000000" or $v=="//") 
                       $v = "";
                   else 
                       $v = preg_replace($reg, "$3-$2-$1", $v);
               }
               //actualizo valor
               $lineArr[$k] = $v;
           } //end foreach lineArr

           //END parsing

           // Agrego campo filename con path relativo
           $lineArr[] = $nombre_file;
           $values_arr = array($lineArr);
           return $values_arr;
       }*/

    /* ** INSCRIPCIONES ** --------------------------------*/
    private static function parsearLineaInscripciones($LINE, $nombre_file, $n_linea = null, $params = []) {

        $LINE = trim($LINE);
        $values_arr = [];
        $lineArr = [];
        $lineArr[0] = trim(mb_substr($LINE, 0, 11, "UTF-8"));  //cuit
        $lineArr[1] = trim(mb_substr($LINE, 11, 30, "UTF-8")); //denominacion
        $lineArr[2] = trim(mb_substr($LINE, 41, 2, "UTF-8"));  //imp_ganancias
        $lineArr[3] = trim(mb_substr($LINE, 43, 2, "UTF-8"));  //imp_iva
        $lineArr[4] = trim(mb_substr($LINE, 45, 2, "UTF-8"));  //monotributo
        $lineArr[5] = trim(mb_substr($LINE, 47, 1, "UTF-8"));  //integrante_soc
        $lineArr[6] = trim(mb_substr($LINE, 48, 1, "UTF-8"));  //empleador
        $lineArr[7] = trim(mb_substr($LINE, 49, 2, "UTF-8"));  //actividad_monotributo

        //trim y comilla a doble comilla
        foreach ($lineArr as $k => $v) {
            $v = preg_replace("/'/u", "''", trim($v));
            //$v = iconv('windows-1252', 'utf-8', $v);
            $lineArr[$k] = $v;
        }

        /* Agrego campo country_code='AR' */
        $lineArr[] = 'AR';

        /* Agrego campo filename con path relativo */
        $lineArr[] = $nombre_file;
        $values_arr = array($lineArr);

        return $values_arr;
    }

    /*** JUICIOS BT ** --------------------------------*/
    private static function parsearLineaJuiciosBt($LINE, $nombre_file, $n_linea, $params = []) {

        $LINE = trim($LINE);
        $LINE = rtrim(trim($LINE), self::$separador_campos);
        $values_arr = [];
        $lineArr = [];
        $lineArr = explode(self::$separador_campos, $LINE);
        $cabeceras = self::$juicios_csv_fields_arr;
        $parseado = [];
        // parse cada campo
        foreach ($lineArr as $k => $v) {
            //escape quote
            $v = trim($v);
            $v = str_replace("'", "''", $v);
            if ($v == "") {
                $v = NULL;
            }

            if ((strtolower($cabeceras[$k]) == "provincia") || (strtolower($cabeceras[$k]) == 'juridic')) {
                $parseado['provincia'] = $v;
            } elseif ((strtolower($cabeceras[$k]) == "fecha") || (strtolower($cabeceras[$k]) == 'f_inicio')) {
                $datetime = DateTime::createFromFormat('d/m/Y', $v);
                if (!$datetime) {
                    $datetime = DateTime::createFromFormat('Y-m-d', $v);
                }
                $datetime->setTime(0, 0, 0);
                $parseado['fecha_causa'] = $datetime->format('Y-m-d H:i:s');
            } elseif (strtolower($cabeceras[$k]) == "juzgado") {
                $parseado['juzgado'] = $v;
            } elseif (strtolower($cabeceras[$k]) == "actor") {
                $parseado['actor'] = $v;
            } elseif ((strtolower($cabeceras[$k]) == "demandado") || (strtolower($cabeceras[$k]) == 'causante')) {
                $parseado['demandado'] = $v;
            } elseif ((strtolower($cabeceras[$k]) == "expediente") || (strtolower($cabeceras[$k]) == 'expdte')) {
                $parseado['expediente'] = $v;
            } elseif ((strtolower($cabeceras[$k]) == "objeto") || (strtolower($cabeceras[$k]) == 'causa')) {
                $parseado['causa'] = $v;
            } elseif (strtolower($cabeceras[$k]) == "texto") {
                $parseado['texto'] = $v;
            } elseif (strtolower($cabeceras[$k]) == "foja") {
                $parseado['foja'] = $v;
            } elseif (strtolower($cabeceras[$k]) == "orden") {
                $parseado['orden'] = $v;
            } elseif (strtolower($cabeceras[$k]) == "decreto") {
                $parseado['decreto'] = $v;
            } elseif (strtolower($cabeceras[$k]) == "abogado") {
                $parseado['abogado'] = $v;
            } elseif (strtolower($cabeceras[$k]) == "caratula") {
                $parseado['caratula'] = $v;
            } elseif (strtolower($cabeceras[$k]) == "secretaria") {
                $parseado['secretaria'] = $v;
            } elseif (strtolower($cabeceras[$k]) == "tipodoc_a") {
                $parseado['tipo_doc_actor'] = $v;
            } elseif (strtolower($cabeceras[$k]) == "nrodoc_a") {
                $parseado['nro_doc_actor'] = $v;
            } elseif (strtolower($cabeceras[$k]) == "tipodoc_d") {
                $parseado['tipo_doc_demandado'] = $v;
            } elseif (strtolower($cabeceras[$k]) == "nrodoc_d") {
                $parseado['nro_doc_demandado'] = $v;
            } elseif (strtolower($cabeceras[$k]) == "novedad") {
                $parseado['novedad'] = $v;
            }
        } // end foreach

        $res = [];
        $res[0] = (isset($parseado['expediente'])) ? $parseado['expediente'] : NULL;
        $res[1] = (isset($parseado['caratula'])) ? $parseado['caratula'] : NULL;
        $res[2] = (isset($parseado['causa'])) ? $parseado['causa'] : NULL;
        $res[3] = (isset($parseado['fecha_causa'])) ? $parseado['fecha_causa'] : NULL;
        $res[4] = (isset($parseado['actor'])) ? $parseado['actor'] : NULL;
        $res[5] = (isset($parseado['tipo_doc_actor'])) ? $parseado['tipo_doc_actor'] : NULL;
        $res[6] = (isset($parseado['nro_doc_actor'])) ? $parseado['nro_doc_actor'] : NULL;
        $res[7] = (isset($parseado['demandado'])) ? $parseado['demandado'] : NULL;
        $res[8] = (isset($parseado['tipo_doc_demandado'])) ? $parseado['tipo_doc_demandado'] : NULL;
        $res[9] = (isset($parseado['nro_doc_demandado'])) ? $parseado['nro_doc_demandado'] : NULL;
        $res[10] = (isset($parseado['provincia'])) ? $parseado['provincia'] : self::$juicios_bt;
        $res[11] = (isset($parseado['juzgado'])) ? $parseado['juzgado'] : NULL;
        $res[12] = (isset($parseado['abogado'])) ? $parseado['abogado'] : NULL;
        $res[13] = (isset($parseado['secretaria'])) ? $parseado['secretaria'] : NULL;
        $res[14] = (isset($parseado['novedad'])) ? $parseado['novedad'] : NULL;
        $res[15] = (isset($parseado['foja'])) ? $parseado['foja'] : NULL;
        $res[16] = (isset($parseado['orden'])) ? $parseado['orden'] : NULL;
        $res[17] = (isset($parseado['decreto'])) ? $parseado['decreto'] : NULL;
        $res[18] = (isset($parseado['texto'])) ? $parseado['texto'] : NULL;
        /* Agrego campo filename con path relativo */
        $res[] = $nombre_file;

        $values_arr = array($res);
        return $values_arr;
    }

    /*** JUICIOS MYF ***/
    private static function parsearLineaJuiciosMYF($LINE, $nombre_file, $n_linea, $params = []) {
        $LINE = trim($LINE);
        $values_arr = [];
        $lineArr = [];
        $lineArr = explode(self::$separador_campos, $LINE);
        $n_campos = count($lineArr);

        if ($n_campos == 26) {
            /* Agrego campos vacios en las ss. posiciones 
                         (empiezo desde el fondo para no alterar las claves sucesivas) */
            //#12 agrego 6 campos varchar vacios 
            array_splice($lineArr, 12, 0, array_fill(0, 6, ""));
            //#10 agrego 6 campos varchar vacios
            array_splice($lineArr, 10, 0, array_fill(0, 6, ""));
            //#7 agrego 2 campos varchar vacios
            array_splice($lineArr, 7, 0, array_fill(0, 2, ""));
        } elseif ($n_campos != 41) {
            //Numero de campos equivocado
            Misc::Log("[" . $nombre_file . ":" . $n_linea . "] Error numero de campos: " . $n_campos . " (esperados: 41)", self::$errorlog);
            self::$consultar_errores = 1;
            return 0;
        }
        // parse cada campo
        foreach ($lineArr as $k => $v) {
            //escape quote
            $v = trim($v);
            $v = str_replace("'", "''", $v);

            // campos fecha #5, #29, #30, #31, #34, #36, #38 
            // 22/8 campos fecha: #5,#29,#30,#31,#32,#35,#37,#39

            if (in_array($k, [5, 29, 30, 31, 32, 35, 37, 39])) {
                $reg = "/^[^\d]*(\d\d?)\/(\d\d?)\/(\d\d\d\d)[^\d]*$/u";
                $res = preg_match($reg, $v);
                if ($res === 0 or $res === FALSE or $v == "00000000" or $v == "//")
                    $v = NULL;
                else {
                    $v = preg_replace($reg, "$3-$1-$2", $v);
                    $v_arr = explode("-", $v);
                    $ano = $v_arr[0];
                    $mes = $v_arr[1];
                    $dia = $v_arr[2];
                    if (!checkdate($mes, $dia, $ano)) {
                        if (checkdate($dia, $mes, $ano)) {
                            $v = "$ano-$dia-$mes";
                        } else {
                            $v = "";
                        }
                    }
                }
            }
            // campo tipo_novedad
            elseif ($k == 6) {
                $v = preg_replace("/  +/", " ", trim(strtoupper($v), ' "'));
            }
            // campos varchar
            else {
                $reg = '/^"(.*)"$/u';
                $res = preg_match($reg, $v);
                if ($res !== 0 and $res !== FALSE)
                    $v = preg_replace('/^"?(.*[^"])"?$/', "$1", $v);
            }

            //actualizo valor
            $lineArr[$k] = $v;

        } //end foreach lineArr

        /* Agrego campo filename con path relativo */
        $lineArr[] = $nombre_file;
        $values_arr = array($lineArr);

        return $values_arr;
    }

    /*** JUICIOS JURAD ***/
    private static function parsearLineaJuiciosJurad($LINE, $nombre_file, $n_linea, $params = []) {

        //$LINE = trim($LINE); //pueden existir campos vacios (tabulados finales)
        $values_arr = [];
        $lineArr = [];
        $lineArr = explode(self::$separador_campos, $LINE);
        $n_campos = count($lineArr);

        if ($n_campos != 20) {
            //Numero de campos equivocado
            Misc::Log("[" . $nombre_file . ":" . $n_linea . "] Error numero de campos: " . $n_campos . " (esperados: 20)", self::$errorlog);
            self::$consultar_errores = 1;
            return 0;
        }
        // parse cada campo
        foreach ($lineArr as $k => $v) {
            //escape quote
            $v = trim($v);
            $v = str_replace("'", "''", $v);

            // campos fecha #5, #29, #30, #31, #34, #36, #38 
            if ($k == 6) {
                $reg = "/^[^\d]*(\d\d?)\/(\d\d?)\/(\d\d\d\d)[^\d]*$/u";
                $res = preg_match($reg, $v);
                if ($res === 0 or $res === FALSE or $v == "00000000" or $v == "//")
                    $v = "";
                else {
                    $v = preg_replace($reg, "$3-$2-$1", $v);
                    $v_arr = explode("-", $v);
                    $ano = $v_arr[0];
                    $mes = $v_arr[1];
                    $dia = $v_arr[2];
                    if (!checkdate($mes, $dia, $ano)) {
                        if (checkdate($dia, $mes, $ano)) {
                            $v = "$ano-$dia-$mes";
                        } else {
                            $v = "";
                        }
                    }
                }
            }
            //actualizo valor
            $lineArr[$k] = $v;
        } //end foreach lineArr

        /* Agrego campo filename con path relativo */
        $lineArr[] = $nombre_file;
        $values_arr = array($lineArr);
        return $values_arr;
    }


    /*** SOCIEDADES BT ***/
    private static function parsearLineaSociedadesBT($LINE, $nombre_file, $n_linea, $params = []) {
        $LINE = trim($LINE);
        $LINE = preg_replace("/\\" . self::$separador_campos . "$/u", "", $LINE); //elimino pipes al final de la linea
        $values_arr = [];
        $lineArr = [];
        $lineArr = explode(self::$separador_campos, $LINE);

        $n_campos = count($lineArr);

        if ($n_campos != 19) {
            //Numero de campos equivocado
            Misc::Log("[" . $nombre_file . ":" . $n_linea . "] Error numero de campos: " . $n_campos . " (esperados: 19)", self::$errorlog);
            self::$consultar_errores = 1;
            return 0;
        }

        foreach ($lineArr as $k => $v) {
            //escape quote
            $v = trim($v);
            $v = str_replace("'", "''", $v);
            // campo id_boletin #0
            if ($k == 0) {
                if ($v != "") {
                    $v = preg_replace("/^[^\d]*(\d+)[^\d]*$/u", "$1", $v);
                }
            }
            // campo fecha_publicacion #6 y #10
            else if ($k == 6 or $k == 10) {
                $reg = "/(\d{4})(\d{2})(\d{2})/u";
                $res = preg_match($reg, $v);
                if ($res === 0 or $res === FALSE or $v == "00000000")
                    $v = "";
                else {
                    $v = preg_replace($reg, "$1-$2-$3", $v);
                }
            }
            //actualizo valor
            $lineArr[$k] = $v;
        } //end foreach lineArr


        // Agrego campo contenido_archivo
        $dir_des_edictos = self::$archivos_des_dir . DIRECTORY_SEPARATOR . self::$fuente['folder_edictos'];
        $archivo_filename = strtolower((str_replace("'", "", $lineArr[18])));

        // busco archivo
        $archivos_textos_bt = $_FILES['archivos_textos_bt']['name'];
        $archivos_textos_bt = array_map("strtolower", $archivos_textos_bt);

        $encontrado = array_search($archivo_filename, $archivos_textos_bt);

        if ($encontrado === FALSE) {
            Misc::Log("[" . $nombre_file . ":" . $n_linea . "] ERROR en la busqueda del archivo $archivo_filename, no se encuentra en la lista de archivos seleccionados", self::$errorlog);
            self::$consultar_errores = 1;
            return 0;
        } else {
            $archivo = $_FILES['archivos_textos_bt']['tmp_name'][$encontrado];
            if (file_exists($archivo)) {
                $archivo_content = file_get_contents($archivo);
                $archivo_content = preg_replace("/^([^A-Z\d]*)/", "", $archivo_content);
                $archivo_content = preg_replace("/'/", "''", $archivo_content);
                $lineArr[] = $archivo_content;
                $res = copy($archivo, $dir_des_edictos . DIRECTORY_SEPARATOR . $archivo_filename);
            } else {
                Misc::Log("[" . $nombre_file . ":" . $n_linea . "] ERROR en la busqueda del archivo $archivo_filename, no existe el temporal", self::$errorlog);
                self::$consultar_errores = 1;
                return 0;
            }
        }

        /* Agrego campo filename con path relativo */
        $lineArr[] = $nombre_file;
        $values_arr = array($lineArr);
        return $values_arr;
    }

    /*** SOCIEDADES GJ ***/
    private static function parsearLineaSociedadesGJ($LINE, $nombre_file, $n_linea, $params = []) {

        $values_arr = [];
        $lineArr = [];
        $lineArr = explode(self::$separador_campos, $LINE);
        $n_campos = count($lineArr);

        if (!in_array($n_campos, [22, 23, 25])) {
            //Numero de campos equivocado
            Misc::Log("[" . $nombre_file . ":" . $n_linea . "] Error numero de campos: " . $n_campos . " (esperados: 22|23|25)", self::$errorlog);
            self::$consultar_errores = 1;
            return 0;
        }

        // parse cada campo
        foreach ($lineArr as $k => $v) {

            // campo id_boletin #0
            if ($k == 0) {
                if ($v == "") {
                    $v = "";
                }
            } elseif ($k == 2 or $k == 9 or ($n_campos != 23 && $k == 13) or ($n_campos == 23 && $k == 14)) { #9 #14
                // campos fecha #2, #9, #13(22/25 campos) o #14(23) 
                $reg = "/(\d{2})\/(\d{2})\/(\d{4})/u";
                $res = preg_match($reg, $v);
                if ($res === 0 or $res === FALSE or $v == "00000000" or $v == "//")
                    $v = NULL;
                else
                    $v = preg_replace($reg, "$3-$2-$1", $v);
            }

            //actualizo valor
            $lineArr[$k] = $v;
        } //end foreach lineArr

        // Arreglo el numero de campos:
        // >> Pueden haber files con nro. campos:
        //   - 22/23 (con o sin el campo #10:contenido_archivo)
        //   - 25 (+#24:duracion, +#25:objeto)
        // >> Los campos #6 y #19 pueden venir en formatos diferentes, van en campos diferentes:
        //    #6:localidad_sociedad_cod, #7:localidad_sociedad, #21:localidad_integrante_cod, #22:localidad_integrante
        //    - 22: +#6:"", #7:value, +#21:"", #22:value
        //    - 23/25: #6:value, +#7:"", #21:value, +#22:""

        /** 22/23 campos **/
        if (in_array($n_campos, [22, 23])) {
            if ($n_campos == 22) {
                array_splice($lineArr, 10, 0, "");
            }
            $lineArr[] = ""; // +Campo 'duracion'
            $lineArr[] = ""; // +Campo 'objeto'
        } else { /** 25 campos **/

            // contenido_archivo va de posicion #22 a #10.
            // Posiciones #23 y #24 bajan a #22 y #23 
            $contenido_archivo = $lineArr[22];
            $_23 = $lineArr[23];
            $_24 = $lineArr[24];
            $lineArr[22] = $_23;
            $lineArr[23] = $_24;
            unset($lineArr[24]);
            array_splice($lineArr, 10, 0, $contenido_archivo);
        }

        // campos 6/7 y 20/21
        if ($n_campos == 23) {
            array_splice($lineArr, 6, 0, "");
            array_splice($lineArr, 21, 0, "");
        } else {
            array_splice($lineArr, 7, 0, "");
            array_splice($lineArr, 22, 0, "");
        }

        /* Agrego campo filename con path relativo */
        $lineArr[] = $nombre_file;

        $values_arr = array($lineArr);
        return $values_arr;
    }




    // ------------- METODOS SECUNDARIOS ---------------------


    private static function esValidoArchivoJuiciosBT($filename) {
        $nombre_file = ltrim(str_replace(self::$directorio_fuente, "", $filename), "/");
        $esValido = TRUE;
        $file = fopen($filename, "r");
        $n_linea = 1;
        while (($LINE = fgets($file)) !== FALSE) {
            // iconv() - utf_encode()
            if (!preg_match('!!u', $LINE)) {
                $try_utf8 = TRUE;
                if (mb_detect_encoding($LINE) === FALSE) {
                    try {
                        $try_utf8 = FALSE;
                        $LINE = iconv("windows-1252", "UTF-8", $LINE);
                    } catch (\Exception $e) {
                        $try_utf8 = TRUE;
                    }
                } elseif ($try_utf8) {
                    try {
                        $LINE = mb_convert_encoding($LINE, 'UTF-8', 'ISO-8859-1');
                    } catch (\Exception $e) {
                    }
                }
            }

            $LINE = trim($LINE);
            $LINE = rtrim(trim($LINE), self::$separador_campos);
            if ($n_linea == 1) {
                self::$juicios_csv_fields_arr = array_map("trim", explode(self::$separador_campos, $LINE));
                $csv_fields_count = count(self::$juicios_csv_fields_arr);

                if (($csv_fields_count < 7) && ($csv_fields_count > 8)) {
                    //Numero de campos equivocado
                    Misc::Log("[" . $nombre_file . ":" . $n_linea . "] Error numero de campos de la cabecera del archivo es distinto: " . $csv_fields_count . " (esperados: 7)", self::$errorlog);
                    $esValido = FALSE;
                }
            }
            $values_arr = [];
            $lineArr = [];
            $lineArr = explode(self::$separador_campos, $LINE);
            $n_campos = count($lineArr);


            if (($n_campos < 6) && ($n_campos > 8)) {
                //Numero de campos equivocado
                Misc::Log("[" . $nombre_file . ":" . $n_linea . "] Error numero de campos es distinto: " . $n_campos . " (esperados: " . $csv_fields_count . ")", self::$errorlog);
                $esValido = FALSE;
            }
            $n_linea++;
        }

        fclose($file);
        return $esValido;
    }

    public static function obtenerNombreMetodo() {
        $nombre = str_replace("_", " ", self::$fuente_key);
        $nombre = ucwords($nombre);
        $nombre = str_replace(" ", "", $nombre);
        return $nombre;
    }

    public static function obtenerFuentes() {
        return [
            'gafip' => [
                'fuente_procesada' => 'gafip'
            ],
            'aduana' => [
                'folder' => 'aduana',
                'label' => 'Aduana',
                'store_procedure' => 'ADUANA_insertar',
                'separador_campos' => "|",
                'fuente_procesada' => 'aduana'

            ],



            'aduanaimpo' => [
                'folder' => 'aduanaimpo',
                'label' => 'Aduana (importaciones)',
                'store_procedure' => 'ADUANA_impo_insertar',
                'separador_campos' => "\t",
                'fuente_procesada' => 'äduanaimpo'
            ],


            'aduanaexpo' => [
                'folder' => 'aduanaexpo',
                'label' => 'Aduana (exportaciones)',
                'store_procedure' => 'ADUANA_expo_insertar',
                'separador_campos' => "\t",
                'fuente_procesada' => 'aduanaexpo'
            ],


            'arba' => [
                'folder' => 'arba',
                'label' => 'Arba',
                'store_procedure' => 'ARBA_actualizar_insertar',
                'separador_campos' => FALSE, // campos fijos
                'fuente_procesada' => 'arba'

            ],

            'cheques' => [
                'folder' => 'cheques_altas',
                'folder_bajas' => 'cheques_bajas',
                'label' => 'Cheques',
                'store_procedure' => 'CHEQUES_insertar',
                'separador_campos' => FALSE, // campos fijos
                'fuente_procesada' => 'cheques'

            ],
            'cyq_bt' => [
                'folder' => 'cyq_bt',
                'label' => 'C Y Q: fuente Bustos Thames',
                'store_procedure' => 'CYQ_BT',
                'separador_campos' => "|",
                'fuente_procesada' => 'cyq_bt'
            ],

            'defunciones' => [
                'folder' => 'defunciones',
                'label' => 'Defunciones',
                'store_procedure' => 'DEFUNCIONES_insertar',
                'separador_campos' => "\t",
                'fuente_procesada' => 'defunciones'

            ],

            'inscripciones' => [
                'folder' => 'inscripciones',
                'label' => 'Inscripciones',
                'store_procedure' => 'INSCRIPCIONES_insertar',
                'separador_campos' => FALSE, // campos fijos
                'fuente_procesada' => 'inscripciones'

            ],

            'juicios_bt' => [
                'folder' => 'juicios_bt',
                'label' => 'Juicios: fuente Bustos Thames',
                'store_procedure' => 'JUICIOS_BT_insertar',
                'normalizar' => [ // CSV_FIELD_NAME = table_field_name
                    "PROVINCIA" => "localidad_del_juzgado",
                    "FECHA" => "fecha_causa",
                    "JUZGADO" => "radicacion",
                    "ACTOR" => "actor",
                    "DEMANDADO" => "demandado",
                    "EXPEDIENTE" => "expediente",
                    "OBJETO" => "tipo_de_novedad",
                    "FOJA" => "foja",
                    "ORDEN" => "codigo",
                    "DECRETO" => "decreto",
                    "ABOGADO" => "abogado",
                    "TEXTO" => "observaciones"
                ],
                'separador_campos' => ';',
                'fuente_procesada' => 'Juicios'

            ],

            'juicios_myf' => [
                'folder' => 'juicios_myf',
                'label' => 'Juicios: fuente MYF',
                'store_procedure' => 'JUICIOS_MYF_insertar',
                'organismos_solicitantes' => array('AFIP'),
                'separador_campos' => ";",
                'fuente_procesada' => 'Juicios'

            ],

            'juicios_jurad' => [
                'folder' => 'juicios_jurad',
                'label' => 'Juicios: fuente Jurad',
                'store_procedure' => 'JUICIOS_JURAD_insertar',
                'separador_campos' => "\t",
                'fuente_procesada' => 'Juicios'
            ],

            'sociedades_bt' => [
                'folder' => 'sociedades_bt',
                'folder_edictos' => 'sociedades_edictos',
                'label' => 'Sociedades: fuente Bustos Thames',
                'store_procedure' => 'SOCIEDADES_BT_insertar',
                'separador_campos' => "|",
                'fuente_procesada' => 'sociedades'
            ],

            'sociedades_gj' => [
                'folder' => 'sociedades_gj',
                'label' => 'Sociedades: fuente Grupo Jurad',
                'store_procedure' => 'SOCIEDADES_GJ_insertar',
                'separador_campos' => "\t",
                'fuente_procesada' => 'sociedades'
            ]
        ];
    }

    // busca los archivos
    private static function obtenerArchivos($directorio_fuente) {

        if (!isset($_POST["fuente"])) {
            $msg = "Error en los parametros del form, la fuente debe ser especificada.";
            Misc::Log($msg, self::$errorlog);
            self::$consultar_errores = 1;
            return array(0, $msg);
        } elseif (!isset($_FILES["bajas"]) && !isset($_FILES["archivo"])) {
            $msg = "Error en los parametros del form, ningún archivo para cargar";
            Misc::Log($msg, self::$errorlog);
            self::$consultar_errores = 1;
            return array(0, $msg);
        } else if (!isset($_FILES["archivo"])) {
            return array(0, "");
        }

        $archivos = [];

        //uploaded file
        if (!isset($_FILES)) {
            $msg = "Error (POST FILES)";
            return array(0, $msg);
        }

        $archivo = $directorio_fuente . DIRECTORY_SEPARATOR . basename($_FILES["archivo"]["name"]);
        $res = move_uploaded_file($_FILES["archivo"]["tmp_name"], $archivo);
        if ($res) {
            $archivos = [realpath($archivo)];
        } else {
            $msg = "No se pudo subir el archivo. $res";
            return array(0, $msg);
        }

        return array(1, $archivos);
    }

    // busca archivos (regex:filename) en $dir
    private static function buscarArchivos($recursive, $dir, $filename, &$files_arr = array()) {
        $files = scandir($dir);

        foreach ($files as $f) {
            $path = realpath($dir . DIRECTORY_SEPARATOR . $f);
            if (!is_dir($path)) {
                if (preg_match("/^" . $filename . "$/i", $f) == 1) {
                    $files_arr[] = $path;
                }
            } else if ($f != "." && $f != "..") {
                if ($recursive) {
                    self::buscarArchivos($recursive, $path, $filename, $files_arr);
                }
            }
        }
        return $files_arr;
    }

    private static function porcentajeBarraProgreso($actual, $total, $campo = "") {
        // Calculo de porcentaje
        $porcentaje = intval($actual / $total * 100) . "%";
        // Javascript for updating the progress bar and information
        while (@ob_end_flush())
            ;
        ob_implicit_flush(true);
        echo '
    <script language="javascript">
    		$("#progress' . $campo . '").html("<div style=\"width:' . $porcentaje . '\">&nbsp;</div>");
    		$("#information' . $campo . '").html("' . $actual . ' registros(s) procesados de ' . $total . '");
    </script>';
        //This is for the buffer achieve the minimum size in order to flush data
        //echo str_repeat(' ',1024*64);

        /*
              // Send output to browser immediately
              ob_flush();
          flush();*/
    }

    private static function validarFechaFuente() {
        self::$fuente_fecha = Request::input('fuente_fecha');
        if (!isset(self::$fuente_fecha)) {
            Misc::Log("Error en el formulario, debe asigar una fecha para la fuente.", self::$errorlog);
            self::$consultar_errores = 1;
            return FALSE;
        } else {
            $datetime = DateTime::createFromFormat('m/d/Y', self::$fuente_fecha);
            if (!$datetime) {
                Misc::Log("Error al parsear la fecha de la fuente ingresada en el formulario, verifique que el formato ingresado sea mm/dd/yyyy.", self::$errorlog);
                self::$consultar_errores = 1;
                return FALSE;
            }
            self::$fuente_fecha = $datetime->format('Y-m-d');
            return TRUE;
        }
    }

    private static function ejecutarStoreProcedure($nombre_SP, $nombre_file, $n_linea, $values) {
        try {
            $res = SQLConnection::backendStoreProcedure($nombre_SP, $values);
        } catch (\Exception $e) {
            self::$consultar_errores = 1;
            Misc::Log("[ERROR SP " . $nombre_SP . "][" . $nombre_file . ":" . $n_linea . "] VALUES: " . implode(",", $values) . "| SQLError: " . $e->getMessage(), self::$errorlog);
        }
    }

    public static function parsearBusquedaPadron($campo) {
        $campo = self::limpiarString($campo);
        $exploded = explode(" ", $campo);
        $full_search = "";
        if (sizeof($exploded) == 1 && strlen($campo) > 2) {
            return "\"" . $campo . "*\"";
        } elseif (((sizeof($exploded) == 2) && ((strlen($exploded[0]) + strlen($exploded[1])) > 2)) || (sizeof($exploded) > 2)) {
            foreach ($exploded as $key => $part) {
                if ($part != '') {
                    if ($part == 'Y') {
                        continue;
                    }
                    $part = (strlen($part > 1)) ? "\"*" . $part . "*\"" : "\"" . $part . "*\"";
                    if ($key == 0) {
                        $full_search = $part;
                    } else {
                        $full_search .= " NEAR " . $part;
                    }
                }
            }
            return $full_search;
        }
        return $full_search;
    }

    public static function limpiarString($str) {
        //limpia string para búsqueda, solo dejando caracteres alfanuméricos y espacios simples
        $str = trim($str);
        $str = preg_replace('/\s+/', ' ', $str);
        $str = preg_replace('/[^\p{Latin}\d ]/u', '', $str);
        return strtoupper($str);
        //return preg_replace( "/[^A-Z0-9Ñ ]/u", "", $str);
    }

}