<?php
session_start();
$usuarioSession = $_SESSION['USUARIO'];
$grupo = $_SESSION['GRUPO'];
$contacto = $_SESSION['CONTACTO'];
$awa_session_id = $_SESSION['AWA_SESION_ID'];
include('../includes/conex.php');
include('../includes/eat.php');
include('../includes/historial.php');
include('../includes/functions.php');
include('../includes/esquemas.php');
include('../class/Schema.php');
include('../class/MotherCar.php');
include('../class/Expediente.php');
include('../class/Bibliotecas.php');
include('../class/Static.php');
include('../class/WebServices.php');
include('../lg/config_vo.php');
if(!isset($usuarioSession) OR $awa_session_id != $awa_id) {
    eatCookies();
    header('Location:../index.php');
}
if(isset($_COOKIE['usuario']) AND $_COOKIE['usuario'] != $staticUsu ) {
    eatCookies();
    header('Loction:../index.php');
}
if (isset($_COOKIE['idioma'])) {
    include('../lg/LG_' . $_COOKIE['idioma'] . '.php');
} else {
    include('../lg/LG_SP.php');
}
$Schema = new Schema($con, $database);
$MotherCar = new MotherCar($con);
$Expediente = new Expediente($con);
$Bibliotecas = new Bibliotecas($con);
$codigo_vehiculo = $_SESSION['VEHICULO_TASACION'];
$target_dir = "../tmp_img/";
$request = isset($_POST['request']) ? Statics::SafeInput($con, $_POST['request']) : 1;



// Upload file
if($request == 1){ 

    $res = $Schema->executeQuery('SELECT MARCA, MODELO, MOSTRAR, IDCAR FROM VEHICULOS WHERE CODIGO = ?', 'i', [$codigo_vehiculo]);
    $row = $res->fetch_array();
    $mostrar = $row['MOSTRAR'];
    $Schema->set_ubicacion_archivos($target_dir)->get_ubicacion_archivos();
    $EXP0 = 'EXP000000000000000';
    $codigo_exp_tipo = $Schema->select_expediente_tipos_valores('VEHICULO_STOCK');
    $descripcion_exp_tipo = $Schema->select_expediente_tipos_valores('VEHICULO_STOCK', 'DESCRIPCION');
    $codigo_esq_estr = $Schema->select_esquema_estructura_valores('VEHICULO', -1);
    $str_replace = substr_replace($EXP0,$codigo_exp_tipo,-strlen($codigo_exp_tipo));
    $contadores = $Expediente->check_contador_expediente($codigo_vehiculo) ? $Expediente->check_contador_expediente($codigo_vehiculo) : Statics::get_contadores($con,$str_replace);
    if($Expediente->check_expediente($codigo_esq_estr, $contadores)) {
        $claveXT = "XT$codigo_exp_tipo";
        $nombreXT = $descripcion_exp_tipo; 
        $padreXT = "##EXPEDIENTES##";
        $iconoXT = "expediente";
        $ubicacionXT = "##PUBLICO##/##EXPEDIENTES##/";
        $ano = date('Y');
        $fechahoy = date('d/m/Y');

        $claveXA = "XA$codigo_exp_tipo".".$ano";
        $nombreXA = $descripcion_exp_tipo; 
        $padreXA = "##EXPEDIENTES##";
        $iconoXA = "fecha";
        $ubicacionXA = "##PUBLICO##/##EXPEDIENTES##/" . $claveXT . "/";


        $Expediente->insert_biblioteca_expedientes_valores($contadores,1,$codigo_exp_tipo,0,$contadores);
        $Expediente->insert_biblioteca_expedientes_valores($contadores,2,$codigo_exp_tipo,1,$fechahoy,0,"NOW()");
        $Expediente->insert_biblioteca_expedientes_valores($contadores,3,$codigo_exp_tipo,2,$descripcion_exp_tipo,false,false,$codigo_exp_tipo);
        $Expediente->insert_biblioteca_expedientes_valores($contadores,$codigo_esq_estr,$codigo_exp_tipo,3,$mostrar,false,false,$codigo_vehiculo);

        if ($Expediente->check_expediente_carpeta($claveXT) == 0) {
            $Expediente->crear_carpeta_expediente($claveXT, $nombreXT, $padreXT, $usuarioSession, $iconoXT, $ubicacionXT);
        } 
        if ($Expediente->check_expediente_carpeta($claveXA) == 0) {
            $acceso = $Expediente->select_acceso_biblioteca_elementos($claveXT);
            $Expediente->crear_carpeta_expediente($claveXA, $ano, $claveXT, $usuarioSession, $iconoXA, $ubicacionXA, $acceso);
        } else {
            $acceso = $Expediente->select_acceso_biblioteca_elementos($claveXA);
        }

        $claveEXP = get_id_unico();
        $padre = $claveXA;
        $ubicacion = $ubicacionXA . "$claveXA/";
        $Expediente->crear_carpeta_expediente($claveEXP,$mostrar,$padre,$usuarioSession,$iconoXT,$ubicacion,$acceso,$contadores);
        $Expediente->insert_biblioteca_etiquetas_expediente(get_id_unico(),$claveEXP,$contadores,1,-1);
    } else {
        $claveEXP = $Expediente->select_clave_padre_acceso_ubicacion_expediente($codigo_vehiculo);
        $acceso = $Expediente->select_clave_padre_acceso_ubicacion_expediente($codigo_vehiculo, 'ACCESO');
        $ubicacion = $Expediente->select_clave_padre_acceso_ubicacion_expediente($codigo_vehiculo, 'UBICACION'); 
    }
    $sql_pos = 'SELECT MAX(E.POS) AS MAX_POS
    FROM BIBLIOTECA_ELEMENTOS E 
    INNER JOIN BIBLIOTECA_ETIQUETAS T ON T.CLAVE = E.CLAVE
    WHERE T.ETIQUETA = ? AND E.PAPELERA = ?';
    $res_pos = $Schema->executeQuery($sql_pos, 'ii', [$codigo_vehiculo, 0]);
    $row_pos = $res_pos->fetch_array();
    $posicion = $row_pos['MAX_POS'] + 1;
    $clave = $Schema->set_clave_elemento(get_id_unico())->get_clave_elemento();
    $name = $_FILES['file']['name'];
    $tmp = $_FILES['file']['tmp_name'];
    $size = $_FILES['file']['size'];
    $part = pathinfo($name);
    $extension = $part['extension'];
    $name = Statics::rename($extension, $posicion, $con, $row['IDCAR']);
    if($part['extension'] != 'pdf') {
        $Schema->set_resize_img(TRUE);
    }
    $Schema->upload_doc($tmp, $name, $size, $claveEXP, $acceso, $ubicacion, $usuarioSession, $codigo_vehiculo, $posicion);


    $codigo_biblioteca_etiquetas = get_id_unico();
    $Schema->asignar_etiquetas_nuevo_expediente($codigo_biblioteca_etiquetas, $codigo_vehiculo, $mostrar, TRUE, TRUE);
    $Schema->executeQuery("INSERT INTO VEHICULOS_TASACIONES_DOCS(TASACION, DOCUMENTO, ALIAS) VALUES(?,?,?)", 'sss', [
        Statics::SafeInput($con, $_POST['codigo_tasacion']), 
        $Schema->get_clave_elemento(), 
        Statics::SafeInput($con, $_POST['key'])
    ]);

    echo $clave;
}

