<?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('../class/Schema.php');
include('../class/MotherCar.php');
include('../class/Ofertas.php');
include('../class/Static.php');
include('../includes/esquemas.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);
$Ofertas = new Ofertas($con);
$MotherCar = new MotherCar($con);

$doc = Statics::SafeInput($con, $_GET['doc']);
if(isset($_GET['codigo_coche']) && !empty($_GET['codigo_coche'])) {
    $codigo_coche =  Statics::SafeInput($con, $_GET['codigo_coche']);
    $MotherCar->set_codigo_vehiculo_tabla_vehiculos($codigo_coche);
    $MotherCar->set_estado('VEN');
    $MotherCar->update_vehiculo();
    $Ofertas->set_codigo($doc);
    /* $Ofertas->set_activo(0); */
    $Ofertas->set_estado(3);
    $Ofertas->update();
    $Schema->executeQuery('UPDATE VEHICULOS_OFERTAS SET ACTIVO = ? WHERE CODIGO <> ? AND VEHICULO = ?', 'isi', [0, $doc, $codigo_coche]);
} else {
    $codigo_coche = $_SESSION['CODIGO_COCHE'];
}
$row = $Schema->executeQuery("SELECT E.NOMBRE, E.SUFIJO, E.PARTES FROM BIBLIOTECA_ELEMENTOS E WHERE E.CLAVE = ? ", 's', [$doc])->fetch_array();
$tmp_doc = '../ofertas/pdf/' . $row['NOMBRE'];
file_exists($tmp_doc) ? unlink($tmp_doc) : false;
$create_doc = fopen($tmp_doc, 'a');
$values = $row['PARTES'];
for($i = 1; $i <= $values; $i++) {
    $sqlPartes = "SELECT FICHERO FROM FICHEROS_" . $row['SUFIJO'] . "  WHERE CLAVE = ? AND PARTE = ? AND VERSION = ?";
    $row_split = $Schema->executeQuery($sqlPartes, 'sis', [$doc, 1, '0'])->fetch_array();
    fwrite($create_doc, $row_split['FICHERO']);
}
fclose($create_doc);
$filename = basename($row['NOMBRE']);
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/zip");
header("Content-Transfer-Emcoding: binary");
readfile($tmp_doc);
unlink($tmp_doc);
Statics::add_trace_history($con, $usuarioSession, $codigo_coche, 6, $row['NOMBRE'] , $doc);
?>