<?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);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $vid   = (int)($_POST['id'] ?? 0);
  $nombre= trim($_POST['nombre'] ?? '');
  $peso  = (float)($_POST['peso'] ?? 1.0);
  $estado= $_POST['estado'] ?? 'activo';
  $hero_image = trim($_POST['hero_image'] ?? '');
  $contenido_html = $_POST['contenido_html'] ?? '';
  $css_inline = $_POST['css_inline'] ?? '';
  $js_inline  = $_POST['js_inline'] ?? '';

  if ($nombre === '' || !in_array($estado, ['borrador','activo','pausado'], true)) {
    $err = 'Nombre y estado válidos son obligatorios.';
  } else {
    try {
      if ($vid > 0) {
        $st = $conn->prepare("UPDATE landing_variants SET nombre=?, peso=?, estado=?, hero_image=?, contenido_html=?, css_inline=?, js_inline=? WHERE id=? AND landing_id=?");
        $st->bind_param("sdssssiii", $nombre, $peso, $estado, $hero_image, $contenido_html, $css_inline, $js_inline, $vid, $landing_id);
        $st->execute(); $msg = 'Variante actualizada.';
      } else {
        $st = $conn->prepare("INSERT INTO landing_variants (landing_id, nombre, peso, estado, hero_image, contenido_html, css_inline, js_inline) VALUES (?,?,?,?,?,?,?,?)");
        $st->bind_param("isdsssss", $landing_id, $nombre, $peso, $estado, $hero_image, $contenido_html, $css_inline, $js_inline);
        $st->execute(); $msg = 'Variante creada.';
      }
    } catch (Throwable $e) { $err = $e->getMessage(); }
  }
}

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

$edit = null;
if ($action === 'edit' && $id > 0) {
  $st = $conn->prepare("SELECT * FROM landing_variants 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_variants WHERE landing_id=".$landing_id." ORDER BY id DESC");
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Landing: Variantes</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>.mono{font-family:ui-monospace,Menlo,Consolas,monospace;white-space:pre-wrap}</style>
</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_blocks.php">Bloques</a>
      <a class="btn btn-light btn-sm" href="landing_variants.php?landing_id=<?= (int)$landing_id ?>">Variantes</a>
      <a class="btn btn-outline-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 variante' : 'Nueva variante' ?></h5>
    <form method="post" class="row g-3">
      <input type="hidden" name="id" value="<?= (int)($edit['id'] ?? 0) ?>">
      <div class="col-md-5">
        <label class="form-label">Nombre</label>
        <input name="nombre" class="form-control" required value="<?= htmlspecialchars($edit['nombre'] ?? '') ?>">
      </div>
      <div class="col-md-2">
        <label class="form-label">Peso (tráfico)</label>
        <input name="peso" type="number" step="0.001" min="0" class="form-control" value="<?= htmlspecialchars((string)($edit['peso'] ?? '1.000')) ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label">Estado</label>
        <?php $est = $edit['estado'] ?? 'activo'; ?>
        <select name="estado" class="form-select">
          <option value="borrador" <?= $est==='borrador'?'selected':'' ?>>Borrador</option>
          <option value="activo"   <?= $est==='activo'?'selected':'' ?>>Activo</option>
          <option value="pausado"  <?= $est==='pausado'?'selected':'' ?>>Pausado</option>
        </select>
      </div>
      <div class="col-12">
        <label class="form-label">Hero image (URL)</label>
        <input name="hero_image" class="form-control" placeholder="/ruleta/uploads/landings/hero-b.jpg" value="<?= htmlspecialchars($edit['hero_image'] ?? '') ?>">
      </div>
      <div class="col-12">
        <label class="form-label">Contenido HTML (override)</label>
        <textarea name="contenido_html" rows="6" class="form-control mono"><?= htmlspecialchars($edit['contenido_html'] ?? '') ?></textarea>
      </div>
      <div class="col-12">
        <label class="form-label">CSS inline (override)</label>
        <textarea name="css_inline" rows="4" class="form-control mono"><?= htmlspecialchars($edit['css_inline'] ?? '') ?></textarea>
      </div>
      <div class="col-12">
        <label class="form-label">JS inline (override)</label>
        <textarea name="js_inline" rows="4" class="form-control mono"><?= htmlspecialchars($edit['js_inline'] ?? '') ?></textarea>
      </div>
      <div class="col-12">
        <button class="btn btn-primary"><?= $edit?'Actualizar':'Crear' ?></button>
        <?php if($edit):?><a href="landing_variants.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>Nombre</th><th>Peso</th><th>Estado</th><th>Actualizado</th><th>Acciones</th></tr></thead>
      <tbody>
        <?php while($r = $list->fetch_assoc()): ?>
          <tr>
            <td><?= (int)$r['id'] ?></td>
            <td><?= htmlspecialchars($r['nombre']) ?></td>
            <td><?= htmlspecialchars($r['peso']) ?></td>
            <td><span class="badge text-bg-secondary"><?= htmlspecialchars($r['estado']) ?></span></td>
            <td><?= htmlspecialchars($r['updated_at']) ?></td>
            <td class="text-nowrap">
              <a class="btn btn-sm btn-outline-primary" href="landing_variants.php?landing_id=<?= (int)$landing_id ?>&action=edit&id=<?= (int)$r['id'] ?>">Editar</a>
              <a class="btn btn-sm btn-outline-danger" href="landing_variants.php?landing_id=<?= (int)$landing_id ?>&action=delete&id=<?= (int)$r['id'] ?>" onclick="return confirm('¿Eliminar variante?')">Eliminar</a>
            </td>
          </tr>
        <?php endwhile; ?>
      </tbody>
    </table>
  </div></div>
</div>
</body>
</html>
