<?php
session_start();
include '../includes/session_control.php';
require_once '../cotizaciones/api/_node.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method Not Allowed');
}

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();

$id          = intval($_POST['id']          ?? 0);

$payload = [
    'id' => $id,
];

if (array_key_exists('idUbicacion', $_POST)) {
    $payload['idUbicacion'] = intval($_POST['idUbicacion'] ?? 0);
}
if (array_key_exists('idEstado', $_POST)) {
    $payload['idEstado'] = intval($_POST['idEstado'] ?? 0);
}
if (array_key_exists('noOrden', $_POST)) {
    $payload['noOrden'] = intval($_POST['noOrden'] ?? 0);
}

// convertir datetime-local "YYYY-MM-DDTHH:MM" → "YYYY-MM-DD HH:MM:00"
$fdRaw = trim($_POST['fechaDesde'] ?? '');
$fhRaw = trim($_POST['fechaHasta'] ?? '');

if (array_key_exists('fechaDesde', $_POST)) {
    $payload['fechaDesde'] = $fdRaw ? str_replace('T', ' ', $fdRaw) . ':00' : null;
}
if (array_key_exists('fechaHasta', $_POST)) {
    $payload['fechaHasta'] = $fhRaw ? str_replace('T', ' ', $fhRaw) . ':00' : null;
}

if (!$id) {
    http_response_code(400);
    exit('ID inválido');
}

$resp = cpn_node_request(
    'POST',
    $base . '/api/banners/update',
    $token,
    $payload
);

if (!($resp['ok'] ?? false)) {
    http_response_code(($resp['_http'] ?? 500) ?: 500);
    $msg = $resp['error']['message'] ?? 'Error al actualizar banner.';
    exit($msg);
}
