<?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();

// → Recoger y validar campos
$idUbicacion = intval($_POST['idUbicacion'] ?? 0);
$idEstado    = intval($_POST['idEstado']    ?? 0);
$noOrden     = intval($_POST['noOrden']     ?? 0);

// → Normalizar fechas: si vienen vacías, pasamos NULL
// DESPUÉS: convertimos "YYYY-MM-DDTHH:MM" → "YYYY-MM-DD HH:MM:00"
$fdRaw = trim($_POST['fechaDesde'] ?? '');
if ($fdRaw !== '') {
    $fechaDesde = str_replace('T', ' ', $fdRaw) . ':00';
} else {
    $fechaDesde = null;
}
$fhRaw = trim($_POST['fechaHasta'] ?? '');
if ($fhRaw !== '') {
    $fechaHasta = str_replace('T', ' ', $fhRaw) . ':00';
} else {
    $fechaHasta = null;
}


if (!$idUbicacion || !$idEstado || !$noOrden) {
    die('Faltan datos obligatorios.');
}

// → Manejo de la imagen subida
if (!isset($_FILES['imagen']) || $_FILES['imagen']['error'] !== UPLOAD_ERR_OK) {
    die('Error al subir imagen.');
}

function sanitizeFileName(string $name): string
{
    // translitera acentos y caracteres especiales
    $name = iconv('UTF-8', 'ASCII//TRANSLIT', $name);
    // quita todo lo que no sea letra, número, punto o guión
    return preg_replace('/[^A-Za-z0-9\.\-]/', '', $name);
}

$originalName = $_FILES['imagen']['name'];
$safeName     = sanitizeFileName($originalName);

// → Directorio destino
$targetDir = __DIR__ . '/img/';
if (!is_dir($targetDir)) {
    mkdir($targetDir, 0755, true);
}

$destination = $targetDir . $safeName;
if (!move_uploaded_file($_FILES['imagen']['tmp_name'], $destination)) {
    die('No se pudo guardar la imagen en el servidor.');
}

// → Construir URL pública de la imagen
$protocol  = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host      = $_SERVER['HTTP_HOST'];
$urlImagen = "{$protocol}://{$host}/banners/img/{$safeName}";

// → Crear registro en Node (MySQL solo en Node)
$resp = cpn_node_request(
    'POST',
    $base . '/api/banners/create',
    $token,
    [
        'idUbicacion' => $idUbicacion,
        'idEstado' => $idEstado,
        'noOrden' => $noOrden,
        'fechaDesde' => $fechaDesde,
        'fechaHasta' => $fechaHasta,
        'urlImagen' => $urlImagen,
    ]
);

if (!($resp['ok'] ?? false)) {
    http_response_code(($resp['_http'] ?? 500) ?: 500);
    $msg = $resp['error']['message'] ?? 'Error creando banner.';
    exit($msg);
}

// → Redirigir de vuelta al listado
header('Location: listado_banners.php');
exit;
