<?php
declare(strict_types=1);

require __DIR__ . '/../partials/auth.php';
require_once __DIR__ . '/../../config/database.php';

$setId = filter_input(INPUT_GET, 'set_id', FILTER_VALIDATE_INT);
if (!$setId) {
    header('Location: index.php');
    exit;
}

$limitRaw = strtolower(trim((string)($_GET['limit'] ?? 'all')));
$requestedLimit = $limitRaw === 'all'
    ? null
    : filter_var($limitRaw, FILTER_VALIDATE_INT, ['options' => ['min_range' => 2, 'max_range' => 50]]);
$shuffleEnabled = ($_GET['shuffle'] ?? '1') !== '0';

$pdo = getDbConnection();
$setStmt = $pdo->prepare('SELECT id, title, description FROM flashcard_sets WHERE id = ? LIMIT 1');
$setStmt->execute([$setId]);
$set = $setStmt->fetch(PDO::FETCH_ASSOC);

if (!$set) {
    header('Location: index.php');
    exit;
}

$wordStmt = $pdo->prepare(
    'SELECT w.id, w.word, w.meaning_vi, w.image_path, w.audio_us_path
     FROM flashcard_set_words fsw
     INNER JOIN words w ON w.id = fsw.word_id
     WHERE fsw.set_id = ? AND w.status = ?
     ORDER BY fsw.order_no ASC, fsw.id ASC'
);
$wordStmt->execute([$setId, 'active']);
$rows = $wordStmt->fetchAll(PDO::FETCH_ASSOC);

if ($shuffleEnabled) {
    shuffle($rows);
}

if (is_int($requestedLimit) && $requestedLimit > 0) {
    $rows = array_slice($rows, 0, min($requestedLimit, count($rows)));
}

$items = array_map(
    static fn(array $row): array => [
        'id' => (int)$row['id'],
        'word' => (string)$row['word'],
        'meaning' => (string)($row['meaning_vi'] ?? ''),
        'image' => !empty($row['image_path']) ? es_url((string)$row['image_path']) : '',
        'audio' => !empty($row['audio_us_path']) ? es_url((string)$row['audio_us_path']) : '',
    ],
    $rows
);
?>
<!doctype html>
<html lang="vi">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
    <meta name="theme-color" content="#eef4ff">
    <title><?= htmlspecialchars((string)$set['title'], ENT_QUOTES, 'UTF-8') ?> | Memory</title>
    <link rel="stylesheet" href="../assets/css/memory.css?v=2">
</head>
<body class="mm-play-body">
<main class="mm-game-shell" id="memoryGame">
    <header class="mm-game-header">
        <div>
            <span>Memory Game</span>
            <h1><?= htmlspecialchars((string)$set['title'], ENT_QUOTES, 'UTF-8') ?></h1>
        </div>
        <a href="index.php" aria-label="Close game">✕</a>
    </header>

    <?php if (count($items) < 2): ?>
        <section class="mm-game-empty">
            <div>🧠</div>
            <h2>Not enough words</h2>
            <p>Add at least two words to this Flashcard Set.</p>
            <a href="../flashcards/edit.php?id=<?= (int)$setId ?>">Edit Flashcard Set</a>
        </section>
    <?php else: ?>
        <section class="mm-scorebar">
            <div><small>Pairs</small><strong id="pairScore">0 / 0</strong></div>
            <div><small>Moves</small><strong id="moveScore">0</strong></div>
            <div><small>Time</small><strong id="gameTime">00:00</strong></div>
        </section>

        <div class="mm-progress"><i id="gameProgress"></i></div>
        <p class="mm-instruction" id="gameMessage">Find the matching picture and English word.</p>

        <section class="mm-board" id="memoryBoard" aria-label="Memory cards"></section>

        <footer class="mm-game-footer">
            <button type="button" id="restartButton">↻ Restart</button>
        </footer>

        <section class="mm-finish" id="finishPanel" hidden>
            <div class="mm-finish-card">
                <div class="mm-finish-icon">🏆</div>
                <h2>Excellent!</h2>
                <p>You found every pair.</p>
                <div class="mm-final-score">
                    <span><small>Moves</small><strong id="finalMoves">0</strong></span>
                    <span><small>Time</small><strong id="finalTime">00:00</strong></span>
                </div>
                <button type="button" id="playAgainButton">Play Again</button>
                <a href="index.php">Choose another set</a>
            </div>
        </section>
    <?php endif; ?>
</main>

<?php if (count($items) >= 2): ?>
<script>
window.MEMORY_ITEMS = <?= json_encode($items, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
window.MEMORY_CONFIG = <?= json_encode(['shuffle' => $shuffleEnabled], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
</script>
<script src="../assets/js/memory.js?v=2"></script>
<?php endif; ?>
</body>
</html>