// Remove file
if($request == 2){ 
    $clave = str_replace('\r\n', '', Statics::SafeInput($con, $_POST['name'])); 
    $Schema->executeQuery('UPDATE BIBLIOTECA_ELEMENTOS SET PAPELERA = ? WHERE CLAVE = ?', 'is', [1, $clave]);
    echo $clave;
}


if($request == 3)  {
    $file_list = [];
    $html = '';
    $clave = str_replace('\r\n', '', Statics::SafeInput($con, $_POST['name'])); 
    $tas = Statics::SafeInput($con, $_POST['tasacion']); 
    $ESQUEMA = $Schema->select_esquema_o_esquema_estructura(TRUE); 
    $GRUPO = $Schema->select_esquema_o_esquema_estructura();

    $res = $Schema->executeQuery('SELECT T.*, E.*, Q.*
    FROM VEHICULOS_TASACIONES_DOCS T
    INNER JOIN BIBLIOTECA_ELEMENTOS E ON T.DOCUMENTO = E.CLAVE 
    INNER JOIN BIBLIOTECA_ETIQUETAS Q ON Q.CLAVE = E.CLAVE
    WHERE T.ALIAS = ? AND T.TASACION = ?
    AND E.PAPELERA = ? 
    AND Q.ESQUEMA = ? 
    AND Q.GRUPOE = ? ', 'ssiii', [$clave, $tas, 0, $ESQUEMA, $GRUPO]);
    
    if($res->num_rows) {
        while($row = $res->fetch_array()) {
            /* $html .= $row['DOCUMENTO'] . '<br>'; */
            $TMP_FILE = '../tmp_img/' . $row['NOMBRE'];
            $Schema->create_file($TMP_FILE, $row['PARTES'], $row['SUFIJO'], $row['CLAVE']);
            $size = filesize($TMP_FILE);
            $file_list = [
                'name'      =>      $row['NOMBRE'], 
                'size'      =>      $size, 
                'path'      =>      'tmp_img/' . $row['NOMBRE']];

        }
    }
    echo json_encode($file_list);
}


if($request == 4) {
    echo 123;
}
?>

