<?php
require 'conex.php';
header('Content-Type: application/json');

$id = trim($_POST['id'] ?? '');
$marca = trim($_POST['marca'] ?? '');
$zona = trim($_POST['zona'] ?? '');
$canton = trim($_POST['canton'] ?? '');
$video = trim($_POST['video'] ?? '');
$fechaini = trim($_POST['fechaini'] ?? '');
$fechafin = trim($_POST['fechafin'] ?? '');
$activo = intval($_POST['activo'] ?? 0);

// Validaciones básicas
if ($marca === '' || $zona === '' || $canton === '' || $video === '' || $fechaini === '' || $fechafin === '') {
  echo json_encode(['success' => false, 'message' => 'Campos vacíos.']);
  exit;
}

try {
  if ($id === '') {
    // Insertar nueva publicidad
    $stmt = $conex->prepare("INSERT INTO tb_publicidad (id_marca, id_zona, id_canton, id_video, fecha_inicio, fecha_fin, activo) 
                              VALUES ((SELECT id FROM tb_marca WHERE nombre_marca = ? LIMIT 1),
                                      (SELECT id FROM tb_zona WHERE zona = ? LIMIT 1),
                                      (SELECT id FROM tb_canton WHERE canton = ? LIMIT 1),
                                      (SELECT id FROM tb_video WHERE video = ? LIMIT 1), ?, ?, ?)");
    $stmt->execute([$marca, $zona, $canton, $video, $fechaini, $fechafin, $activo]);
  } else {
    // Actualizar publicidad existente
    $stmt = $conex->prepare("UPDATE tb_publicidad 
                             SET id_marca = (SELECT id FROM tb_marca WHERE nombre_marca = ? LIMIT 1),
                                 id_zona = (SELECT id FROM tb_zona WHERE zona = ? LIMIT 1),
                                 id_canton = (SELECT id FROM tb_canton WHERE canton = ? LIMIT 1),
                                 id_video = (SELECT id FROM tb_video WHERE video = ? LIMIT 1),
                                 fecha_inicio = ?, fecha_fin = ?, activo = ?
                             WHERE id = ?");
    $stmt->execute([$marca, $zona, $canton, $video, $fechaini, $fechafin, $activo, $id]);
  }
  
  echo json_encode(['success' => true]);
} catch (PDOException $e) {
  echo json_encode(['success' => false, 'message' => 'Error en la base de datos: ' . $e->getMessage()]);
}
