<?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/Static.php');
include('../class/Crypt.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');
}
use Treinetic\ImageArtist\lib\PolygonShape;
use Treinetic\ImageArtist\lib\Text\TextBox;
use Treinetic\ImageArtist\lib\Text\Color;
use Treinetic\ImageArtist\lib\Text\Font;
use Treinetic\ImageArtist\lib\Overlays\Overlay;
use Treinetic\ImageArtist\lib\Image;
require('../vendor/autoload.php');
date_default_timezone_set('Europe/Madrid');
$Schema = new Schema($con);
$portal = Statics::SafeInput($con, Crypt::decryptURL($_POST['portal']));
$codigo_coche = Statics::SafeInput($con, $_POST['codigo_coche']);
$precio_contado = Statics::SafeInput($con, $_POST['precio_contado']);
$precio_financiado = Statics::SafeInput($con, $_POST['precio_financiado']);
$comentarios = mysqli_real_escape_string($con, nl2br($_POST['comentarios']));
$comentarios = str_replace('\r\n', '', $comentarios);
$date = date('Y-m-d H:i:s');


$resIMG = $Schema->executeQuery('SELECT E.CLAVE, E.NOMBRE, E.SUFIJO, E.PARTES, E.POS
FROM BIBLIOTECA_ELEMENTOS E 
INNER JOIN BIBLIOTECA_ETIQUETAS T1 ON E.CLAVE = T1.CLAVE
WHERE T1.ETIQUETA = ?', 'i', [$codigo_coche]);
if($resIMG->num_rows) {
    while($rowIMG = $resIMG->fetch_array()) {
        $sufijo = $rowIMG['SUFIJO'];
        $Schema->executeQuery("DELETE FROM FICHEROS_$sufijo WHERE CLAVE = ? AND VERSION <> ?", 'ss', [$rowIMG['CLAVE'], 0]);
    }
}
if(isset($_POST['foto'])) {
    if($_FILES['doc']['size'] > 0) {


        $posicion = isset($_POST['posicion_mascara']) ? 'Top' : 'Bottom';
        $name = $_FILES['doc']['name'];
        $tmp = $_FILES['doc']['tmp_name'];
        $size = $_FILES['doc']['size'];
        move_uploaded_file($tmp, "../tmp_img/mascaras/$name");
        $banner = new Image("../tmp_img/mascaras/$name");
        print_r($_FILES['doc']);
        
        foreach($_POST['foto'] as $f) {
            $f = Statics::SafeInput($con, $f);
            $f = explode("@", $f);
            $nombre_foto = $f[0];
            $clave_foto = $f[1];
            $entrada_foto = $f[2];
            $sufijo_foto = $f[3];
            $sufijo_foto = $f[3];
            $version_foto = $f[4] + 1;

            $foto = new Image("../tmp_img/mascaras/$nombre_foto");

            $bannerWidth = $foto->getWidth();
            $bannerHeight = $banner->getHeight() > $foto->getHeight() ? $banner->getHeight() / 10 : $foto->getHeight() / 10;

            $diccionario = [
                "Top"       =>      50,
                "Middle"    =>      ($foto->getHeight() - $bannerHeight) / 2,
                "Bottom"    =>      $foto->getHeight() - $bannerHeight
            ];
            
            $foto->merge($banner, 50, $diccionario[$posicion]);
            $foto->save("../tmp_img/mascaras/$nombre_foto", IMAGETYPE_PNG);


            $path = pathinfo($nombre_foto);
            $extension = $path['extension'];
            $item = "../tmp_img/mascaras/" . $path['basename'];
            $Schema->resize_img($item, 2000, $path['basename'], "../tmp_img/mascaras/");

            $ruta = fopen($item,"r");
            $doc_binario = fread($ruta,filesize($item));
            fclose($ruta);
            $size_foto = filesize($item);

            
            
            $Schema->executeQuery("INSERT INTO FICHEROS_$sufijo_foto(CLAVE, PARTE, VERSION, FICHERO, TAMANO, ENTRADA, TAMANOREAL) VALUES(?, ?, ?, ?, ?, ?, ?)", 'sissisi', [$clave_foto, 1, $version_foto, $doc_binario, $size_foto, $entrada_foto, $size_foto]); 
        }
    }
}
$res = $Schema->executeQuery('SELECT VEHICULO FROM VEHICULOS_PUBLICACIONES WHERE VEHICULO = ? AND PORTAL = ? AND ACTIVO = ?', 'iii', [$codigo_coche, $portal, 1]);
if($res->num_rows) {
   $Schema->executeQuery('UPDATE VEHICULOS_PUBLICACIONES SET ACTIVO = ?, FIN = ? WHERE VEHICULO = ? AND PORTAL = ? AND ACTIVO = ?', 'isiii', [0, $date, $codigo_coche, $portal, 1]);
}
$Schema->executeQuery('INSERT INTO VEHICULOS_PUBLICACIONES(VEHICULO, PORTAL, INICIO, ACTIVO, PRECIO_CONTADO, PRECIO_FINANCIADO, COMENTARIOS) VALUES(?, ?, ?, ?, ?, ?, ?)', 'iisiiis', [$codigo_coche, $portal, $date, 1, $precio_contado, $precio_financiado, $comentarios]);
Statics::eat_all_files("../tmp_img/mascaras/");
Statics::eat_all_files("../tmp_img/photo_multipost/");

header("Location:../post-stocks.php?p=" . Crypt::encryptURL($portal));




?>