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

function h($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

$rows = [];
$error = null;

try {
  $sql = "
    SELECT j.id, j.fecha_juego, j.rasca_id, j.premio_id, j.porcentaje,
           j.ip_address, j.user_agent,
           p.nombre AS premio_nombre
    FROM jugadas_rasca j
    LEFT JOIN rasca_premios p
      ON p.id = j.premio_id AND p.rasca_id = j.rasca_id
    ORDER BY j.id DESC
    LIMIT 200
  ";
  $q = $conn->query($sql);
  if ($q) {
    $rows = $q->fetch_all(MYSQLI_ASSOC);
  } else {
    $error = 'No se pudo ejecutar la consulta de jugadas.';
  }
} catch (Throwable $e) {
  $error = $e->getMessage();
}
?>
<!doctype html>
<html lang="es"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Rasca | Jugadas</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="rasca_config.php">Config Rasca</a>
    <a class="btn btn-outline-light btn-sm" href="rasca_premios.php">Premios Rasca</a>
    <a class="btn btn-outline-light btn-sm" href="../index.php?action=logout">Salir</a>
  </div>
</div></nav>

<div class="container py-4">
  <h4 class="mb-3">Últimas jugadas (Rasca)</h4>

  <?php if ($error): ?>
    <div class="alert alert-danger"><?= h($error) ?></div>
  <?php endif; ?>

  <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>Rasca</th>
          <th>Premio</th>
          <th>%</th>
          <th>IP</th>
          <th>User Agent</th>
        </tr>
      </thead>
      <tbody>
      <?php foreach($rows as $r): ?>
        <tr>
          <td><?= (int)$r['id'] ?></td>
          <td><?= h($r['fecha_juego']) ?></td>
          <td><?= (int)$r['rasca_id'] ?></td>
          <td><?= h($r['premio_nombre'] ?: '#'.(int)$r['premio_id']) ?></td>
          <td><?= h($r['porcentaje']) ?></td>
          <td><?= h($r['ip_address'] ?? '—') ?></td>
          <td class="text-truncate" style="max-width:360px"><?= h($r['user_agent'] ?? '') ?></td>
        </tr>
      <?php endforeach; ?>
      <?php if(!$rows && !$error): ?>
        <tr><td colspan="7" class="text-center text-muted">Sin jugadas</td></tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div></div>
</div>
</body></html>
