<?php
declare(strict_types=1);
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/../../includes/db.php';

/* ---------- helpers ---------- */
function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
function t_exists(mysqli $db,string $t): bool {
  $st=$db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? LIMIT 1");
  $st->bind_param('s',$t); $st->execute(); $ok=(bool)$st->get_result()->fetch_row(); $st->close(); return $ok;
}
function c_exists(mysqli $db,string $t,string $c): bool {
  $st=$db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=? LIMIT 1");
  $st->bind_param('ss',$t,$c); $st->execute(); $ok=(bool)$st->get_result()->fetch_row(); $st->close(); return $ok;
}
function first_existing(mysqli $db,string $t,array $cols): ?string {
  foreach($cols as $c) if (c_exists($db,$t,$c)) return $c; return null;
}
function detect_content_table(mysqli $db): array {
  foreach (['lms_content','lms_contents','lms_module_contents','module_contents','lms_content_items'] as $T) {
    if (!t_exists($db,$T)) continue;
    $mid   = first_existing($db,$T,['module_id','lms_module_id']);
    $title = first_existing($db,$T,['title','name']);
    $url   = first_existing($db,$T,['url','file_url','path','link']);
    $type  = first_existing($db,$T,['type','content_type']);
    if ($mid && $title && $url) return compact('T','mid','title','url','type');
  } return ['T'=>null];
}

/* read meta from saved game html (type + duration) */
function read_game_meta_from_file(string $gameUrl): array {
  $root = realpath(dirname(__DIR__,2)); // /elms
  $path = parse_url($gameUrl, PHP_URL_PATH) ?: '';
  $file = $path && str_starts_with($path,'/elms/') ? $root . substr($path, strlen('/elms')) : '';
  if (!$file || !is_file($file)) return ['type'=>null,'duration'=>null];
  $html = @file_get_contents($file);
  if ($html===false) return ['type'=>null,'duration'=>null];
  if (preg_match('~<script[^>]*id=["\']game-data["\'][^>]*>(\{.*\})</script>~si', $html, $m)) {
    $payload = json_decode($m[1], true);
    $type = (string)($payload['type'] ?? '');
    $dur  = (int)($payload['data']['duration'] ?? 0);
    return ['type'=>$type?:null,'duration'=>$dur?:null];
  }
  return ['type'=>null,'duration'=>null];
}
function type_badge(string $type=null): array {
  $map = [
    'fill'  => ['🧩 Fill Blanks','primary'],
    'match' => ['🔗 Match','info'],
    'order' => ['🔀 Order','warning'],
    'word'  => ['📝 Word Bank','secondary'],
    'wordsearch'=>['🔎 Word Search','secondary'],
    'memory'=>['🃏 Memory','success'],
    'wheel' => ['🎡 Wheel','warning'],
    'crossword'=>['✚ Crossword','dark'],
  ];
  if (!$type || !isset($map[$type])) return ['🎮 Game','secondary'];
  return $map[$type];
}

/* ---------- DB ---------- */
$mysqli = $mysqli ?? ($conn ?? new mysqli('localhost','root','','edencamp_edencampus'));
$mysqli->set_charset('utf8mb4');

$CT = detect_content_table($mysqli);

/* course list */
$COURSES=[]; $COURSE_LABEL='name';
if (t_exists($mysqli,'courses')) {
  $COURSE_LABEL = first_existing($mysqli,'courses',['course_name','name','title']) ?? 'id';
  $rs = $mysqli->query("SELECT id,$COURSE_LABEL AS label FROM courses ORDER BY label");
  while($rs && ($r=$rs->fetch_assoc())) $COURSES[]=['id'=>(int)$r['id'],'label'=>$r['label']];
  if($rs) $rs->close();
}

/* request params */
$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;

/* module table detection and lookup helpers */
$Tmod = t_exists($mysqli,'lms_modules') ? 'lms_modules' : (t_exists($mysqli,'course_modules') ? 'course_modules' : null);
$MOD_TITLE_COL = $Tmod ? (first_existing($mysqli,$Tmod,['title','name']) ?? 'id') : null;
$MOD_COURSE_COL = $Tmod ? (first_existing($mysqli,$Tmod,['course_id','cid']) ?? 'course_id') : null;

/* cache module+course names */
$MODULE_CACHE = []; $COURSE_CACHE = [];
foreach($COURSES as $c){ $COURSE_CACHE[$c['id']]=$c['label']; }
if ($Tmod) {
  $where = $cid>0 ? "WHERE `$MOD_COURSE_COL`=".(int)$cid : '';
  $rs = $mysqli->query("SELECT id, `$MOD_TITLE_COL` AS title, `$MOD_COURSE_COL` AS course_id FROM `$Tmod` $where");
  while($rs && ($r=$rs->fetch_assoc())) $MODULE_CACHE[(int)$r['id']] = ['title'=>$r['title'],'course_id'=>(int)$r['course_id']];
  if($rs) $rs->close();
}

