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

function slugify($s){ $s=trim(strtolower($s)); $s=preg_replace('/[^a-z0-9-]+/','-',$s); return trim($s,'-'); }

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

if($_SERVER['REQUEST_METHOD']==='POST'){
  $pid=(int)($_POST['id']??0);
  $titulo=trim($_POST['titulo']??'');
  $slug=trim($_POST['slug']??'');
  $estado=$_POST['estado']??'borrador';
  $hero_image=trim($_POST['hero_image']??'');
  $contenido_html=$_POST['contenido_html']??'';
  $css_inline=$_POST['css_inline']??'';
  $js_inline=$_POST['js_inline']??'';
  $meta_title=trim($_POST['meta_title']??'');
  $meta_desc=trim($_POST['meta_desc']??'');
  $canonical_url=trim($_POST['canonical_url']??'');
  $game_url = trim($_POST['game_url'] ?? '');

  // (Opcional) Normaliza y valida URL
  if ($game_url !== '' && !filter_var($game_url, FILTER_VALIDATE_URL)) {
    $err = 'La URL del juego no es válida.';
  }

  if(!$err){
    if($titulo===''){ $err='El título es obligatorio.'; }
    else{
      if($slug==='') $slug=slugify($titulo);
      try{
        if($pid>0){
          $st=$conn->prepare("UPDATE landing_pages 
            SET titulo=?, slug=?, estado=?, hero_image=?, contenido_html=?, css_inline=?, js_inline=?, meta_title=?, meta_desc=?, canonical_url=?, game_url=?
            WHERE id=?");
          $st->bind_param("sssssssssssi",
            $titulo,$slug,$estado,$hero_image,$contenido_html,$css_inline,$js_inline,$meta_title,$meta_desc,$canonical_url,$game_url,$pid
          );
          $st->execute(); $msg='Landing actualizada.';
        }else{
          $st=$conn->prepare("INSERT INTO landing_pages
            (titulo,slug,estado,hero_image,contenido_html,css_inline,js_inline,meta_title,meta_desc,canonical_url,game_url)
            VALUES (?,?,?,?,?,?,?,?,?,?,?)");
          $st->bind_param("sssssssssss",
            $titulo,$slug,$estado,$hero_image,$contenido_html,$css_inline,$js_inline,$meta_title,$meta_desc,$canonical_url,$game_url
          );
          $st->execute(); $id=$conn->insert_id; $msg='Landing creada.';
        }
      }catch(Throwable $e){ $err=$e->getMessage(); }
    }
  }
}

if($action==='delete' && $id>0){
  $conn->query("DELETE FROM landing_pages WHERE id=".$id);
  $msg='Landing eliminada.'; $id=0;
}
$edit=null; if($action==='edit' && $id>0){ $edit=$conn->query("SELECT * FROM landing_pages WHERE id=".$id)->fetch_assoc(); }
$list=$conn->query("SELECT * FROM landing_pages 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 Pages | Admin</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>
  </div>
</div></nav>

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

  <div class="card mb-4"><div class="card-body">
    <h5 class="mb-3"><?= $edit?'Editar landing':'Nueva landing' ?></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">Título</label>
        <input name="titulo" class="form-control" required value="<?= htmlspecialchars($edit['titulo']??'') ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label">Slug</label>
        <input name="slug" class="form-control" value="<?= htmlspecialchars($edit['slug']??'') ?>" placeholder="mi-landing">
      </div>
      <div class="col-md-3">
        <label class="form-label">Estado</label>
        <select name="estado" class="form-select">
          <option value="borrador" <?= (($edit['estado']??'')==='borrador'?'selected':'')?>>Borrador</option>
          <option value="publicado" <?= (($edit['estado']??'')==='publicado'?'selected':'')?>>Publicado</option>
        </select>
      </div>

      <div class="col-12">
        <label class="form-label">Hero image (URL pública)</label>
        <input name="hero_image" class="form-control" value="<?= htmlspecialchars($edit['hero_image']??'') ?>" placeholder="/ruleta/uploads/landings/hero.jpg">
      </div>

      <div class="col-12">
        <label class="form-label">Contenido HTML</label>
        <textarea name="contenido_html" class="form-control" rows="8" placeholder="<section>..."></textarea>
        <script>document.getElementsByName('contenido_html')[0].value = <?= json_encode($edit['contenido_html']??'') ?>;</script>
      </div>

      <div class="col-12">
        <label class="form-label">CSS inline (opcional)</label>
        <textarea name="css_inline" class="form-control" rows="4" placeholder="/* estilos */"></textarea>
        <script>document.getElementsByName('css_inline')[0].value = <?= json_encode($edit['css_inline']??'') ?>;</script>
      </div>

      <div class="col-12">
        <label class="form-label">JS inline (opcional)</label>
        <textarea name="js_inline" class="form-control" rows="4" placeholder="// scripts"></textarea>
        <script>document.getElementsByName('js_inline')[0].value = <?= json_encode($edit['js_inline']??'') ?>;</script>
      </div>

      <div class="col-md-4">
        <label class="form-label">Meta title</label>
        <input name="meta_title" class="form-control" value="<?= htmlspecialchars($edit['meta_title']??'') ?>">
      </div>
      <div class="col-md-5">
        <label class="form-label">Meta description</label>
        <input name="meta_desc" class="form-control" value="<?= htmlspecialchars($edit['meta_desc']??'') ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label">Canonical URL</label>
        <input name="canonical_url" class="form-control" value="<?= htmlspecialchars($edit['canonical_url']??'') ?>">
      </div>

      <!-- NUEVO CAMPO: URL del juego -->
      <div class="col-md-6">
        <label class="form-label">URL del juego</label>
        <input name="game_url" class="form-control" placeholder="https://ejemplo.com/juego"
               value="<?= htmlspecialchars($edit['game_url'] ?? '') ?>">
      </div>

      <div class="col-12">
        <button class="btn btn-primary"><?= $edit?'Actualizar':'Crear' ?></button>
        <?php if($edit):?><a href="landing.php" class="btn btn-secondary">Cancelar</a><?php endif;?>
      </div>
    </form>
  </div></div>

  <div class="card"><div class="card-body table-responsive">
    <table class="table table-sm table-striped align-middle">
      <thead>
        <tr>
          <th>ID</th><th>Título</th><th>Slug</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['titulo']) ?></td>
            <td><code><?= htmlspecialchars($r['slug']) ?></code></td>
            <td><?= htmlspecialchars($r['estado']) ?></td>
            <td><?= htmlspecialchars($r['updated_at']??'') ?></td>
            <td class="text-nowrap d-flex gap-1">
              <a class="btn btn-sm btn-outline-primary" href="landing.php?action=edit&id=<?= (int)$r['id'] ?>">Editar</a>
              <a class="btn btn-sm btn-outline-danger" href="landing.php?action=delete&id=<?= (int)$r['id'] ?>" onclick="return confirm('¿Eliminar landing?')">Eliminar</a>
              <a class="btn btn-sm btn-success" target="_blank" href="../landing.php?slug=<?= urlencode($r['slug']) ?>">Ver</a>
              <?php if (!empty($r['game_url'])): ?>
                <a class="btn btn-sm btn-outline-success" target="_blank" href="<?= htmlspecialchars($r['game_url']) ?>">Juego</a>
              <?php endif; ?>
            </td>
          </tr>
        <?php endwhile; ?>
      </tbody>
    </table>
  </div></div>
</div>
</body></html>
