<?php
session_start();
$usuarioSession = isset($_SESSION['USUARIO']) ? $_SESSION['USUARIO'] : 'usuario_cron';
$grupo = isset($_SESSION['GRUPO']) ? $_SESSION['GRUPO'] : '-1';
$contacto = isset($_SESSION['CONTACTO']) ? $_SESSION['CONTACTO'] : '-1';
$awa_session_id = isset($_SESSION['AWA_SESION_ID']) ? $_SESSION['AWA_SESION_ID'] : '0000CRON000';
include('../lg/config_vo.php');//+
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');//-
$cookieUser = filter_input(INPUT_COOKIE, 'usuario') ?? null; 
$cookieIdioma = filter_input(INPUT_COOKIE, 'idioma') ?? null; 
if((!isset($usuarioSession) or $awa_session_id != $awa_id) or (isset($cookieUser) AND $cookieUser != $staticUsu )){
    eatCookies();
    Statics::add_trace_history($con, "CRON", -1, 14, 'multipost-stock-cochescom-cron: Sin usuario de session. No se ha publicado');
    die('No user');
}
empty($cookieIdioma)?
    include('../lg/LG_' . $cookieIdioma . '.php'):
    include('../lg/LG_SP.php');


date_default_timezone_set('Europe/Madrid');
$date = date('Y-m-d H:i:s');


$Schema = new Schema($con);
$MotherCar = new MotherCar($con);
$dom = new DOMDocument();
$dom->encoding = 'UTF-8';
$dom->xmlVersion = '1.0';
$dom->formatOutput = true;

$bucket_xml = '../bucket/xml_bucket/cochescom';
if (!file_exists($bucket_xml)) {
    mkdir($bucket_xml, 0777, true);
}
$xml = 'CochescomDealerbest.xml';
$root = $dom->createElement('Traspaso');
$version_xml_node = $dom->createElement('Version', "1.0");
$root->appendChild($version_xml_node);
$anuncio_node = $dom->createElement('Anuncio');

$sql = 'SELECT V.*, P.PORTAL AS PORTAL_TO_POST, P.PRECIO_CONTADO AS PUBLICACION_PRECIO_CONTADO, P.PRECIO_FINANCIADO AS PUBLICACION_PRECIO_FINANCIADO, P.COMENTARIOS AS PUBLICACION_COMENTARIOS
FROM VEHICULOS V
INNER JOIN VEHICULOS_PUBLICACIONES P ON V.CODIGO = P.VEHICULO AND P.ACTIVO = ? AND P.PORTAL = (SELECT R.CODIGO FROM VEHICULOS_PORTALES R WHERE R.ALIAS = ?)
WHERE V.ACTIVO = ?';
$res = $Schema->executeQuery($sql, 'isi', [1, 'MPC', 1]);
while($row = $res->fetch_array()) {
    $codigo_vehiculo = $row['CODIGO'];
    $origen = $row['CODE_EXT'];
    $portal = $row['PORTAL_TO_POST'];
    $rowCar = $MotherCar->getCarData($codigo_vehiculo);

    if(!empty($rowCar['VENTA_TOTALSINDTO'])) {
        include('../includes/components/xml_body.php');
    }
}

$dom->appendChild($root);
$dom->save($bucket_xml . '/' . $xml, LIBXML_NOEMPTYTAG);
Statics::add_trace_history($con, "CRON", -1, 14, "Multipublicación - vehículo publicado en coches.com"); // 14 = publicación VEHICULOS_LITERALES.TIPO = TIP_TRA

if(!empty(filter_input(INPUT_get, 'manual'))){
    header("Location:../post-stocks.php?p=3");
}