<?php
namespace App\Custom;

use App\Custom\Misc;
use App\Custom\SQLConnection;
class AutomatizacionInscripciones {

    public function procesarArchivos($root_path, $cantidad_archivos = 2) {
        $errores = 0;
        $mensajes_error = [];
        $total = 0;
        $procesadas = 0;
        $i = 0;
        $opened_root = Misc::abrirDirectorio($root_path); // abro carpeta raíz
        if (is_array($opened_root)) { // es un directorio válido
            $current_path = $root_path;
            while (($i < $cantidad_archivos) && (($level_1_folder = readdir($opened_root[0])) !== false)) { // leo raíz y extraigo carpetas de años
                $current_path = $root_path . DIRECTORY_SEPARATOR . $level_1_folder;
                $opened_level_1_folder = Misc::abrirDirectorio($current_path); // abro carpeta de un año
                if (is_array($opened_level_1_folder)) { // es un directorio válido
                    while (($i < $cantidad_archivos) && (($file = readdir($opened_level_1_folder[0])) !== false)) { // leo directorio constituciones y extraigo archivos
                        $opened_file = Misc::abrirArchivo($current_path . DIRECTORY_SEPARATOR . $file);
                        if (is_array($opened_file)) {
                            $numero_linea = 0;
                            $i++;
                            while ((($line = fgets($opened_file[0])) !== false)) {
                                $numero_linea++;
                                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) {
                                            $errores++;
                                            $mensajes_error[] = "[{$current_path}/{$file}][linea: {$numero_linea}] Error en la conversion de caracteres con iconv().";
                                            $try_utf8 = true;
                                        }
                                    } elseif ($try_utf8) {
                                        try {
                                            $line = mb_convert_encoding($line, 'UTF-8', 'ISO-8859-1');
                                        } catch (\Exception $e) {
                                            $errores++;
                                            $mensajes_error[] = "[{$current_path}/{$file}][linea: {$numero_linea}] Error en la conversion de caracteres con utf8_encode().";
                                            continue;
                                        }
                                    }
                                }
                                $values_arr = self::parsearLineaInscripciones($line, $file, $numero_linea);

                                /* insert via store procedure */
                                try {
                                    // Esperar 9 milisegundos
                                    usleep(90000);
                                    $aux = SQLConnection::backendStoreProcedure('INSCRIPCIONES_insertar', array_values($values_arr), true);
                                    if (isset($aux->error)) {
                                        $errores++;
                                        $mensajes_error[] = "[{$current_path}/{$file}][linea: {$numero_linea}] Error SQL: " . $aux->error;
                                    } else {
                                        $procesadas++;
                                    }
                                } catch (\Exception $e) {
                                    $errores++;
                                    $mensajes_error[] = "[{$current_path}/{$file}][linea: {$numero_linea}] Error SQL: " . $e->getMessage();
                                }
                            }
                            $total += $numero_linea;
                            fclose($opened_file[0]); // cierro el archivo de constituciones
                            unlink($current_path . DIRECTORY_SEPARATOR . $file);
                        } elseif ($opened_file !== false) {
                            $errores++;
                            $mensajes_error[] = $opened_file;
                        }
                    }
                    closedir($opened_level_1_folder[0]);//cierro carpeta de año
                } elseif ($opened_level_1_folder !== false) {
                    $errores++;
                    $mensajes_error[] = $opened_level_1_folder;
                }
            }
            closedir($opened_root[0]);
        } else {
            $errores++;
            $mensajes_error[] = ($opened_root === false) ? 'Error: el directorio raíz no es un directorio.' : $opened_root;
        }
        return [
            'numero_de_errores' => $errores,
            'mensajes_error' => $mensajes_error,
            'total_numero_lineas' => $total,
            'numero_lineas_procesadas' => $procesadas,
            'status' => ($total == $procesadas) ? 'Success' : 'Errors Found'
        ];

    }

    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 = $lineArr;

        return $values_arr;
    }

}