<?php
// ruleta/admin/landing_page_blocks.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'); }

// Cargar landing
$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);

// Cargar catálogo de bloques para el <select>
$blocks_rs = $conn->query("SELECT id, nombre, tipo FROM landing_blocks ORDER BY nombre ASC");
$blocks = [];
while($b = $blocks_rs->fetch_assoc()){ $blocks[] = $b; }

// Helpers
function valid_zone($z) {
  $z = trim($z);
  if ($z==='') $z = 'main';
  // podrías limitar: ['header','main','footer','sidebar']
  return substr($z, 0, 40);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $lpb_id   = (int)($_POST['id'] ?? 0);
  $block_id = (int)($_POST['block_id'] ?? 0);
  $zona     = valid_zone($_POST['zona'] ?? 'main');
  $posicion = (int)($_POST['posicion'] ?? 1);

  if ($block_id <= 0) {
    $err = 'Debes seleccionar un bloque.';
  } else {
    try {
      if ($lpb_id > 0) {
        $st = $conn->prepare("UPDATE landing_page_blocks SET block_id=?, zona=?, posicion=? WHERE id=? AND landing_id=?");
        $st->bind_param("isiii", $block_id, $zona, $posicion, $lpb_id, $landing_id);
        $st->execute(); $msg = 'Asignación actualizada.';
      } else {
        $st = $conn->prepare("INSERT INTO landing_page_blocks (landing_id, block_id, zona, posicion) VALUES (?,?,?,?)");
        $st->bind_param("iisi", $landing_id, $block_id, $zona, $posicion);
        $st->execute(); $msg = 'Bloque asignado a la landing.';
      }
    } catch (Throwable $e) { $err = $e->getMessage(); }
  }
}

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

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

// Listado agrupado por zona y ordenado por posición
$list = $conn->query("
  SELECT lpb.id, lpb.block_id, lpb.zona, lpb.posicion,
         lb.nombre, lb.tipo
  FROM landing_page_blocks lpb
  JOIN landing_blocks lb ON lb.id = lpb.block_id
  WHERE lpb.landing_id = {$landing_id}
  ORDER BY lpb.zona ASC, lpb.posicion ASC, lpb.id ASC
");
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Landing: Asignar Bloques</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_blocks.php">Bloques</a>
      <a class="btn btn-outline-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-light btn-sm" href="landing_page_blocks.php?landing_id=<?= (int)$landing_id ?>">Asignar bloques</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> <small class="text-muted">(#<?= (int)$landing_id ?>)</small></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 asignación' : 'Nueva asignación' ?></h5>
    <form method="post" class="row g-3">
      <input type="hidden" name="id" value="<?= (int)($edit['id'] ?? 0) ?>">

      <div class="col-md-6">
        <label class="form-label">Bloque</label>
        <select name="block_id" class="form-select" required>
          <option value="">— Selecciona —</option>
          <?php
          $sel_block = (int)($edit['block_id'] ?? 0);
          foreach ($blocks as $b):
          ?>
            <option value="<?= (int)$b['id'] ?>" <?= $sel_block===(int)$b['id']?'selected':'' ?>>
              [<?= htmlspecialchars(strtoupper($b['tipo'])) ?>] <?= htmlspecialchars($b['nombre']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="col-md-3">
        <label class="form-label">Zona</label>
        <input name="zona" class="form-control" placeholder="main / header / footer" value="<?= htmlspecialchars($edit['zona'] ?? 'main') ?>">
      </div>

      <div class="col-md-3">
        <label class="form-label">Posición</label>
        <input name="posicion" type="number" class="form-control" value="<?= htmlspecialchars((string)($edit['posicion'] ?? '1')) ?>">
      </div>

      <div class="col-12">
        <button class="btn btn-primary"><?= $edit ? 'Actualizar' : 'Asignar' ?></button>
        <?php if($edit):?><a href="landing_page_blocks.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">
      <h5 class="mb-3">Bloques asignados</h5>
      <table class="table table-sm table-striped align-middle">
        <thead>
          <tr>
            <th>ID</th>
            <th>Bloque</th>
            <th>Tipo</th>
            <th>Zona</th>
            <th>Posición</th>
            <th>Acciones</th>
          </tr>
        </thead>
        <tbody>
        <?php if ($list && $list->num_rows): while($r = $list->fetch_assoc()): ?>
          <tr>
            <td><?= (int)$r['id'] ?></td>
            <td><?= htmlspecialchars($r['nombre']) ?></td>
            <td><span class="badge text-bg-secondary"><?= htmlspecialchars($r['tipo']) ?></span></td>
            <td><code><?= htmlspecialchars($r['zona']) ?></code></td>
            <td><?= (int)$r['posicion'] ?></td>
            <td class="text-nowrap">
              <a class="btn btn-sm btn-outline-primary" href="landing_page_blocks.php?landing_id=<?= (int)$landing_id ?>&action=edit&id=<?= (int)$r['id'] ?>">Editar</a>
              <a class="btn btn-sm btn-outline-danger" href="landing_page_blocks.php?landing_id=<?= (int)$landing_id ?>&action=delete&id=<?= (int)$r['id'] ?>" onclick="return confirm('¿Eliminar asignación?')">Eliminar</a>
            </td>
          </tr>
        <?php endwhile; else: ?>
          <tr><td colspan="6" class="text-center text-muted">Sin bloques asignados</td></tr>
        <?php endif; ?>
        </tbody>
      </table>
      <p class="text-muted small mb-0">* Sugerencia: usa zonas como <code>header</code>, <code>main</code>, <code>footer</code> o <code>sidebar</code>, y ordena con <strong>posiciones</strong> (1,2,3...).</p>
    </div>
  </div>
</div>
</body>
</html>
