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

$rows = [];
$st = $conn->prepare("
  SELECT lv.id AS variant_id, COALESCE(lv.nombre,'Base') AS nombre,
         SUM(lvs.event_type='impression') AS impresiones,
         SUM(lvs.event_type='conversion') AS conversiones
  FROM landing_variant_stats lvs
  LEFT JOIN landing_variants lv ON lv.id=lvs.variant_id
  WHERE lvs.landing_id=?
  GROUP BY lvs.variant_id, lv.nombre
  ORDER BY impresiones DESC
");
$st->bind_param('i',$landing_id);
$st->execute();
$res = $st->get_result();
while($r=$res->fetch_assoc()){
  $r['cr'] = $r['impresiones'] ? round(100*$r['conversiones']/$r['impresiones'],2) : 0.0;
  $rows[] = $r;
}
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Landing: Stats</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
</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_stats.php?landing_id=<?= (int)$landing_id ?>">Stats</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">Stats: <strong><?= htmlspecialchars($landing['titulo']) ?></strong></h4>

  <div class="card mb-4"><div class="card-body">
    <canvas id="chart"></canvas>
  </div></div>

  <div class="card"><div class="card-body table-responsive">
    <table class="table table-sm table-striped align-middle">
      <thead><tr><th>Variante</th><th>Impresiones</th><th>Conversiones</th><th>CR %</th></tr></thead>
      <tbody>
        <?php foreach($rows as $r): ?>
          <tr>
            <td><?= htmlspecialchars($r['nombre'] ?? 'Base') ?></td>
            <td><?= (int)$r['impresiones'] ?></td>
            <td><?= (int)$r['conversiones'] ?></td>
            <td><?= number_format($r['cr'],2) ?></td>
          </tr>
        <?php endforeach; ?>
        <?php if(!$rows): ?><tr><td colspan="4" class="text-center text-muted">Sin datos</td></tr><?php endif; ?>
      </tbody>
    </table>
  </div></div>
</div>

<script>
const data = <?= json_encode($rows, JSON_UNESCAPED_UNICODE) ?>;
const labels = data.map(r => r.nombre || 'Base');
const imps   = data.map(r => +r.impresiones);
const convs  = data.map(r => +r.conversiones);
const cr     = data.map(r => +r.cr);

new Chart(document.getElementById('chart'), {
  type: 'bar',
  data: {
    labels,
    datasets: [
      { label: 'Impresiones', data: imps },
      { label: 'Conversiones', data: convs },
      { label: 'CR %', data: cr, yAxisID: 'y1', type: 'line' }
    ]
  },
  options: {
    responsive: true,
    scales: {
      y:  { beginAtZero: true, title:{display:true,text:'Impresiones / Conversiones'} },
      y1: { beginAtZero: true, position:'right', title:{display:true,text:'CR %'} }
    }
  }
});
</script>
</body>
</html>
