<?php
declare(strict_types=1);

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

$pdo = getDbConnection();
$pageTitle = 'Memory Game';
$pageSubtitle = 'Find matching picture and word pairs';
$activeTeacherNav = 'memory';

$q = trim((string)($_GET['q'] ?? ''));
$sql = "SELECT fs.id, fs.title, fs.description, COUNT(fsw.id) AS word_count
        FROM flashcard_sets fs
        LEFT JOIN flashcard_set_words fsw ON fsw.set_id = fs.id";
$params = [];

if ($q !== '') {
    $sql .= " WHERE fs.title LIKE ? OR fs.description LIKE ?";
    $params = ["%{$q}%", "%{$q}%"];
}

$sql .= " GROUP BY fs.id, fs.title, fs.description
          HAVING COUNT(fsw.id) >= 2
          ORDER BY fs.updated_at DESC, fs.id DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$sets = $stmt->fetchAll(PDO::FETCH_ASSOC);

ob_start();
?>
<link rel="stylesheet" href="../assets/css/memory.css?v=1">

<div class="mm-manager-head">
    <div>
        <span class="section-kicker">Learning Game</span>
        <h2>Memory Game</h2>
        <p>Choose a Flashcard Set and find every picture–word pair.</p>
    </div>
    <a class="button button-secondary" href="../flashcards/">Open Flashcards</a>
</div>

<form class="mm-manager-search" method="get">
    <input
        type="search"
        name="q"
        value="<?= htmlspecialchars($q, ENT_QUOTES, 'UTF-8') ?>"
        placeholder="Search Flashcard Sets..."
    >
    <?php if ($q !== ''): ?>
        <a class="button button-secondary" href="index.php">Clear</a>
    <?php endif; ?>
</form>

<div class="mm-set-grid">
    <?php if (!$sets): ?>
        <div class="mm-empty">
            <div class="mm-empty-icon">🧠</div>
            <h3>No playable Flashcard Sets</h3>
            <p>A Memory Game needs at least two words.</p>
            <a class="button button-primary" href="../flashcards/">Create a Flashcard Set</a>
        </div>
    <?php endif; ?>

    <?php foreach ($sets as $set): ?>
        <article class="mm-set-card">
            <div class="mm-set-card-icon">🧠</div>
            <div class="mm-set-card-copy">
                <h3><?= htmlspecialchars((string)$set['title'], ENT_QUOTES, 'UTF-8') ?></h3>
                <p><?= htmlspecialchars((string)($set['description'] ?? ''), ENT_QUOTES, 'UTF-8') ?></p>
                <span><?= (int)$set['word_count'] ?> words</span>
            </div>
            <a class="button button-primary" href="play.php?set_id=<?= (int)$set['id'] ?>">Play</a>
        </article>
    <?php endforeach; ?>
</div>

<?php
$content = ob_get_clean();
require __DIR__ . '/../layouts/app.php';