/* ---------- fetch games with pagination ---------- */
$GAMES=[]; $total=0;
if ($CT['T']) {
  $selT = $CT['T']; $selTitle = $CT['title']; $selUrl = $CT['url']; $selMid = $CT['mid'];
  $where = " WHERE `$selUrl` LIKE '%/uploads/games/%' ";
  $tp=''; $vals=[];
  if ($mid>0){ $where.=" AND `$selMid`=? "; $tp.='i'; $vals[]=$mid; }
  if ($cid>0 && $Tmod){
    $ids=[]; foreach($MODULE_CACHE as $id=>$m) if ((int)$m['course_id']===$cid) $ids[]=$id;
    if ($ids){ $where.=" AND `$selMid` IN (".implode(',', array_map('intval',$ids)).") "; }
    else { $where.=" AND 0 "; }
  }
  if ($q!==''){ $where.=" AND `$selTitle` LIKE ? "; $tp.='s'; $vals[]='%'.$q.'%'; }

  // count
  $sqlCnt = "SELECT COUNT(*) FROM `$selT` $where";
  $stc = $mysqli->prepare($sqlCnt);
  if ($tp) $stc->bind_param($tp, ...$vals);
  $stc->execute(); $stc->bind_result($total); $stc->fetch(); $stc->close();

  // page
  $sql = "SELECT `$selTitle` AS title, `$selUrl` AS url, `$selMid` AS module_id
          FROM `$selT` $where ORDER BY `$selTitle` LIMIT ? OFFSET ?";
  $stm = $mysqli->prepare($sql);
  $tpPage=$tp.'ii'; $valsPage=$vals; $valsPage[]=$per; $valsPage[]=$offset;
  $stm->bind_param($tpPage, ...$valsPage);
  $stm->execute(); $rs = $stm->get_result();
  while($rs && ($r=$rs->fetch_assoc())) {
    $modId = (int)$r['module_id'];
    if ($Tmod && !isset($MODULE_CACHE[$modId])){
      $sub = $mysqli->prepare("SELECT `$MOD_TITLE_COL` AS title, `$MOD_COURSE_COL` AS course_id FROM `$Tmod` WHERE id=? LIMIT 1");
      $sub->bind_param('i',$modId); $sub->execute(); $subr=$sub->get_result()->fetch_assoc();
      if ($subr) $MODULE_CACHE[$modId]=['title'=>$subr['title'],'course_id'=>(int)$subr['course_id']];
      $sub->close();
    }
    $mTitle = $MODULE_CACHE[$modId]['title'] ?? 'Module #'.$modId;
    $cId    = $MODULE_CACHE[$modId]['course_id'] ?? 0;
    $cTitle = $COURSE_CACHE[$cId] ?? ($cId?('Course #'.$cId):'—');

    $meta = read_game_meta_from_file((string)$r['url']);
    $GAMES[]=[
      'title'=>$r['title'],
      'url'=>$r['url'],
      'type'=>$meta['type'],
      'duration'=>$meta['duration'],
      'module'=>['id'=>$modId,'title'=>$mTitle],
      'course'=>['id'=>$cId,'title'=>$cTitle],
    ];
  }
  $stm->close();
}

