<?php
// /elms/student/games/games.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('Database connection not found.');
}

$mysqli->set_charset('utf8mb4');

$PAGE_TITLE = 'Games / Activities';
$ACTIVE     = 'games';

if (!function_exists('esc_game')) {
    function esc_game($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

if (!function_exists('game_tbl_exists')) {
    function game_tbl_exists(mysqli $db, string $table): bool
    {
        $stmt = $db->prepare("
            SELECT 1 
            FROM INFORMATION_SCHEMA.TABLES 
            WHERE TABLE_SCHEMA = DATABASE() 
              AND TABLE_NAME = ? 
            LIMIT 1
        ");
        $stmt->bind_param('s', $table);
        $stmt->execute();
        $ok = (bool)$stmt->get_result()->fetch_row();
        $stmt->close();
        return $ok;
    }
}

if (!function_exists('game_col_exists')) {
    function game_col_exists(mysqli $db, string $table, string $col): bool
    {
        $stmt = $db->prepare("
            SELECT 1 
            FROM INFORMATION_SCHEMA.COLUMNS 
            WHERE TABLE_SCHEMA = DATABASE() 
              AND TABLE_NAME = ? 
              AND COLUMN_NAME = ? 
            LIMIT 1
        ");
        $stmt->bind_param('ss', $table, $col);
        $stmt->execute();
        $ok = (bool)$stmt->get_result()->fetch_row();
        $stmt->close();
        return $ok;
    }
}

if (!function_exists('game_first_col')) {
    function game_first_col(mysqli $db, string $table, array $cols): ?string
    {
        foreach ($cols as $col) {
            if (game_col_exists($db, $table, $col)) {
                return $col;
            }
        }
        return null;
    }
}

if (!function_exists('detect_game_content_table')) {
    function detect_game_content_table(mysqli $db): array
    {
        /*
        |--------------------------------------------------------------------------
        | Priority fix:
        | lms_content_items normally belongs to lms_units through unit_id.
        | So for lms_content_items we must prefer unit_id before module_id.
        |--------------------------------------------------------------------------
        */
        $tables = [
    'lms_content',
    'lms_contents',
    'lms_module_contents',
    'module_contents',
    'lms_content_items',
];

        foreach ($tables as $table) {
            if (!game_tbl_exists($db, $table)) {
                continue;
            }

            if ($table === 'lms_content_items') {
                $moduleCol = game_first_col($db, $table, ['unit_id', 'module_id', 'lms_module_id']);
            } else {
                $moduleCol = game_first_col($db, $table, ['module_id', 'unit_id', 'lms_module_id']);
            }

            $titleCol  = game_first_col($db, $table, ['title', 'name']);
            $urlCol    = game_first_col($db, $table, ['source_path_or_url', 'url', 'file_url', 'path', 'link']);
            $typeCol   = game_first_col($db, $table, ['type', 'content_type']);

            if ($moduleCol && $titleCol && $urlCol) {
                return [
                    'table'     => $table,
                    'moduleCol' => $moduleCol,
                    'titleCol'  => $titleCol,
                    'urlCol'    => $urlCol,
                    'typeCol'   => $typeCol,
                ];
            }
        }

        return ['table' => null];
    }
}

if (!function_exists('read_game_meta')) {
    function read_game_meta(string $gameUrl): array
{
    $root = realpath(dirname(__DIR__, 2));
    $path = parse_url($gameUrl, PHP_URL_PATH) ?: '';

    if (!$root || !$path || strpos($path, '/elms/') !== 0) {
        return ['type' => null, 'duration' => null, 'max_tries' => null];
    }

    $file = $root . substr($path, strlen('/elms'));

    if (!is_file($file)) {
        return ['type' => null, 'duration' => null, 'max_tries' => null];
    }

    $html = @file_get_contents($file);
    if ($html === false) {
        return ['type' => null, 'duration' => null, 'max_tries' => null];
    }

    if (preg_match('~atob\("([^"]+)"\)~', $html, $m)) {
        $payload = json_decode(base64_decode($m[1]), true);
        if (is_array($payload)) {
            return [
                'type'      => (string)($payload['type'] ?? '') ?: null,
                'duration'  => (int)($payload['data']['duration'] ?? $payload['data']['time'] ?? 0) ?: null,
                'max_tries' => (int)($payload['data']['max_tries'] ?? $payload['data']['tries'] ?? 0) ?: null,
            ];
        }
    }

        return ['type' => null, 'duration' => null, 'max_tries' => null];
}
}

if (!function_exists('game_type_badge')) {
    function game_type_badge(?string $type): array
    {
       $map = [
    'fill'       => ['Fill Blanks', 'primary', 'bi-pencil-square'],
    'match'      => ['Match', 'info', 'bi-link-45deg'],
    'order'      => ['Order', 'warning', 'bi-sort-down'],
    'word'       => ['Word Bank', 'secondary', 'bi-card-text'],
    'wordsearch' => ['Word Search', 'secondary', 'bi-search'],
    'memory'     => ['Memory', 'success', 'bi-grid-3x3-gap'],
    'crossword'  => ['Crossword', 'dark', 'bi-plus-square'],
    'image_hotspot' => ['Image Hotspot', 'primary', 'bi-image'],
'truefalse'     => ['True / False', 'success', 'bi-check2-square'],
'draglabel' => ['Drag Label', 'info', 'bi-arrows-move'],
];

        if (!$type || !isset($map[$type])) {
            return ['Game', 'primary', 'bi-controller'];
        }

        return $map[$type];
    }
}

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

$progressMap = [];

if ($studentId > 0 && game_tbl_exists($mysqli, 'lms_game_attempts')) {
    $hasGameId  = game_col_exists($mysqli, 'lms_game_attempts', 'game_id');
    $hasGameUrl = game_col_exists($mysqli, 'lms_game_attempts', 'game_url');

    if ($hasGameId) {
        $res = $mysqli->query("
            SELECT 
                game_id,
                MAX(percent) AS best_score,
                COUNT(*) AS attempts
            FROM lms_game_attempts
            WHERE student_id = $studentId
            GROUP BY game_id
        ");

        if ($res) {
            while ($r = $res->fetch_assoc()) {
                $progressMap[(int)$r['game_id']] = [
                    'score' => (float)$r['best_score'],
                    'attempts' => (int)$r['attempts']
                ];
            }
        }
    } elseif ($hasGameUrl) {
        $res = $mysqli->query("
            SELECT 
                game_url,
                MAX(percent) AS best_score,
                COUNT(*) AS attempts
            FROM lms_game_attempts
            WHERE student_id = $studentId
            GROUP BY game_url
        ");

        if ($res) {
            while ($r = $res->fetch_assoc()) {
                $progressMap[(string)$r['game_url']] = [
                    'score' => (float)$r['best_score'],
                    'attempts' => (int)$r['attempts']
                ];
            }
        }
    }
}
$contentTable = detect_game_content_table($mysqli);

$cid    = (int)($_GET['course_id'] ?? 0);
$mid    = (int)($_GET['module_id'] ?? 0);
$q      = trim((string)($_GET['q'] ?? ''));
$per    = max(6, min(60, (int)($_GET['per'] ?? 24)));
$page   = max(1, (int)($_GET['page'] ?? 1));
$offset = ($page - 1) * $per;

$courses      = [];
$moduleCache  = [];
$courseCache  = [];
$games        = [];
$total        = 0;
$studentCourseIds = [];

/*
|--------------------------------------------------------------------------
| Courses
|--------------------------------------------------------------------------
*/
try {
    if (
        $studentId > 0 &&
        game_tbl_exists($mysqli, 'enrollments') &&
        game_tbl_exists($mysqli, 'batches') &&
        game_tbl_exists($mysqli, 'courses') &&
        game_col_exists($mysqli, 'enrollments', 'student_id') &&
        game_col_exists($mysqli, 'enrollments', 'batch_id') &&
        game_col_exists($mysqli, 'batches', 'course_id')
    ) {
        $courseLabelCol = game_first_col($mysqli, 'courses', ['course_name', 'name', 'title']) ?? 'id';

        $stmt = $mysqli->prepare("
            SELECT DISTINCT c.id, c.`$courseLabelCol` AS label
            FROM enrollments e
            JOIN batches b ON b.id = e.batch_id
            JOIN courses c ON c.id = b.course_id
            WHERE e.student_id = ?
            ORDER BY label
        ");
        $stmt->bind_param('i', $studentId);
        $stmt->execute();
        $res = $stmt->get_result();

        while ($r = $res->fetch_assoc()) {
    $courseId = (int)$r['id'];

    $courses[] = [
        'id'    => $courseId,
        'label' => (string)$r['label'],
    ];

    $courseCache[$courseId] = (string)$r['label'];
    $studentCourseIds[] = $courseId;
}

        $stmt->close();
    }

    if (!$courses && $studentId <= 0 && game_tbl_exists($mysqli, 'courses')) {
        $courseLabelCol = game_first_col($mysqli, 'courses', ['course_name', 'name', 'title']) ?? 'id';
        $res = $mysqli->query("SELECT id, `$courseLabelCol` AS label FROM courses ORDER BY label");

        while ($res && ($r = $res->fetch_assoc())) {
            $courses[] = [
                'id'    => (int)$r['id'],
                'label' => (string)$r['label'],
            ];
            $courseCache[(int)$r['id']] = (string)$r['label'];
        }
    }
} catch (Throwable $e) {
    $courses = [];
}

/*
|--------------------------------------------------------------------------
| Modules / Batch Modules Mapping
|--------------------------------------------------------------------------
| Your DB:
| lms_content.module_id = batch_modules.id
| batch_modules.course_module_id = course_modules.id
| batch_modules.source_course_id / course_modules.course_id = courses.id
|--------------------------------------------------------------------------
*/
$moduleTable = null;
$moduleTitleCol = null;
$moduleCourseCol = null;

try {
    /*
    |--------------------------------------------------------------------------
    | Priority 1: lms_content.module_id maps to batch_modules.id
    |--------------------------------------------------------------------------
    */
    if (
        game_tbl_exists($mysqli, 'batch_modules') &&
        game_tbl_exists($mysqli, 'course_modules') &&
        game_col_exists($mysqli, 'batch_modules', 'course_module_id') &&
        game_col_exists($mysqli, 'course_modules', 'title')
    ) {
        $courseModuleTitleCol = game_first_col($mysqli, 'course_modules', ['title', 'name', 'module_name']) ?? 'title';
        $courseModuleCourseCol = game_first_col($mysqli, 'course_modules', ['course_id', 'cid']) ?? null;

        $courseIdExpr = '0';

        if (game_col_exists($mysqli, 'batch_modules', 'source_course_id')) {
            $courseIdExpr = 'COALESCE(bm.source_course_id, cm.`' . $courseModuleCourseCol . '`)';
        } elseif ($courseModuleCourseCol) {
            $courseIdExpr = 'cm.`' . $courseModuleCourseCol . '`';
        }

        $where = '';

        if ($cid > 0) {
            if (game_col_exists($mysqli, 'batch_modules', 'source_course_id')) {
                $where = "WHERE COALESCE(bm.source_course_id, cm.`$courseModuleCourseCol`) = " . (int)$cid;
            } elseif ($courseModuleCourseCol) {
                $where = "WHERE cm.`$courseModuleCourseCol` = " . (int)$cid;
            }
        }

        $res = $mysqli->query("
            SELECT
                bm.id AS id,
                cm.`$courseModuleTitleCol` AS title,
                $courseIdExpr AS course_id
            FROM batch_modules bm
            LEFT JOIN course_modules cm ON cm.id = bm.course_module_id
            $where
            ORDER BY cm.`$courseModuleTitleCol`, bm.id
            LIMIT 500
        ");

        while ($res && ($r = $res->fetch_assoc())) {
            $bmId = (int)$r['id'];
            $courseIdFromModule = (int)($r['course_id'] ?? 0);
            $title = trim((string)($r['title'] ?? ''));
            if ($title === '' && game_col_exists($mysqli, 'batch_modules', 'course_module_id')) {
    $cmId = 0;

    $tmp = $mysqli->prepare("
        SELECT course_module_id
        FROM batch_modules
        WHERE id = ?
        LIMIT 1
    ");
    $tmp->bind_param('i', $bmId);
    $tmp->execute();
    $tmpRow = $tmp->get_result()->fetch_assoc();
    $tmp->close();

    if ($tmpRow) {
        $cmId = (int)($tmpRow['course_module_id'] ?? 0);
    }

    if ($cmId > 0 && game_tbl_exists($mysqli, 'course_modules')) {
        $cmTitleCol = game_first_col($mysqli, 'course_modules', ['title', 'name', 'module_name']);

        if ($cmTitleCol) {
            $tmp2 = $mysqli->prepare("
                SELECT `$cmTitleCol` AS title
                FROM course_modules
                WHERE id = ?
                LIMIT 1
            ");
            $tmp2->bind_param('i', $cmId);
            $tmp2->execute();
            $tmp2Row = $tmp2->get_result()->fetch_assoc();
            $tmp2->close();

            if ($tmp2Row && trim((string)$tmp2Row['title']) !== '') {
                $title = trim((string)$tmp2Row['title']);
            }
        }
    }
}

            if ($title === '') {
    $title = 'Module #' . $bmId;
}

if (preg_match('/^Module\s*#\d+$/i', $title)) {
    $tmp3 = $mysqli->prepare("
        SELECT cm.title AS title
        FROM batch_modules bm
        JOIN course_modules cm ON cm.id = bm.course_module_id
        WHERE bm.id = ?
        LIMIT 1
    ");
    $tmp3->bind_param('i', $bmId);
    $tmp3->execute();
    $tmp3Row = $tmp3->get_result()->fetch_assoc();
    $tmp3->close();

    if ($tmp3Row && trim((string)$tmp3Row['title']) !== '') {
        $title = trim((string)$tmp3Row['title']);
    }
}

            $moduleCache[$bmId] = [
                'title'     => $title,
                'course_id' => $courseIdFromModule,
            ];

            if ($courseIdFromModule > 0 && empty($courseCache[$courseIdFromModule]) && game_tbl_exists($mysqli, 'courses')) {
                $courseLabelCol = game_first_col($mysqli, 'courses', ['course_name', 'name', 'title']) ?? 'id';

                $cs = $mysqli->prepare("
                    SELECT `$courseLabelCol` AS label
                    FROM courses
                    WHERE id = ?
                    LIMIT 1
                ");
                $cs->bind_param('i', $courseIdFromModule);
                $cs->execute();
                $cr = $cs->get_result()->fetch_assoc();
                $cs->close();

                if ($cr) {
                    $courseCache[$courseIdFromModule] = (string)$cr['label'];
                }
            }
        }

        /*
        |--------------------------------------------------------------------------
        | Mark active module table virtual mapping
        |--------------------------------------------------------------------------
        */
        $moduleTable = 'batch_modules';
        $moduleTitleCol = 'title';
        $moduleCourseCol = 'course_id';
    }

    /*
    |--------------------------------------------------------------------------
    | Fallback: if batch_modules mapping not available
    |--------------------------------------------------------------------------
    */
    if (!$moduleCache) {
        if (game_tbl_exists($mysqli, 'lms_modules')) {
            $moduleTable = 'lms_modules';
        } elseif (game_tbl_exists($mysqli, 'course_modules')) {
            $moduleTable = 'course_modules';
        }

        if ($moduleTable) {
            $moduleTitleCol  = game_first_col($mysqli, $moduleTable, ['title', 'name', 'unit_title', 'module_name']) ?? 'id';
            $moduleCourseCol = game_first_col($mysqli, $moduleTable, ['course_id', 'cid']) ?? null;

            if ($moduleCourseCol) {
                $where = $cid > 0 ? "WHERE `$moduleCourseCol` = " . (int)$cid : '';

                $res = $mysqli->query("
                    SELECT 
                        id, 
                        `$moduleTitleCol` AS title, 
                        `$moduleCourseCol` AS course_id 
                    FROM `$moduleTable`
                    $where
                    ORDER BY title
                    LIMIT 1000
                ");
            } else {
                $res = $mysqli->query("
                    SELECT 
                        id, 
                        `$moduleTitleCol` AS title,
                        0 AS course_id
                    FROM `$moduleTable`
                    ORDER BY title
                    LIMIT 1000
                ");
            }

            while ($res && ($r = $res->fetch_assoc())) {
                $moduleCache[(int)$r['id']] = [
                    'title'     => (string)($r['title'] ?? ('Module #' . (int)$r['id'])),
                    'course_id' => (int)($r['course_id'] ?? 0),
                ];
            }
        }
    }
} catch (Throwable $e) {
    $moduleCache = [];
}
/*
|--------------------------------------------------------------------------
| Fetch games
|--------------------------------------------------------------------------
*/
$games = [];
$seen  = [];

$sourceTables = [];

if (game_tbl_exists($mysqli, 'lms_content')) {
    $sourceTables[] = 'lms_content';
}

if (!empty($contentTable['table']) && $contentTable['table'] !== 'lms_content') {
    $sourceTables[] = $contentTable['table'];
}

foreach ($sourceTables as $table) {
    $titleCol  = game_first_col($mysqli, $table, ['title','name']);
    $urlCol    = game_first_col($mysqli, $table, ['source_path_or_url','url','file_url','path','link']);
    $moduleCol = game_first_col($mysqli, $table, ['module_id','unit_id','lms_module_id']);
    $typeCol   = game_first_col($mysqli, $table, ['type','content_type']);

    if (!$titleCol || !$urlCol || !$moduleCol) {
        continue;
    }

    $where = " WHERE (LOWER(`$urlCol`) LIKE '%uploads/games/%' ";

    if ($typeCol) {
        $where .= " OR LOWER(`$typeCol`) IN ('game','games','activity','interactive') ";
    }

    $where .= ") ";

    if ($mid > 0) {
        $where .= " AND `$moduleCol` = " . (int)$mid . " ";
    }

    if ($q !== '') {
        $where .= " AND `$titleCol` LIKE '%" . $mysqli->real_escape_string($q) . "%' ";
    }

    $sql = "
        SELECT 
            id AS content_id,
            `$titleCol` AS title,
            `$urlCol` AS url,
            `$moduleCol` AS module_id
        FROM `$table`
        $where
        ORDER BY id DESC
        LIMIT 1000
    ";

    $res = $mysqli->query($sql);

    while ($res && ($r = $res->fetch_assoc())) {
        $url = trim((string)($r['url'] ?? ''));
        if ($url === '' || isset($seen[$url])) {
            continue;
        }

        $modId = (int)($r['module_id'] ?? 0);
        $realModuleId = $modId;
$moduleTitle  = 'Module #' . $modId;
$courseId     = 0;

/* Case 1: lms_content.module_id = batch_modules.id */
if (isset($moduleCache[$modId])) {
    $moduleTitle = (string)($moduleCache[$modId]['title'] ?? $moduleTitle);
    $courseId    = (int)($moduleCache[$modId]['course_id'] ?? 0);
}

/* Case 2: lms_content.module_id = course_modules.id */
if (($courseId <= 0 || preg_match('/^Module\s*#\d+$/i', $moduleTitle)) && game_tbl_exists($mysqli, 'course_modules')) {
    $cmTitleCol  = game_first_col($mysqli, 'course_modules', ['title','name','module_name']) ?? 'title';
    $cmCourseCol = game_first_col($mysqli, 'course_modules', ['course_id','cid']);

    if ($cmCourseCol) {
        $cm = $mysqli->prepare("
            SELECT `$cmTitleCol` AS title, `$cmCourseCol` AS course_id
            FROM course_modules
            WHERE id = ?
            LIMIT 1
        ");
        $cm->bind_param('i', $modId);
        $cm->execute();
        $cmRow = $cm->get_result()->fetch_assoc();
        $cm->close();

        if ($cmRow) {
            $moduleTitle = trim((string)$cmRow['title']) ?: $moduleTitle;
            $courseId    = (int)($cmRow['course_id'] ?? 0);
        }
    }
}

/* Case 3: lms_content.module_id = batch_modules.id, but not cached */
if (($courseId <= 0 || preg_match('/^Module\s*#\d+$/i', $moduleTitle)) && game_tbl_exists($mysqli, 'batch_modules') && game_tbl_exists($mysqli, 'course_modules')) {
    $cmTitleCol  = game_first_col($mysqli, 'course_modules', ['title','name','module_name']) ?? 'title';
    $cmCourseCol = game_first_col($mysqli, 'course_modules', ['course_id','cid']);

    $courseExpr = '0';
    if (game_col_exists($mysqli, 'batch_modules', 'source_course_id') && $cmCourseCol) {
        $courseExpr = "COALESCE(bm.source_course_id, cm.`$cmCourseCol`)";
    } elseif (game_col_exists($mysqli, 'batch_modules', 'source_course_id')) {
        $courseExpr = "bm.source_course_id";
    } elseif ($cmCourseCol) {
        $courseExpr = "cm.`$cmCourseCol`";
    }

    $bm = $mysqli->prepare("
        SELECT cm.`$cmTitleCol` AS title, $courseExpr AS course_id
        FROM batch_modules bm
        LEFT JOIN course_modules cm ON cm.id = bm.course_module_id
        WHERE bm.id = ?
        LIMIT 1
    ");
    $bm->bind_param('i', $modId);
    $bm->execute();
    $bmRow = $bm->get_result()->fetch_assoc();
    $bm->close();

    if ($bmRow) {
        $moduleTitle = trim((string)$bmRow['title']) ?: $moduleTitle;
        $courseId    = (int)($bmRow['course_id'] ?? 0);
    }
}

if ($cid > 0 && $courseId > 0 && $courseId !== $cid) {
    continue;
}

$courseTitle = $courseCache[$courseId] ?? '';

if ($courseTitle === '' && $courseId > 0 && game_tbl_exists($mysqli, 'courses')) {
    $cLabel = game_first_col($mysqli, 'courses', ['course_name','name','title']) ?? 'id';
    $cs = $mysqli->prepare("SELECT `$cLabel` AS label FROM courses WHERE id=? LIMIT 1");
    $cs->bind_param('i', $courseId);
    $cs->execute();
    $cr = $cs->get_result()->fetch_assoc();
    $cs->close();

    if ($cr) {
        $courseTitle = (string)$cr['label'];
        $courseCache[$courseId] = $courseTitle;
    }
}

if ($courseTitle === '') {
    $courseTitle = $courseId > 0 ? ('Course #' . $courseId) : 'Course';
}

        if (
            $modId > 0 &&
            (!isset($moduleCache[$modId]) || empty($moduleCache[$modId]['course_id'])) &&
            game_tbl_exists($mysqli, 'batch_modules') &&
            game_tbl_exists($mysqli, 'course_modules')
        ) {
            $cmTitleCol  = game_first_col($mysqli, 'course_modules', ['title','name','module_name']) ?? 'title';
            $cmCourseCol = game_first_col($mysqli, 'course_modules', ['course_id','cid']);

            $courseExpr = '0';

            if (game_col_exists($mysqli, 'batch_modules', 'source_course_id') && $cmCourseCol) {
                $courseExpr = "COALESCE(bm.source_course_id, cm.`$cmCourseCol`)";
            } elseif (game_col_exists($mysqli, 'batch_modules', 'source_course_id')) {
                $courseExpr = "bm.source_course_id";
            } elseif ($cmCourseCol) {
                $courseExpr = "cm.`$cmCourseCol`";
            }

            $mx = $mysqli->prepare("
                SELECT cm.`$cmTitleCol` AS title, $courseExpr AS course_id
                FROM batch_modules bm
                LEFT JOIN course_modules cm ON cm.id = bm.course_module_id
                WHERE bm.id = ?
                LIMIT 1
            ");
            $mx->bind_param('i', $modId);
            $mx->execute();
            $mr = $mx->get_result()->fetch_assoc();
            $mx->close();

            if ($mr) {
                $moduleCache[$modId] = [
                    'title'     => trim((string)$mr['title']) ?: ('Module #' . $modId),
                    'course_id' => (int)($mr['course_id'] ?? 0),
                ];
            }
        }

       

        if ($cid > 0 && $courseId > 0 && $courseId !== $cid) {
            continue;
        }


        if ($courseTitle === '' && $courseId > 0 && game_tbl_exists($mysqli, 'courses')) {
            $cLabel = game_first_col($mysqli, 'courses', ['course_name','name','title']) ?? 'id';
            $cx = $mysqli->prepare("SELECT `$cLabel` AS label FROM courses WHERE id=? LIMIT 1");
            $cx->bind_param('i', $courseId);
            $cx->execute();
            $cr = $cx->get_result()->fetch_assoc();
            $cx->close();

            if ($cr) {
                $courseTitle = (string)$cr['label'];
                $courseCache[$courseId] = $courseTitle;
            }
        }

        if ($courseTitle === '') {
            $courseTitle = $courseId > 0 ? ('Course #' . $courseId) : 'Course';
        }

        $meta = read_game_meta($url);

        $games[] = [
            'id'        => (int)$r['content_id'],
            'title'     => trim((string)$r['title']) ?: 'Game',
            'url'       => $url,
            'type'      => $meta['type'] ?: 'game',
            'duration'  => $meta['duration'],
            'max_tries' => $meta['max_tries'],
            'module'    => [
                'id'    => $modId,
                'title' => $moduleTitle,
            ],
            'course'    => [
                'id'    => $courseId,
                'title' => $courseTitle,
            ],
        ];

        $seen[$url] = true;
    }
}

$total = count($games);
$pages = max(1, (int)ceil($total / max(1, $per)));

if ($games) {
    $games = array_slice($games, $offset, $per);
}
require_once __DIR__ . '/../../includes/student_layout_top.php';
?>

<style>
    .games-hero {
        background:
            radial-gradient(circle at top right, rgba(56,189,248,.28), transparent 32%),
            linear-gradient(135deg, #1d4ed8, #0f172a);
        color: #fff;
        border-radius: 24px;
        padding: 24px;
        box-shadow: 0 18px 40px rgba(37,99,235,.22);
        margin-bottom: 20px;
    }

    .games-hero-title {
        font-size: 1.35rem;
        font-weight: 900;
        margin-bottom: 4px;
    }

    .games-hero-text {
        color: rgba(255,255,255,.76);
        margin: 0;
    }

    .games-filter-card {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 20px;
        padding: 18px;
        box-shadow: 0 10px 28px rgba(15,23,42,.05);
        margin-bottom: 20px;
    }

    .games-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(270px, 1fr));
        gap: 18px;
    }

    .game-card {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 20px;
        padding: 16px;
        box-shadow: 0 10px 28px rgba(15,23,42,.05);
        transition: .18s ease;
        display: flex;
        flex-direction: column;
        min-height: 230px;
    }

    .game-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 16px 34px rgba(15,23,42,.09);
        border-color: #bfdbfe;
    }

    .game-card-top {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 10px;
        margin-bottom: 12px;
    }

    .game-type {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 6px 10px;
        border-radius: 999px;
        font-size: .75rem;
        font-weight: 850;
        background: #eff6ff;
        color: #1d4ed8;
    }

    .game-time {
        display: inline-flex;
        align-items: center;
        gap: 5px;
        padding: 6px 9px;
        border-radius: 999px;
        font-size: .72rem;
        font-weight: 800;
        background: #f8fafc;
        color: #475569;
        border: 1px solid #e5e7eb;
    }

    .game-title {
        font-weight: 900;
        font-size: 1rem;
        line-height: 1.4;
        margin-bottom: 12px;
        color: #111827;
    }

    .game-meta {
        display: flex;
        flex-wrap: wrap;
        gap: 7px;
        margin-bottom: 12px;
    }
    

    .game-chip {
        display: inline-flex;
        align-items: center;
        gap: 5px;
        padding: 6px 9px;
        border-radius: 999px;
        font-size: .72rem;
        font-weight: 750;
        background: #f8fafc;
        color: #475569;
        border: 1px solid #e5e7eb;
    }

    .game-footer {
        margin-top: auto;
    }

    .game-play-btn {
        width: 100%;
        border-radius: 14px;
        font-weight: 850;
        padding: 10px 14px;
    }

    .games-empty {
        background: #fff;
        border: 1px dashed #cbd5e1;
        border-radius: 20px;
        padding: 45px 20px;
        text-align: center;
        color: #64748b;
    }

    .games-empty i {
        font-size: 2.5rem;
        color: #cbd5e1;
        display: block;
        margin-bottom: 10px;
    }

    .games-pagination .page-link {
        border-radius: 999px;
        margin: 0 3px;
        border-color: #e5e7eb;
        color: #2563eb;
        font-weight: 700;
    }

    .games-pagination .page-item.active .page-link {
        background: #2563eb;
        border-color: #2563eb;
    }
    .game-modal .modal-dialog {
        max-width: 1180px;
    }

    .game-modal .modal-content {
        border: 0;
        border-radius: 22px;
        overflow: hidden;
        box-shadow: 0 25px 70px rgba(15,23,42,.35);
    }

    .game-modal .modal-header {
        background: linear-gradient(135deg, #1d4ed8, #0f172a);
        color: #fff;
        border-bottom: 0;
        padding: 14px 18px;
    }

    .game-modal .modal-title {
        font-size: 1rem;
        font-weight: 850;
    }

    .game-modal .btn-close {
        filter: invert(1);
        opacity: .9;
    }

    .game-modal-body {
        background: #f8fafc;
        padding: 0;
    }

    .game-frame {
        width: 100%;
        height: 78vh;
        border: 0;
        display: block;
        background: #fff;
    }

    .game-modal-footer {
        padding: 10px 14px;
        background: #fff;
        border-top: 1px solid #e5e7eb;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 10px;
    }
    .game-chip {
    max-width: 100%;
    line-height: 1.3;
}

    @media (max-width: 768px) {
        .game-modal .modal-dialog {
            margin: 8px;
        }

        .game-frame {
            height: 72vh;
        }

        .game-modal-footer {
            flex-direction: column;
            align-items: stretch;
        }
    }
    @media (max-width: 576px) {
        .games-hero {
            padding: 20px;
            border-radius: 20px;
        }

        .games-grid {
            grid-template-columns: 1fr;
        }
    }
    
    .game-card {
    overflow: hidden;
}

.game-chip {
    max-width: 100%;
    word-break: break-word;
}

.game-title {
    min-height: 44px;
}

.game-modal .modal-dialog {
    width: min(1180px, calc(100vw - 28px));
}

@media (max-width: 768px) {
    .games-filter-card .row > div {
        width: 100%;
    }

    .game-title {
        min-height: auto;
    }

    .game-frame {
        height: 76vh;
    }

    .game-modal .modal-header {
        padding: 12px 14px;
    }
}
    
</style>


<div class="student-page-tabs">
    <a href="/elms/student/modules.php">My Courses</a>
    <a href="/elms/student/learn/index.php">Learn</a>
    <a href="/elms/student/assessments/assessments.php">Assessments</a>
    <a href="/elms/student/results.php">Results</a>
    <a href="/elms/student/games/games.php" class="active">Games</a>
</div>

<div class="games-hero">
    <div class="d-flex flex-wrap align-items-center justify-content-between gap-3">
        <div>
            <div class="games-hero-title">
                Games / Activities
            </div>
            <p class="games-hero-text">
                Play interactive learning activities assigned to your modules.
            </p>
        </div>

        <div class="badge bg-light text-dark rounded-pill px-3 py-2">
            <?= (int)$total ?> item(s)
        </div>
    </div>
</div>

<div class="games-filter-card">
    <form class="row g-3 align-items-end" method="get">
        <div class="col-lg-4">
            <label class="form-label fw-bold">Course</label>
            <select name="course_id" class="form-select" onchange="this.form.module_id.value=''; this.form.submit();">
                <option value="">All courses...</option>
                <?php foreach ($courses as $course): ?>
                    <option value="<?= (int)$course['id'] ?>" <?= $cid === (int)$course['id'] ? 'selected' : '' ?>>
                        <?= esc_game($course['label']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="col-lg-4">
            <label class="form-label fw-bold">Module</label>
            <select name="module_id" class="form-select" onchange="this.form.submit()">
    <option value="">All modules...</option>

    <?php
    $gameModuleIds = [];

foreach ($games as $g) {
    $gameModuleIds[(int)$g['module']['id']] = $g['module']['title'];
}
    ?>

    <?php foreach ($moduleCache as $id => $info): ?>
        <?php
        if (!isset($gameModuleIds[(int)$id])) continue;

        if ($cid > 0 && (int)($info['course_id'] ?? 0) !== $cid) {
            continue;
        }
        ?>
        <option value="<?= (int)$id ?>" <?= $mid === (int)$id ? 'selected' : '' ?>>
            <?= esc_game($info['title'] ?? ('Module #' . $id)) ?>
        </option>
    <?php endforeach; ?>
</select>
        </div>

        <div class="col-lg-3">
            <label class="form-label fw-bold">Search title</label>
            <input 
                type="text" 
                name="q" 
                value="<?= esc_game($q) ?>" 
                class="form-control" 
                placeholder="Type to search..."
            >
        </div>

        <div class="col-lg-1">
            <label class="form-label fw-bold">Per</label>
            <select name="per" class="form-select">
                <?php foreach ([12, 24, 36, 48] as $opt): ?>
                    <option value="<?= $opt ?>" <?= $per === $opt ? 'selected' : '' ?>>
                        <?= $opt ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="col-12 d-flex flex-wrap gap-2">
            <button class="btn btn-primary rounded-pill fw-bold px-4">
                <i class="bi bi-funnel me-1"></i>
                Apply
            </button>

            <a class="btn btn-outline-secondary rounded-pill fw-bold px-4" href="/elms/student/games/games.php">
                Reset
            </a>
        </div>
    </form>
</div>

<?php if (!$contentTable['table']): ?>
    <div class="games-empty">
        <i class="bi bi-database-x"></i>
        Game content table was not found.
    </div>
<?php elseif (!$games): ?>
    <div class="games-empty">
        <i class="bi bi-controller"></i>
        No games found. Try another course/module or clear the search.
    </div>
<?php else: ?>
    <div class="games-grid">
        <?php foreach ($games as $index => $game): ?>
<?php
$gameKey = (string)$game['url']; // single source
$prog = $progressMap[$gameKey] ?? $progressMap[(int)$game['id']] ?? null;
?>
            <?php
            [$label, $variant, $icon] = game_type_badge($game['type']);
            $duration = (int)($game['duration'] ?? 0);
            $durationText = $duration > 0 ? ($duration . 's') : '∞';
            ?>
            <div class="game-card">
                <div class="game-card-top">
                    <span class="game-type">
                        <i class="bi <?= esc_game($icon) ?>"></i>
                        <?= esc_game($label) ?>
                    </span>

                    <span class="game-time">
                        <i class="bi bi-stopwatch"></i>
                        <?= esc_game($durationText) ?>
                    </span>
                </div>
<?php if (!empty($game['max_tries'])): ?>
    <span class="game-time">
        <i class="bi bi-arrow-repeat"></i>
        <?= (int)$game['max_tries'] ?> tries
    </span>
<?php endif; ?>
                <div class="game-title">
                    <?= esc_game($game['title']) ?>
                </div>

                <div class="game-meta">
                    <span class="game-chip">
                        <i class="bi bi-book"></i>
                        <?= esc_game($game['course']['title'] ?? 'Course') ?>
                    </span>

                   <?php
$moduleLabel = trim((string)($game['module']['title'] ?? ''));

$isGenericModule = (
    $moduleLabel === '' ||
    preg_match('/^Module\s*#\d+$/i', $moduleLabel)
);
?>

<?php if (!$isGenericModule): ?>
    <span class="game-chip">
        <i class="bi bi-box"></i>
        <?= esc_game($moduleLabel) ?>
    </span>
<?php endif; ?>
                </div>

                <div class="text-muted small mb-3">
                    EDEN CAMPUS Learning Activity
                </div>
<?php if ($prog): ?>
    <div class="mb-2">
        <span class="badge bg-success">
            <?= round($prog['score']) ?>%
        </span>
        <span class="badge bg-secondary">
            <?= $prog['attempts'] ?> attempts
        </span>
    </div>
<?php else: ?>
    <div class="mb-2">
        <span class="badge bg-warning text-dark">
    New
</span>
    </div>
<?php endif; ?>
                <div class="game-footer">
                    <button
    type="button"
    class="btn btn-primary game-play-btn open-game-modal"
    data-game-url="<?= esc_game($game['url']) ?>"
data-game-id="<?= (int)$game['id'] ?>"
    data-game-title="<?= esc_game($game['title']) ?>"
>
    <i class="bi bi-play-fill me-1"></i>
    Play
</button>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <?php if ($pages > 1): ?>
        <?php
        function game_page_url(int $p): string
        {
            $qs = $_GET;
            $qs['page'] = $p;
            return '?' . http_build_query($qs);
        }

        $prev = max(1, $page - 1);
        $next = min($pages, $page + 1);
        ?>
        <nav class="mt-4 games-pagination" aria-label="Pagination">
            <ul class="pagination justify-content-center flex-wrap">
                <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                    <a class="page-link" href="<?= esc_game(game_page_url($prev)) ?>">Prev</a>
                </li>

                <?php
                $start = max(1, $page - 2);
                $end   = min($pages, $page + 2);
                ?>

                <?php for ($p = $start; $p <= $end; $p++): ?>
                    <li class="page-item <?= $p === $page ? 'active' : '' ?>">
                        <a class="page-link" href="<?= esc_game(game_page_url($p)) ?>">
                            <?= $p ?>
                        </a>
                    </li>
                <?php endfor; ?>

                <li class="page-item <?= $page >= $pages ? 'disabled' : '' ?>">
                    <a class="page-link" href="<?= esc_game(game_page_url($next)) ?>">Next</a>
                </li>
            </ul>
        </nav>
    <?php endif; ?>
<?php endif; ?>

<div class="modal fade game-modal" id="gamePlayModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-centered modal-fullscreen-lg-down">
        <div class="modal-content">
            <div class="modal-header">
                <div>
                    <h5 class="modal-title" id="gameModalTitle">Game / Activity</h5>
                    <div class="small text-white-50">EDEN CAMPUS Learning Activity</div>
                </div>

                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="game-modal-body">
                <iframe
                    id="gameFrame"
                    class="game-frame"
                    src="about:blank"
                    title="Game Activity"
                    allowfullscreen
                ></iframe>
            </div>

            <div class="game-modal-footer">
                <div class="small text-muted">
                    <i class="bi bi-info-circle me-1"></i>
                    Close this popup after completing the activity.
                </div>

                <div class="d-flex gap-2">
                    <a href="#" target="_blank" id="openGameNewTab" class="btn btn-sm btn-outline-secondary rounded-pill px-3">
                        <i class="bi bi-box-arrow-up-right me-1"></i>
                        Open New Tab
                    </a>

                    <button type="button" class="btn btn-sm btn-primary rounded-pill px-3" data-bs-dismiss="modal">
                        Done
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const modalEl = document.getElementById('gamePlayModal');
    const frame = document.getElementById('gameFrame');
    const title = document.getElementById('gameModalTitle');
    const newTab = document.getElementById('openGameNewTab');

    if (!modalEl || !frame || !title) return;

    const modal = new bootstrap.Modal(modalEl, {
        backdrop: 'static',
        keyboard: true
    });

    document.querySelectorAll('.open-game-modal').forEach(function (btn) {
        btn.addEventListener('click', function () {
            const url = btn.getAttribute('data-game-url') || '';
            const gameTitle = btn.getAttribute('data-game-title') || 'Game / Activity';

            title.textContent = gameTitle;
            frame.src = 'about:blank';
setTimeout(()=>{
    frame.src = url;
}, 50);

            if (newTab) {
                newTab.href = url;
            }

            modal.show();
        });
    });

    modalEl.addEventListener('hidden.bs.modal', function () {
        frame.src = 'about:blank';
        title.textContent = 'Game / Activity';

        if (newTab) {
            newTab.href = '#';
        }
    });
});
</script>
<?php
require_once __DIR__ . '/../../includes/student_layout_bottom.php';
?>