<?php
// Student › module_content — render one item inline (PDF/video/audio/image/link) or embed a quiz.
declare(strict_types=1);
if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__.'/../includes/app.php';
require_once __DIR__.'/../includes/db.php';
if (is_file(__DIR__.'/../includes/helpers.php')) require_once __DIR__.'/../includes/helpers.php';

header('Content-Type: text/html; charset=utf-8');

/* ------------------------- helpers ------------------------- */
if (!function_exists('esc')) { function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); } }
if (!function_exists('str_contains')) { function str_contains($h,$n){ return $n==='' || strpos((string)$h,(string)$n)!==false; } }
if (!function_exists('str_starts_with')){ function str_starts_with($h,$n){ $h=(string)$h; $n=(string)$n; return $n===''||strncmp($h,$n,strlen($n))===0; } }

function origin_url(): string {
  $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
  $scheme = $https ? 'https' : 'http';
  $host = $_SERVER['HTTP_HOST'] ?? 'admin.edencampus.lk';
  return $scheme.'://'.$host;
}

function t_exists(string $t): bool { global $mysqli;
  $st=$mysqli->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(string $t,string $c): bool { global $mysqli;
  $t=$mysqli->real_escape_string($t); $c=$mysqli->real_escape_string($c);
  $sql="SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='$t' AND COLUMN_NAME='$c' LIMIT 1";
  if ($res=$mysqli->query($sql)) { $ok=$res->num_rows>0; $res->close(); return $ok; }
  return false;
}

/* Build absolute URL from a stored value — supports /uploads and /elms/uploads */
function abs_url_from_value(string $v): string {
  $v = trim(str_replace('\\','/',$v));
  if ($v === '') return '';
  if (preg_match('~^(?:https?:)?//~i', $v) || str_starts_with($v,'data:')) return $v;

  // Root-relative path → keep exactly (works for /uploads/... or /elms/uploads/...)
  if (str_starts_with($v,'/')) return origin_url().$v;

  // Common relative forms from DB (uploads, content, games)
  if (preg_match('~^(?:elms/)?uploads/|^uploads/|^content/|^games/|^files/~i',$v)) {
    if (str_starts_with($v,'elms/')) $v = substr($v,4); // normalize "elms/uploads/.." → "uploads/.."
    return origin_url().'/'.ltrim($v,'/');
  }

  // Bare filename with known extension → assume /uploads/content/
  if (preg_match('~\.(pdf|mp4|webm|ogg|mov|mkv|mp3|wav|m4a|aac|oga|jpg|jpeg|png|gif|webp|svg|html?)$~i', $v))
    return origin_url().'/uploads/content/'.ltrim($v,'/');

  // Fallback relative
  return origin_url().'/'.ltrim($v,'/');
}

/* If URL is /uploads/... or /elms/uploads/..., return the alternate variant for fallback */
function alt_uploads_variant(string $url): ?string {
  $p = parse_url($url); if(!$p) return null;
  $path = $p['path'] ?? ''; if($path==='') return null;

  if (str_starts_with($path,'/elms/uploads/')) {
    $alt = origin_url().substr($path,5); // remove "/elms"
  } elseif (str_starts_with($path,'/uploads/')) {
    $alt = origin_url().'/elms'.$path;   // add "/elms"
  } else {
    return null;
  }
  if (isset($p['query']))    $alt .= '?'.$p['query'];
  if (isset($p['fragment'])) $alt .= '#'.$p['fragment'];
  return $alt;
}

/* If a link points to a folder (game/HTML pack), try index.html inside it */
function alt_index_fallback(string $url): ?string {
  $p = parse_url($url); if (!$p) return null;
  $path = $p['path'] ?? ''; if ($path==='') return null;

  // If it already ends with a file (pdf, html, media, image) → no index fallback
  if (preg_match('~\.(?:html?|php|pdf|mp4|webm|ogg|mov|mkv|mp3|wav|m4a|aac|oga|jpg|jpeg|png|gif|webp|svg)$~i', $path)) return null;

  if (substr($path,-1) !== '/') $path .= '/';
  $new = ($p['scheme'] ?? '').($p['scheme']? '://':'')
       . ($p['host'] ?? '')
       . (isset($p['port']) ? ':'.$p['port'] : '')
       . $path . 'index.html';
  if (isset($p['query']))    $new .= '?'.$p['query'];
  if (isset($p['fragment'])) $new .= '#'.$p['fragment'];
  return $new ?: null;
}

function detect_file_url_from_row(array $row): string {
  foreach (['file_url','url','path','file','content_url','link','filepath','file_path','filename','attachment','document','resource','location','source'] as $k){
    if (!empty($row[$k])) return abs_url_from_value((string)$row[$k]);
  }
  foreach ($row as $v){
    if (!is_string($v)) continue; $vv=trim($v); if ($vv==='') continue;
    if (str_contains($vv,'/uploads/') || preg_match('~^https?://~i',$vv) ||
        preg_match('~\.(pdf|mp4|webm|ogg|mkv|mov|mp3|wav|m4a|aac|oga|jpg|jpeg|png|gif|webp|svg|html?)$~i',$vv))
      return abs_url_from_value($vv);
  }
  return '';
}
function detect_kind(string $t, string $url): string {
  $t=strtolower(trim($t));
  $ext=strtolower(pathinfo((string)(parse_url($url,PHP_URL_PATH) ?? ''), PATHINFO_EXTENSION));

  if ($t){
    if (str_contains($t,'quiz')) return 'quiz';
    if (str_contains($t,'pdf'))  return 'pdf';
    if (str_starts_with($t,'image/')) return 'image';
    if (str_starts_with($t,'audio/')||str_contains($t,'audio')) return 'audio';
    if (str_starts_with($t,'video/')||str_contains($t,'video')) return 'video';
  }
  if ($ext==='pdf') return 'pdf';
  if (in_array($ext,['jpg','jpeg','png','gif','webp','svg'])) return 'image';
  if (in_array($ext,['mp3','wav','m4a','aac','oga'])) return 'audio';
  if (in_array($ext,['mp4','webm','ogg','mov','mkv'])) return 'video';
  return 'link';
}
function to_youtube_embed(string $url): ?string {
  if (!preg_match('~(?:youtu\.be/|youtube\.com/(?:watch\?v=|embed/|shorts/))([\w\-]{6,})~i', $url, $m)) return null;
  return 'https://www.youtube.com/embed/'.rawurlencode($m[1]).'?rel=0';
}
function to_vimeo_embed(string $url): ?string {
  if (!preg_match('~vimeo\.com/(?:video/)?(\d+)~i', $url, $m)) return null;
  return 'https://player.vimeo.com/video/'.rawurlencode($m[1]);
}

/* ------------------------- inputs ------------------------- */
$item_id   = (int)($_GET['item_id'] ?? 0);
$module_id = (int)($_GET['module_id'] ?? 0);

/* ------------------------ table pick ---------------------- */
$T=null; foreach(['lms_content','lms_contents','lms_module_contents','module_contents','lms_content_items'] as $x){ if (t_exists($x)) { $T=$x; break; } }
if (!$T){ echo '<div class="p-4 text-danger">No content table found.</div>'; exit; }

$ID  = c_exists($T,'id') ? 'id' : (c_exists($T,'content_id') ? 'content_id' : null);
$MID = c_exists($T,'module_id') ? 'module_id' : (c_exists($T,'lms_module_id') ? 'lms_module_id' : null);
$REL = c_exists($T,'is_released') ? 'is_released' : (c_exists($T,'active') ? 'active' : null);

/* ------------------------ styles -------------------------- */
echo '<style>
  :root{--line:#e6eaf3; --ink:#0f172a;}
  html,body{margin:0;padding:0}
  body{font-family:Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,Arial,sans-serif;color:var(--ink)}
  .bar{padding:12px 16px;border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between;gap:12px}
  .ttl{font-weight:800;margin:0;font-size:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
  .wrap{padding:12px}
  .wrap iframe, .wrap video{width:100%;max-height:82vh;border:0}
  .wrap img{max-width:100%;height:auto}
  @media (max-width:760px){
    .wrap iframe, .wrap video{max-height:78vh}
  }
</style>';

/* ------------------- single item view --------------------- */
if ($item_id>0 && $ID){
  $sql="SELECT * FROM `$T` WHERE `$ID`=?".($REL? " AND `$REL`=1" : "")." LIMIT 1";
  $st=$mysqli->prepare($sql); $st->bind_param('i',$item_id); $st->execute();
  $row=$st->get_result()->fetch_assoc(); $st->close();

  if (!$row){ echo '<div class="wrap"><div class="text-danger">Item not found.</div></div>'; exit; }

  $title=(string)($row['title'] ?? $row['name'] ?? $row['topic'] ?? ('Item #'.$item_id));
  $quiz =(int)($row['quiz_id'] ?? $row['exam_id'] ?? 0);
  $url  = detect_file_url_from_row($row);
  $ctype=(string)($row['type'] ?? $row['mime_type'] ?? $row['content_type'] ?? $row['file_type'] ?? '');
  $kind = $quiz>0 ? 'quiz' : detect_kind($ctype,$url);

  echo '<div class="bar"><div class="ttl">'.esc($title).'</div></div><div class="wrap">';

  /* Quiz inline */
  if ($kind === 'quiz') {
    $qurl = app_url('/student/quiz.php?quiz_id='.(int)$quiz.'&embed=1');
    echo '<div class="mb-2"><a class="btn btn-sm btn-outline-secondary" href="'.esc(app_url('/student/quiz.php?quiz_id='.(int)$quiz)).'" target="_blank" rel="noopener">Open full page ↗</a></div>';
    echo '<iframe class="quiz-frame" src="'.esc($qurl).'" allow="clipboard-write; autoplay; fullscreen" style="height:82vh"></iframe>';
    echo '</div>'; exit;
  }

  if ($url===''){ echo '<div class="text-danger">No file/URL set for this item.</div></div>'; exit; }

  /* Special video hosts */
  if ($yt = to_youtube_embed($url)){
    echo '<div class="mb-2"><a class="btn btn-sm btn-outline-secondary" href="'.esc($url).'" target="_blank" rel="noopener">View externally ↗</a></div>';
    echo '<div class="ratio ratio-16x9"><iframe src="'.esc($yt).'" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share; fullscreen" allowfullscreen style="height:72vh"></iframe></div>';
    echo '</div>'; exit;
  }
  if ($vim = to_vimeo_embed($url)){
    echo '<div class="mb-2"><a class="btn btn-sm btn-outline-secondary" href="'.esc($url).'" target="_blank" rel="noopener">View externally ↗</a></div>';
    echo '<div class="ratio ratio-16x9"><iframe src="'.esc($vim).'" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen style="height:72vh"></iframe></div>';
    echo '</div>'; exit;
  }

  /* For everything else show inline first, then offer full page */
  echo '<div class="mb-2"><a class="btn btn-sm btn-outline-secondary" href="'.esc($url).'" target="_blank" rel="noopener">View externally ↗</a></div>';

  $altU = alt_uploads_variant($url);  // /uploads ↔ /elms/uploads fallback
  $altI = alt_index_fallback($url);   // folder → /index.html fallback

  if ($kind==='image'){
    echo '<img src="'.esc($url).'" alt="">';
  } elseif ($kind==='video'){
    echo '<video src="'.esc($url).'" controls playsinline style="max-height:82vh"></video>';
  } elseif ($kind==='audio'){
    echo '<audio src="'.esc($url).'" controls style="width:100%"></audio>';
  } else {
    // pdf or generic link → iframe
    $src = $kind==='pdf' ? $url.'#toolbar=1&navpanes=0' : $url;
    echo '<iframe id="inlineFrame" src="'.esc($src).'" allow="autoplay; encrypted-media; fullscreen; clipboard-write" referrerpolicy="no-referrer-when-downgrade" style="height:82vh"></iframe>';
    // JS fallbacks: 1) alternate uploads path  2) /index.html inside folder (games/HTML packs)
    echo '<script>
      (function(){
        var f = document.getElementById("inlineFrame"); if(!f) return;
        var loaded = false, triedAltU = false, triedAltI = false;
        var altU = '.json_encode($altU).';
        var altI = '.json_encode($altI).';

        f.addEventListener("load", function(){ loaded = true; });

        function swap(u){ if(!u) return false; f.src = u; return true; }

        setTimeout(function(){
          if(loaded) return;
          if(!triedAltU && swap(altU)) { triedAltU = true; return; }
          if(!triedAltI && swap(altI)) { triedAltI = true; return; }
        }, 2500);
      })();
    </script>';
  }

  echo '</div>'; exit;
}

/* ---------------- module overview fallback ---------------- */
if ($module_id>0 && $MID && $ID){
  $sql="SELECT * FROM `$T` WHERE `$MID`=?".($REL? " AND `$REL`=1" : "")." ORDER BY `$ID`";
  $st=$mysqli->prepare($sql); $st->bind_param('i',$module_id); $st->execute();
  $rs=$st->get_result();

  echo '<div class="bar"><div class="ttl">Module Items</div></div><div class="wrap">';
  if (!$rs->num_rows){ echo '<div class="text-muted">No items in this module.</div></div>'; exit; }
  while ($row=$rs->fetch_assoc()){
    $id=(int)($row[$ID] ?? 0);
    $title=(string)($row['title'] ?? $row['name'] ?? $row['topic'] ?? ('Item #'.$id));
    $ctype=(string)($row['type'] ?? $row['mime_type'] ?? $row['content_type'] ?? $row['file_type'] ?? '' );
    echo '<div class="d-flex align-items-center justify-content-between border rounded p-2 mb-2">
            <div><div class="fw-semibold">'.esc($title).'</div>
            <div class="small text-muted">'.esc($ctype ?: 'item').'</div></div>
            <div>
              <a class="btn btn-sm btn-primary" href="'.esc(app_url('/student/module_content.php?item_id='.$id)).'">Open</a>
              <a class="btn btn-sm btn-link" href="'.esc(app_url('/student/module_content.php?item_id='.$id)).'">View</a>
            </div>
          </div>';
  }
  echo '</div>'; exit;
}

echo '<div class="wrap text-muted">Select an item.</div>';