$pages = max(1, (int)ceil($total / $per));
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>All Games / Activities · EDEN CAMPUS</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    :root{
      --eden1:#0f172a; --eden2:#2563eb; --bg:#f6f8ff; --ink:#0f172a;
      --card:#ffffff; --line:#e6eaf3;
    }
    body{background:var(--bg); color:var(--ink)}
    .topbar{background:linear-gradient(90deg,var(--eden1),var(--eden2)); color:#fff}
    .topbar a{color:#fff;text-decoration:none}
    .page-title{font-weight:800; letter-spacing:.2px}
    .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:18px}
    .card-game{
      background:var(--card); border:1px solid var(--line); border-radius:18px;
      box-shadow:0 12px 28px rgba(2,8,23,.06); padding:16px; display:flex; gap:10px; flex-direction:column;
      transition:transform .15s ease, box-shadow .15s ease;
    }
    .card-game:hover{transform:translateY(-3px); box-shadow:0 18px 36px rgba(2,8,23,.10)}
    .soft{border:1px solid #dfe6ff; background:#eef2ff; color:#111}
    .crumbs{display:flex;gap:6px;flex-wrap:wrap}
    .crumbs .badge{font-weight:600}
    .title{font-weight:700; font-size:1.06rem}
    .meta{color:#64748b}
    .btn-play{background:var(--eden2); border-color:var(--eden2); width:100%; font-weight:700}
    .btn-play:hover{background:#1e4fd5;border-color:#1e4fd5}
    .filters .form-label{font-weight:700; color:#334155}
    .empty{border:1px dashed var(--line); background:#fff; border-radius:16px; padding:24px; color:#64748b; text-align:center}
    .pagination{--bs-pagination-focus-box-shadow:none}
    @media (max-width:600px){ .grid{grid-template-columns:1fr} }
  </style>
</head>
<body>
  <!-- Header -->
  <div class="topbar">
    <div class="container py-2 d-flex align-items-center justify-content-between">
      <a class="btn btn-sm btn-light fw-semibold" href="/elms/student/">← Student Home</a>
      <div class="page-title">All Games / Activities</div>
      <span class="text-white-50 small"><?= (int)$total ?> item(s)</span>
    </div>
  </div>

  <!-- Filters -->
  <div class="container py-4 filters">
    <form class="row g-3 mb-3" method="get">
      <div class="col-lg-4">
        <label class="form-label">Course</label>
        <select name="course_id" class="form-select" onchange="this.form.submit()">
          <option value="">All courses…</option>
          <?php foreach($COURSES as $c): ?>
            <option value="<?= (int)$c['id'] ?>" <?= $cid===(int)$c['id']?'selected':'' ?>><?= esc($c['label']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-lg-4">
        <label class="form-label">Module</label>
        <select name="module_id" class="form-select">
          <option value="">All modules…</option>
          <?php
            if ($Tmod && $cid>0){
              foreach($MODULE_CACHE as $id=>$info){
                if ((int)$info['course_id']!==$cid) continue;
                echo '<option value="'.(int)$id.'" '.($mid===$id?'selected':'').'>'.esc($info['title']).'</option>';
              }
            } elseif ($Tmod && $cid===0){
              $rs = $mysqli->query("SELECT id, `$MOD_TITLE_COL` AS title FROM `$Tmod` ORDER BY id LIMIT 200");
              while($rs && ($r=$rs->fetch_assoc())){
                echo '<option value="'.(int)$r['id'].'" '.($mid===(int)$r['id']?'selected':'').'>'.esc($r['title']).'</option>';
              }
              if($rs) $rs->close();
            }
          ?>
        </select>
      </div>
      <div class="col-lg-3">
        <label class="form-label">Search title</label>
        <input name="q" value="<?= esc($q) ?>" class="form-control" placeholder="Type to search…">
      </div>
      <div class="col-lg-1">
        <label class="form-label">Per page</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 gap-2">
        <button class="btn btn-primary fw-semibold">Apply</button>
        <a class="btn btn-outline-secondary" href="?">Reset</a>
      </div>
    </form>

    <!-- Cards -->
    <?php if (!$GAMES): ?>
      <div class="empty">No games found. Try another course/module or clear the search.</div>
    <?php else: ?>
      <div class="grid">
        <?php foreach($GAMES as $g):
          [$label,$variant] = type_badge($g['type']);
          $dur = (int)($g['duration'] ?? 0); $durTxt = $dur>0 ? ($dur.'s') : '∞';
          $crumbCourse = $g['course']['title'] ?: '—';
          $crumbModule = $g['module']['title'] ?: ('Module #'.$g['module']['id']);
        ?>
        <div class="card-game">
          <div class="d-flex align-items-center justify-content-between">
            <span class="badge text-bg-<?= esc($variant) ?>"><?= esc($label) ?></span>
            <span class="badge soft">⏱ <?= esc($durTxt) ?></span>
          </div>

          <div class="title"><?= esc($g['title']) ?></div>

          <div class="crumbs">
            <span class="badge text-bg-light">📚 <?= esc($crumbCourse) ?></span>
            <span class="badge text-bg-light">📦 <?= esc($crumbModule) ?></span>
          </div>

          <div class="meta small">EDEN CAMPUS</div>

          <!-- Only one clear action -->
          <a class="btn btn-play btn-sm text-white mt-1" target="_blank" href="<?= esc($g['url']) ?>">Play</a>
        </div>
        <?php endforeach; ?>
      </div>

      <!-- Pagination -->
      <?php if ($pages>1): ?>
      <nav class="mt-4" aria-label="Pagination">
        <ul class="pagination justify-content-center flex-wrap">
          <?php
            function 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);
          ?>
          <li class="page-item <?= $page<=1?'disabled':'' ?>"><a class="page-link" href="<?= esc(page_url($prev)) ?>">« Prev</a></li>
          <?php
            $window = 2;
            $start = max(1, $page-$window);
            $end   = min($pages, $page+$window);
            if ($start>1){
              echo '<li class="page-item"><a class="page-link" href="'.esc(page_url(1)).'">1</a></li>';
              if ($start>2) echo '<li class="page-item disabled"><span class="page-link">…</span></li>';
            }
            for($p=$start;$p<=$end;$p++){
              echo '<li class="page-item '.($p===$page?'active':'').'"><a class="page-link" href="'.esc(page_url($p)).'">'.$p.'</a></li>';
            }
            if ($end<$pages){
              if ($end<$pages-1) echo '<li class="page-item disabled"><span class="page-link">…</span></li>';
              echo '<li class="page-item"><a class="page-link" href="'.esc(page_url($pages)).'">'.$pages.'</a></li>';
            }
          ?>
          <li class="page-item <?= $page>=$pages?'disabled':'' ?>"><a class="page-link" href="<?= esc(page_url($next)) ?>">Next »</a></li>
        </ul>
      </nav>
      <?php endif; ?>
    <?php endif; ?>
  </div>
</body>
</html>
