<?php

/*
 * ROMAN DIGITAL - Autor: Américo Patetta
 */

set_include_path("../../");
include_once("server/class/PedidosManager.php");
include_once("server/class/Delivery.php");
include_once("server/class/WebStatusManager.php");
include_once("server/class/Audit/Logger.php");
@session_start();

$jsonParams = file_get_contents('php://input');
$paramObj = json_decode($jsonParams);
$curl = array();
// if(isset($paramObj->idPedido) && isset($paramObj->status) && isset($paramObj->lat) && isset($paramObj->lng)){

$lat = isset($paramObj->lat)?$paramObj->lat:0;
$lng = isset($paramObj->lng)?$paramObj->lng:0;


if (isset($paramObj->idPedido) && isset($paramObj->status) && isset($paramObj->token)) {
    Logger::log(sprintf("SetStatus(idPedido: %s, status: %s)",$paramObj->idPedido, $paramObj->status));
    $delivery = new Delivery(-1);
    $idDelivery = $delivery->setIdDeliveryFromToken($paramObj->token);
    if ($idDelivery != -1) {
        $pedidosManager = new PedidosManager();
        $idPedidoBocatti = $pedidosManager::getIdPedidoBocatti($paramObj->idPedido);
        $ack['error'] = ($pedidosManager->setPedidoStatus($paramObj->idPedido, $paramObj->status, $idDelivery,null,$lat,$lng)) ? 0 : -1;
        if ($idPedidoBocatti != null && $ack['error'] === 0) {
            $curl = WebStatusManager::updateStatus($idPedidoBocatti, $paramObj->status);
            //echo "<pre>";
            //print_r($curl);
            $ack['msg'] = "Ok!";
        } else {
            $ack['msg'] = "Status sin cambios";
            $curl['res'] = -1;
            $curl['msg'] = "No se ha podido actualizar el pedido (Ptk: " . $paramObj->idPedido . ", Bocatti: " . $idPedidoBocatti . ")";
        }
    } else {
        $ack['error'] = -3;
        $ack['msg'] = "Identificador de Delivery incorrecto";
        $curl['res'] = -4;
        $curl['msg'] = "El token provisto no es válido.";
    }
} else {
    Logger::log("SetStatus(Parámetros incompletos)");
    $curl['res'] = -4;
    $curl['msg'] = "Parametrización incorrecta";
    $ack['error'] = -2;
    $ack['msg'] = "Parametrización incorrecta";
}

header('Content-Type: application/json; charset=utf-8');
echo json_encode($ack);