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

/** Cargar ruletas (id, nombre) */
function all_ruletas(mysqli $conn): array {
  $res = $conn->query("SELECT id, nombre FROM ruletas ORDER BY id DESC");
  return $res ? $res->fetch_all(MYSQLI_ASSOC) : [];
}

/** Helper para bind dinámico (mysqli requiere referencias) */
function stmt_bind_params(mysqli_stmt $stmt, string $types, array &$params): void {
  if ($types === '' || !$params) return;
  $bind = [$types];
  foreach ($params as $k => $v) { $bind[] = &$params[$k]; }
  call_user_func_array([$stmt, 'bind_param'], $bind);
}

$ruletas   = all_ruletas($conn);
$ruleta_id = (int)($_GET['ruleta_id'] ?? 0);
$q         = trim((string)($_GET['q'] ?? ''));
$desde     = (string)($_GET['desde'] ?? '');
$hasta     = (string)($_GET['hasta'] ?? '');

$where  = "1=1";
$params = [];
$types  = "";

// Filtros
if ($ruleta_id) {
  $where .= " AND j.ruleta_id=?";
  $types .= "i";
  $params[] = $ruleta_id;
}
if ($q !== '') {
  $where .= " AND (p.nombre LIKE CONCAT('%',?,'%') OR j.ip_address LIKE CONCAT('%',?,'%'))";
  $types  .= "ss";
  $params[] = $q;
  $params[] = $q;
}
if ($desde !== '') {
  $where .= " AND j.fecha_juego >= ?";
  $types  .= "s";
  $params[] = $desde . " 00:00:00";
}
if ($hasta !== '') {
  $where .= " AND j.fecha_juego <= ?";
  $types  .= "s";
  $params[] = $hasta . " 23:59:59";
}

// Export CSV
if (($_GET['export'] ?? '') === 'csv') {
  header('Content-Type: text/csv; charset=utf-8');
  header('Content-Disposition: attachment; filename=jugadas.csv');
  $out = fopen('php://output', 'w');
  fputcsv($out, ['ID','Fecha','Ruleta','Premio','IP','User Agent']);

  $sql = "SELECT j.id, j.fecha_juego, r.nombre AS ruleta, p.nombre AS premio, j.ip_address, j.user_agent
          FROM jugadas j
          LEFT JOIN ruletas r ON r.id=j.ruleta_id
          LEFT JOIN premios p ON p.id=j.premio_id
          WHERE $where
          ORDER BY j.id DESC";
  $stmt = $conn->prepare($sql);
  stmt_bind_params($stmt, $types, $params);
  $stmt->execute();
  $res = $stmt->get_result();
  while ($row = $res->fetch_assoc()) {
    fputcsv($out, [
      $row['id'],
      $row['fecha_juego'],
      $row['ruleta'],
      $row['premio'],
      $row['ip_address'],
      $row['user_agent']
    ]);
  }
  fclose($out);
  exit;
}

// Paginación
$page = max(1, (int)($_GET['page'] ?? 1));
$pp   = 25;
$off  = ($page - 1) * $pp;

// Total
$sqlCount = "SELECT COUNT(*) c
             FROM jugadas j
             LEFT JOIN ruletas r ON r.id=j.ruleta_id
             LEFT JOIN premios p ON p.id=j.premio_id
             WHERE $where";
$stmt = $conn->prepare($sqlCount);
stmt_bind_params($stmt, $types, $params);
$stmt->execute();
$total = (int)$stmt->get_result()->fetch_assoc()['c'];

// Página actual
$sql = "SELECT j.id, j.fecha_juego, r.nombre AS ruleta, p.nombre AS premio, j.ip_address, j.user_agent
        FROM jugadas j
        LEFT JOIN ruletas r ON r.id=j.ruleta_id
        LEFT JOIN premios p ON p.id=j.premio_id
        WHERE $where
        ORDER BY j.id DESC
        LIMIT $pp OFFSET $off";
