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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $bid   = (int)($_POST['id'] ?? 0);
  $nombre= trim($_POST['nombre'] ?? '');
  $tipo  = $_POST['tipo'] ?? 'html';
  $contenido = $_POST['contenido'] ?? '';

  if ($nombre === '' || !in_array($tipo, ['html','css','js'], true)) {
    $err = 'Nombre y tipo válidos son obligatorios.';
  } else {
    try {
      if ($bid > 0) {
        $st = $conn->prepare("UPDATE landing_blocks SET nombre=?, tipo=?, contenido=? WHERE id=?");
        $st->bind_param("sssi", $nombre, $tipo, $contenido, $bid);
        $st->execute(); $msg = 'Bloque actualizado.';
      } else {
        $st = $conn->prepare("INSERT INTO landing_blocks (nombre, tipo, contenido) VALUES (?,?,?)");
        $st->bind_param("sss", $nombre, $tipo, $contenido);
        $st->execute(); $msg = 'Bloque creado.';
      }
    } catch (Throwable $e) { $err = $e->getMessage(); }
  }
}

if ($action === 'delete' && $id > 0) {
  try {
    $conn->query("DELETE FROM landing_blocks WHERE id=".$id);
    $msg = 'Bloque eliminado.';
  } catch (Throwable $e) { $err = $e->getMessage(); }
  $id = 0;
}

$edit = null;
if ($action === 'edit' && $id > 0) {
  $rs = $conn->query("SELECT * FROM landing_blocks WHERE id=".$id);
  $edit = $rs ? $rs->fetch_assoc() : null;
}

$list = $conn->query("SELECT * FROM landing_blocks ORDER BY updated_at DESC, id DESC");
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Landing: Bloques reutilizables</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-light btn-sm" href="landing_blocks.php">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">
  <?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 bloque' : 'Nuevo bloque' ?></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">Nombre</label>
        <input name="nombre" class="form-control" required value="<?= htmlspecialchars($edit['nombre'] ?? '') ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label">Tipo</label>
        <select name="tipo" class="form-select">
          <?php $t=$edit['tipo']??'html'; ?>
          <option value="html" <?= $t==='html'?'selected':'' ?>>HTML</option>
          <option value="css"  <?= $t==='css'?'selected':'' ?>>CSS</option>
          <option value="js"   <?= $t==='js'?'selected':'' ?>>JS</option>
        </select>
      </div>
      <div class="col-12">
        <label class="form-label">Contenido</label>
        <textarea name="contenido" rows="10" class="form-control mono"><?= htmlspecialchars($edit['contenido'] ?? '') ?></textarea>
      </div>
      <div class="col-12">
        <button class="btn btn-primary"><?= $edit?'Actualizar':'Crear' ?></button>
        <?php if($edit):?><a href="landing_blocks.php" 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>Tipo</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><span class="badge text-bg-secondary"><?= htmlspecialchars($r['tipo']) ?></span></td>
            <td><?= htmlspecialchars($r['updated_at']) ?></td>
            <td class="text-nowrap">
              <a class="btn btn-sm btn-outline-primary" href="landing_blocks.php?action=edit&id=<?= (int)$r['id'] ?>">Editar</a>
              <a class="btn btn-sm btn-outline-danger" href="landing_blocks.php?action=delete&id=<?= (int)$r['id'] ?>" onclick="return confirm('¿Eliminar bloque?')">Eliminar</a>
            </td>
          </tr>
        <?php endwhile; ?>
      </tbody>
    </table>
  </div></div>
</div>
</body>
</html>
