<?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('../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');
if(!isset($usuarioSession) OR !isset($awa_session_id)) {
    eatCookies();
    Statics::add_trace_history($con, "CRON", -1, 14, 'multipost-stock-miprimercoche-cron: Sin usuario de session. No se ha publicado');
    die('No user');
}
if(isset($_COOKIE['idioma'])) {
    include('../lg/LG_' . $_COOKIE['idioma'] . '.php');
} else {
    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/miprimercoche';
if (!file_exists($bucket_xml)) {
    mkdir($bucket_xml, 0777, true);
}
//$xml = 'sourceDealerBest_test.xml';// queda sobreescrito
$xml = 'MiprimercocheDealerbest.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_TOTAL'])) {
        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 miprimercoche");
if(!empty(filter_input(INPUT_get, 'manual'))){
    header("Location:../post-stocks.php?p=3");
}