$stmt = $conn->prepare($sql);
stmt_bind_params($stmt, $types, $params);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$pages = (int)ceil($total / $pp);

// Query para export sin "page"
$exportQuery = $_GET;
unset($exportQuery['page']);
$exportQuery['export'] = 'csv';
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <title>Jugadas | Admin Ruletas</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-lg bg-dark navbar-dark">
  <div class="container-fluid">
    <a class="navbar-brand" href="dashboard.php">Home</a>
    <div class="d-flex gap-2">
      <a class="btn btn-outline-light btn-sm" href="ruletas.php">Ruletas</a>
      <a class="btn btn-outline-light btn-sm" href="premios.php">Premios</a>
    </div>
  </div>
</nav>

<div class="container py-4">
  <h3 class="mb-3">Historial de Jugadas</h3>

  <form class="row g-2 mb-3" method="get">
    <div class="col-md-3">
      <label class="form-label">Ruleta</label>
      <select name="ruleta_id" class="form-select">
        <option value="">Todas</option>
        <?php foreach ($ruletas as $ru): ?>
          <?php $rid = (int)$ru['id']; ?>
          <option value="<?= $rid ?>" <?= $ruleta_id == $rid ? 'selected' : '' ?>>
            <?= htmlspecialchars($ru['nombre']) ?> (ID <?= $rid ?>)
          </option>
        <?php endforeach; ?>
      </select>
    </div>

    <div class="col-md-2">
      <label class="form-label">Desde</label>
      <input type="date" name="desde" class="form-control" value="<?= htmlspecialchars($desde) ?>">
    </div>

    <div class="col-md-2">
      <label class="form-label">Hasta</label>
      <input type="date" name="hasta" class="form-control" value="<?= htmlspecialchars($hasta) ?>">
    </div>

    <div class="col-md-3">
      <label class="form-label">Buscar (premio/IP)</label>
      <input type="text" name="q" class="form-control" value="<?= htmlspecialchars($q) ?>" placeholder="Premio, 192.168...">
    </div>

    <div class="col-md-2 d-flex align-items-end gap-2">
      <button class="btn btn-primary w-100">Filtrar</button>
      <a class="btn btn-outline-secondary" href="jugadas.php">Limpiar</a>
    </div>

    <div class="col-12">
      <a class="btn btn-success btn-sm" href="jugadas.php?<?= http_build_query($exportQuery) ?>">Exportar CSV</a>
    </div>
  </form>

  <div class="card shadow-sm">
    <div class="card-body table-responsive">
      <table class="table table-striped table-sm align-middle">
        <thead>
          <tr>
            <th>ID</th><th>Fecha</th><th>Ruleta</th><th>Premio</th><th>IP</th><th>User Agent</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($rows as $row): ?>
          <tr>
            <td><?= (int)$row['id'] ?></td>
            <td><?= htmlspecialchars($row['fecha_juego']) ?></td>
            <td><?= htmlspecialchars($row['ruleta'] ?? '—') ?></td>
            <td><?= htmlspecialchars($row['premio'] ?? '—') ?></td>
            <td><?= htmlspecialchars($row['ip_address'] ?? '—') ?></td>
            <td class="text-truncate" style="max-width:400px;" title="<?= htmlspecialchars($row['user_agent'] ?? '') ?>">
              <?= htmlspecialchars($row['user_agent'] ?? '') ?>
            </td>
          </tr>
          <?php endforeach; ?>
          <?php if (!$rows): ?>
            <tr><td colspan="6" class="text-center text-muted">Sin registros</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <?php if ($pages > 1): ?>
  <nav class="mt-3">
    <ul class="pagination pagination-sm">
      <?php for ($i = 1; $i <= $pages; $i++): ?>
        <li class="page-item <?= $i == $page ? 'active' : '' ?>">
          <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $i])) ?>"><?= $i ?></a>
        </li>
      <?php endfor; ?>
    </ul>
  </nav>
  <?php endif; ?>
</div>
</body>
</html>
