<?php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . '/../../includes/student_auth.php';
require_once __DIR__ . '/../../includes/db.php';

$mysqli = $mysqli ?? ($conn ?? null);
if (!$mysqli instanceof mysqli) die('DB missing');

$student_id = (int)($_SESSION['student_id'] ?? 0);

function e($v){ return htmlspecialchars((string)$v, ENT_QUOTES); }

$sql = "
SELECT *
FROM lms_game_attempts
WHERE student_id = ?
ORDER BY finished_at DESC
";

$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i', $student_id);
$stmt->execute();
$res = $stmt->get_result();

$rows = [];
while ($r = $res->fetch_assoc()) $rows[] = $r;
?>

<!doctype html>
<html>
<head>
<title>My Game Attempts</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body class="bg-light">

<div class="container py-4">

<h3 class="mb-3">🎮 My Game Attempts</h3>

<div class="card">
<div class="card-body table-responsive">

<table class="table table-bordered align-middle">
<thead class="table-light">
<tr>
<th>#</th>
<th>Game</th>
<th>Score</th>
<th>Percent</th>
<th>Time</th>
<th>Status</th>
<th>Date</th>
</tr>
</thead>

<tbody>
<?php if (!$rows): ?>
<tr><td colspan="7" class="text-center text-muted">No attempts yet</td></tr>
<?php else: ?>

<?php foreach ($rows as $i => $r): ?>
<tr>
<td><?= $i+1 ?></td>

<td>#<?= (int)$r['game_id'] ?></td>

<td>
<strong><?= (int)$r['score'] ?></strong> / <?= (int)$r['total'] ?>
</td>

<td><?= (float)$r['percent'] ?>%</td>

<td><?= (int)$r['time_sec'] ?>s</td>

<td>
<?php if ($r['success']): ?>
<span class="badge bg-success">PASS</span>
<?php else: ?>
<span class="badge bg-danger">FAIL</span>
<?php endif; ?>
</td>

<td><?= e($r['finished_at']) ?></td>

</tr>
<?php endforeach; ?>

<?php endif; ?>
</tbody>
</table>

</div>
</div>

</div>

</body>
</html>