<?php
// ruleta/admin/landing_crm.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 id,titulo 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') {
  $hid   = (int)($_POST['id'] ?? 0);
  $nombre= trim($_POST['nombre'] ?? '');
  $endpoint = trim($_POST['endpoint'] ?? '');
  $method   = $_POST['method'] ?? 'POST';
  $secret   = trim($_POST['secret'] ?? '');
  $active   = isset($_POST['active']) ? 1 : 0;

  if ($nombre === '' || $endpoint === '' || !in_array($method, ['POST','GET'], true)) {
    $err = 'Nombre, endpoint y método (POST/GET) son obligatorios.';
  } else {
    try {
      if ($hid > 0) {
        $st = $conn->prepare("UPDATE landing_crm_hooks SET nombre=?, endpoint=?, method=?, secret=?, active=? WHERE id=? AND landing_id=?");
        $st->bind_param("ssssiii", $nombre, $endpoint, $method, $secret, $active, $hid, $landing_id);
        $st->execute(); $msg = 'Hook actualizado.';
      } else {
        $st = $conn->prepare("INSERT INTO landing_crm_hooks (landing_id, nombre, endpoint, method, secret, active) VALUES (?,?,?,?,?,?)");
        $st->bind_param("issssi", $landing_id, $nombre, $endpoint, $method, $secret, $active);
        $st->execute(); $msg = 'Hook creado.';
      }
    } catch (Throwable $e) { $err = $e->getMessage(); }
  }
}

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

$edit = null;
if ($action === 'edit' && $id > 0) {
  $st = $conn->prepare("SELECT * FROM landing_crm_hooks 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_crm_hooks 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 CRM Hooks</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-light btn-sm" href="landing_crm.php?landing_id=<?= (int)$landing_id ?>">CRM Hooks</a>
      <a class="btn btn-outline-light btn-sm" href="landing_forms.php?landing_id=<?= (int)$landing_id ?>">Leads</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> (#<?= (int)$landing_id ?>)</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 hook' : 'Nuevo hook' ?></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">Nombre</label>
        <input name="nombre" class="form-control" required value="<?= htmlspecialchars($edit['nombre'] ?? '') ?>">
      </div>
      <div class="col-md-6">
        <label class="form-label">Endpoint (URL)</label>
        <input name="endpoint" class="form-control" required placeholder="https://hooks.zapier.com/..." value="<?= htmlspecialchars($edit['endpoint'] ?? '') ?>">
      </div>
      <div class="col-md-2">
        <label class="form-label">Método</label>
        <?php $m=$edit['method']??'POST'; ?>
        <select name="method" class="form-select">
          <option value="POST" <?= $m==='POST'?'selected':'' ?>>POST</option>
          <option value="GET"  <?= $m==='GET' ?'selected':'' ?>>GET</option>
        </select>
      </div>
      <div class="col-md-8">
        <label class="form-label">Secret / Bearer (opcional)</label>
        <input name="secret" class="form-control" placeholder="Se enviará como Authorization: Bearer ..." value="<?= htmlspecialchars($edit['secret'] ?? '') ?>">
      </div>
      <div class="col-md-4 d-flex align-items-end">
        <div class="form-check">
          <input class="form-check-input" type="checkbox" id="active" name="active" <?= (isset($edit['active']) ? (intval($edit['active']) ? 'checked' : '') : 'checked') ?>>
          <label class="form-check-label" for="active">Activo</label>
        </div>
      </div>
      <div class="col-12">
        <button class="btn btn-primary"><?= $edit?'Actualizar':'Crear' ?></button>
        <?php if($edit):?><a href="landing_crm.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>Endpoint</th><th>Método</th><th>Activo</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><code><?= htmlspecialchars($r['endpoint']) ?></code></td>
            <td><span class="badge text-bg-secondary"><?= htmlspecialchars($r['method']) ?></span></td>
            <td><?= intval($r['active']) ? 'Sí' : 'No' ?></td>
            <td class="text-nowrap">
              <a class="btn btn-sm btn-outline-primary" href="landing_crm.php?landing_id=<?= (int)$landing_id ?>&action=edit&id=<?= (int)$r['id'] ?>">Editar</a>
              <a class="btn btn-sm btn-outline-danger" href="landing_crm.php?landing_id=<?= (int)$landing_id ?>&action=delete&id=<?= (int)$r['id'] ?>" onclick="return confirm('¿Eliminar hook?')">Eliminar</a>
            </td>
          </tr>
        <?php endwhile; if(!$list || !$list->num_rows): ?>
          <tr><td colspan="6" class="text-center text-muted">Sin hooks configurados</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div></div>
</div>
</body>
</html>
