<?php
session_start();
require_once __DIR__ . '/db.php';
if (empty($_SESSION['admin_id'])) { header('Location: ../index.php'); exit; }

$landing_id = (int)($_GET['landing_id'] ?? 0);
if ($landing_id <= 0) { die('landing_id requerido'); }

$landing = $conn->query("SELECT * FROM landing_pages WHERE id=".$landing_id)->fetch_assoc();
if (!$landing) { die('Landing no existe'); }

$msg = $err = '';
$action = $_GET['action'] ?? '';
$id = (int)($_GET['id'] ?? 0);

function to_mysql_dt($s) {
  // recibe "YYYY-MM-DDTHH:MM" y devuelve "YYYY-MM-DD HH:MM:00" o NULL
  $s = trim((string)$s);
  if ($s === '') return null;
  $s = str_replace('T',' ',$s);
  if (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}/',$s)) return $s.':00';
  return null;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $sid  = (int)($_POST['id'] ?? 0);
  $start= to_mysql_dt($_POST['start_at'] ?? '');
  $end  = to_mysql_dt($_POST['end_at'] ?? '');
  $estado = $_POST['estado'] ?? 'programada';

  if (!in_array($estado, ['programada','activa','finalizada'], true)) {
    $err = 'Estado inválido.';
  } else {
    try {
      if ($sid > 0) {
        $st = $conn->prepare("UPDATE landing_schedule SET start_at=?, end_at=?, estado=? WHERE id=? AND landing_id=?");
        $st->bind_param("sssii", $start, $end, $estado, $sid, $landing_id);
        $st->execute(); $msg = 'Rango actualizado.';
      } else {
        $st = $conn->prepare("INSERT INTO landing_schedule (landing_id,start_at,end_at,estado) VALUES (?,?,?,?)");
        $st->bind_param("isss", $landing_id, $start, $end, $estado);
        $st->execute(); $msg = 'Rango creado.';
      }
    } catch (Throwable $e) { $err = $e->getMessage(); }
  }
}

if ($action === 'delete' && $id > 0) {
  try {
    $st = $conn->prepare("DELETE FROM landing_schedule WHERE id=? AND landing_id=?");
    $st->bind_param("ii", $id, $landing_id);
    $st->execute(); $msg = 'Rango eliminado.';
  } catch (Throwable $e) { $err = $e->getMessage(); }
  $id = 0;
}

$edit = null;
if ($action === 'edit' && $id > 0) {
  $st = $conn->prepare("SELECT * FROM landing_schedule WHERE id=? AND landing_id=?");
  $st->bind_param("ii", $id, $landing_id);
  $st->execute();
  $edit = $st->get_result()->fetch_assoc();
}

$list = $conn->query("SELECT * FROM landing_schedule WHERE landing_id=".$landing_id." ORDER BY start_at ASC, id ASC");

// helpers para mostrar en datetime-local
function to_input_dt($s) {
  if (!$s) return '';
  $s = str_replace(' ', 'T', substr($s,0,16));
  return $s;
}
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Landing: Schedule</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-dark bg-dark">
  <div class="container-fluid">
    <a class="navbar-brand" href="dashboard.php">Admin</a>
    <div class="d-flex gap-2">
      <a class="btn btn-outline-light btn-sm" href="landing.php">Landings</a>
      <a class="btn btn-outline-light btn-sm" href="landing_variants.php?landing_id=<?= (int)$landing_id ?>">Variantes</a>
      <a class="btn btn-light btn-sm" href="landing_schedule.php?landing_id=<?= (int)$landing_id ?>">Schedule</a>
      <a class="btn btn-outline-light btn-sm" href="../index.php?action=logout">Salir</a>
    </div>
  </div>
</nav>

<div class="container py-4">
  <div class="mb-3">
    <a class="btn btn-secondary btn-sm" href="landing.php">← Volver a Landings</a>
  </div>

  <h4 class="mb-3">Landing: <strong><?= htmlspecialchars($landing['titulo']) ?></strong></h4>

  <?php if($msg):?><div class="alert alert-success py-2"><?= htmlspecialchars($msg) ?></div><?php endif;?>
  <?php if($err):?><div class="alert alert-danger py-2"><?= htmlspecialchars($err) ?></div><?php endif;?>

  <div class="card shadow-sm mb-4"><div class="card-body">
    <h5 class="mb-3"><?= $edit ? 'Editar rango' : 'Nuevo rango' ?></h5>
    <form method="post" class="row g-3">
      <input type="hidden" name="id" value="<?= (int)($edit['id'] ?? 0) ?>">
      <div class="col-md-4">
        <label class="form-label">Inicio</label>
        <input type="datetime-local" name="start_at" class="form-control" value="<?= htmlspecialchars(to_input_dt($edit['start_at'] ?? '')) ?>">
      </div>
      <div class="col-md-4">
        <label class="form-label">Fin</label>
        <input type="datetime-local" name="end_at" class="form-control" value="<?= htmlspecialchars(to_input_dt($edit['end_at'] ?? '')) ?>">
      </div>
      <div class="col-md-4">
        <label class="form-label">Estado</label>
        <?php $est=$edit['estado']??'programada'; ?>
        <select name="estado" class="form-select">
          <option value="programada" <?= $est==='programada'?'selected':'' ?>>Programada</option>
          <option value="activa"     <?= $est==='activa'?'selected':'' ?>>Activa</option>
          <option value="finalizada" <?= $est==='finalizada'?'selected':'' ?>>Finalizada</option>
        </select>
      </div>
      <div class="col-12">
        <button class="btn btn-primary"><?= $edit?'Actualizar':'Crear' ?></button>
        <?php if($edit):?><a href="landing_schedule.php?landing_id=<?= (int)$landing_id ?>" class="btn btn-secondary">Cancelar</a><?php endif;?>
      </div>
    </form>
  </div></div>

  <div class="card shadow-sm"><div class="card-body table-responsive">
    <table class="table table-sm table-striped align-middle">
      <thead><tr><th>ID</th><th>Inicio</th><th>Fin</th><th>Estado</th><th>Acciones</th></tr></thead>
      <tbody>
        <?php while($r = $list->fetch_assoc()): ?>
          <tr>
            <td><?= (int)$r['id'] ?></td>
            <td><?= htmlspecialchars($r['start_at'] ?? '—') ?></td>
            <td><?= htmlspecialchars($r['end_at'] ?? '—') ?></td>
            <td><span class="badge text-bg-secondary"><?= htmlspecialchars($r['estado']) ?></span></td>
            <td class="text-nowrap">
              <a class="btn btn-sm btn-outline-primary" href="landing_schedule.php?landing_id=<?= (int)$landing_id ?>&action=edit&id=<?= (int)$r['id'] ?>">Editar</a>
              <a class="btn btn-sm btn-outline-danger" href="landing_schedule.php?landing_id=<?= (int)$landing_id ?>&action=delete&id=<?= (int)$r['id'] ?>" onclick="return confirm('¿Eliminar rango?')">Eliminar</a>
            </td>
          </tr>
        <?php endwhile; ?>
      </tbody>
    </table>
  </div></div>
</div>
</body>
</html>
