<?php
// /elms/student/module_content.php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . '/../includes/db.php';

$mysqli = $mysqli ?? ($conn ?? null);

if (!$mysqli instanceof mysqli) {
  http_response_code(500);
  exit('DB connection failed');
}

$mysqli->set_charset('utf8mb4');

if (empty($_SESSION['student_id'])) {
  header('Location: /elms/student/login.php?next=' . rawurlencode($_SERVER['REQUEST_URI'] ?? '/elms/student/modules.php'));
  exit;
}

function h($s) {
  return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function table_exists(mysqli $db, string $table): bool {
  $table = $db->real_escape_string($table);
  $q = $db->query("SHOW TABLES LIKE '{$table}'");
  return $q && $q->num_rows > 0;
}

function col_exists(mysqli $db, string $table, string $col): bool {
  $table = $db->real_escape_string($table);
  $col = $db->real_escape_string($col);
  $q = $db->query("SHOW COLUMNS FROM `{$table}` LIKE '{$col}'");
  return $q && $q->num_rows > 0;
}

function content_href(?string $p): string {
  if (!$p) return '';

  $p = str_replace('\\', '/', trim($p));

  if ($p === '') return '';

  if (preg_match('#^https?://#i', $p)) {
    return $p;
  }

  if (str_starts_with($p, '/elms/')) {
    return $p;
  }

  if (str_starts_with($p, '/uploads/')) {
    return '/elms' . $p;
  }

  if (preg_match('#^(uploads/|content/|assessments/|submissions/)#i', $p)) {
    return '/elms/' . ltrim($p, '/');
  }

  if (str_starts_with($p, '/')) {
    return $p;
  }

  return '/elms/uploads/content/' . ltrim($p, '/');
}

function icon_for_type(string $type): string {
  return match (strtolower($type)) {
    'pdf'   => 'bi-file-earmark-pdf',
    'video' => 'bi-play-btn',
    'link'  => 'bi-link-45deg',
    'text'  => 'bi-card-text',
    'quiz'  => 'bi-question-circle',
    'game'  => 'bi-controller',
    default => 'bi-file-earmark',
  };
}

function badge_for_type(string $type): string {
  return match (strtolower($type)) {
    'pdf'   => 'text-bg-danger',
    'video' => 'text-bg-primary',
    'link'  => 'text-bg-info',
    'text'  => 'text-bg-secondary',
    'quiz'  => 'text-bg-warning',
    'game'  => 'text-bg-success',
    default => 'text-bg-dark',
  };
}

$student_id = (int)$_SESSION['student_id'];
$module_id  = (int)($_GET['module_id'] ?? 0);
$course_id  = (int)($_GET['course_id'] ?? 0);

if ($module_id <= 0) {
  header('Location: /elms/student/modules.php');
  exit;
}

/* Student */
$studentCols = "id, full_name, academic_email, center_reg_no, reference_no, lms_status";

if (col_exists($mysqli, 'studentss', 'course_id')) {
  $studentCols .= ", course_id";
}

$st = $mysqli->prepare("SELECT $studentCols FROM studentss WHERE id=? LIMIT 1");
$st->bind_param('i', $student_id);
$st->execute();
$student = $st->get_result()->fetch_assoc();
$st->close();

if (!$student) {
  session_destroy();
  header('Location: /elms/student/login.php');
  exit;
}

$_SESSION['student_name']   = $student['full_name'] ?? ($_SESSION['student_name'] ?? 'Student');
$_SESSION['academic_email'] = $student['academic_email'] ?? ($_SESSION['academic_email'] ?? '');
$_SESSION['center_reg_no']  = $student['center_reg_no'] ?? ($_SESSION['center_reg_no'] ?? '');

$lms_status = strtolower(trim((string)($student['lms_status'] ?? 'active')));

if (in_array($lms_status, ['inactive', 'suspended'], true)) {
  session_destroy();
  header('Location: /elms/student/login.php');
  exit;
}

/* Student course ids */
$courseIds = [];

if (table_exists($mysqli, 'enrollments') && table_exists($mysqli, 'batches')) {
  $sql = "
    SELECT DISTINCT b.course_id
    FROM enrollments e
    INNER JOIN batches b ON b.id = e.batch_id
    WHERE e.student_id = ?
      AND b.course_id IS NOT NULL
  ";

  $st = $mysqli->prepare($sql);

  if ($st) {
    $st->bind_param('i', $student_id);
    $st->execute();
    $rs = $st->get_result();

    while ($r = $rs->fetch_assoc()) {
      $cid = (int)($r['course_id'] ?? 0);
      if ($cid > 0) $courseIds[$cid] = $cid;
    }

    $st->close();
  }
}

if (!$courseIds && !empty($student['course_id'])) {
  $cid = (int)$student['course_id'];
  if ($cid > 0) $courseIds[$cid] = $cid;
}

/* Module table detect */
$moduleTable = null;

foreach (['course_modules', 'lms_modules'] as $tbl) {
  if (!table_exists($mysqli, $tbl)) continue;
  if (!col_exists($mysqli, $tbl, 'id') || !col_exists($mysqli, $tbl, 'course_id')) continue;

  $chk = $mysqli->prepare("SELECT id, course_id FROM `$tbl` WHERE id=? LIMIT 1");
  if ($chk) {
    $chk->bind_param('i', $module_id);
    $chk->execute();
    $found = $chk->get_result()->fetch_assoc();
    $chk->close();

    if ($found) {
      $moduleTable = $tbl;
      if ($course_id <= 0) $course_id = (int)$found['course_id'];
      break;
    }
  }
}

if (!$moduleTable) {
  $PAGE_TITLE = 'Lessons';
  $ACTIVE_MENU = 'lessons';
  require_once __DIR__ . '/studentlayout_top.php';
  ?>
  <div class="card soft-card">
    <div class="card-body text-center py-5">
      <i class="bi bi-exclamation-triangle fs-1 text-danger d-block mb-3"></i>
      <h2 class="h5 fw-bold">Module not found</h2>
      <p class="text-muted mb-0">This module does not exist.</p>
      <a href="/elms/student/modules.php" class="btn btn-primary mt-3">Back to Modules</a>
    </div>
  </div>
  <?php
  require_once __DIR__ . '/studentlayout_bottom.php';
  exit;
}

/* Security: student must own this course */
if ($course_id > 0 && $courseIds && !isset($courseIds[$course_id])) {
  $PAGE_TITLE = 'Access Denied';
  $ACTIVE_MENU = 'lessons';
  require_once __DIR__ . '/studentlayout_top.php';
  ?>
  <div class="card soft-card">
    <div class="card-body text-center py-5">
      <i class="bi bi-lock fs-1 text-warning d-block mb-3"></i>
      <h2 class="h5 fw-bold">Access denied</h2>
      <p class="text-muted mb-0">This module is not assigned to your course.</p>
      <a href="/elms/student/modules.php" class="btn btn-primary mt-3">Back to Modules</a>
    </div>
  </div>
  <?php
  require_once __DIR__ . '/studentlayout_bottom.php';
  exit;
}

$titleCol = col_exists($mysqli, $moduleTable, 'title') ? 'title' : (col_exists($mysqli, $moduleTable, 'name') ? 'name' : 'id');

/* Module details */
$sql = "
  SELECT 
    m.id,
    m.course_id,
    m.`$titleCol` AS title,
    c.course_name
  FROM `$moduleTable` m
  LEFT JOIN courses c ON c.id = m.course_id
  WHERE m.id = ?
  LIMIT 1
";

$st = $mysqli->prepare($sql);
$st->bind_param('i', $module_id);
$st->execute();
$module = $st->get_result()->fetch_assoc();
$st->close();

if (!$module) {
  header('Location: /elms/student/modules.php');
  exit;
}

$course_id = (int)$module['course_id'];

/* Content table detect */
$contentTable = null;

foreach (['lms_content', 'module_content', 'contents'] as $tbl) {
  if (table_exists($mysqli, $tbl) && col_exists($mysqli, $tbl, 'module_id')) {
    $contentTable = $tbl;
    break;
  }
}

/* Fetch content */
$items = [];

if ($contentTable) {
  $cols = [
    'id' => col_exists($mysqli, $contentTable, 'id') ? 'id' : null,
    'title' => col_exists($mysqli, $contentTable, 'title') ? 'title' : (col_exists($mysqli, $contentTable, 'name') ? 'name' : null),
    'type' => col_exists($mysqli, $contentTable, 'content_type') ? 'content_type' : (col_exists($mysqli, $contentTable, 'type') ? 'type' : null),
    'description' => col_exists($mysqli, $contentTable, 'description') ? 'description' : (col_exists($mysqli, $contentTable, 'body') ? 'body' : null),
    'file_path' => col_exists($mysqli, $contentTable, 'file_path') ? 'file_path' : (col_exists($mysqli, $contentTable, 'file') ? 'file' : (col_exists($mysqli, $contentTable, 'path') ? 'path' : null)),
    'url' => col_exists($mysqli, $contentTable, 'url') ? 'url' : (col_exists($mysqli, $contentTable, 'link') ? 'link' : null),
    'sort_order' => col_exists($mysqli, $contentTable, 'sort_order') ? 'sort_order' : null,
    'active' => col_exists($mysqli, $contentTable, 'active') ? 'active' : (col_exists($mysqli, $contentTable, 'is_active') ? 'is_active' : null),
    'require_paid' => col_exists($mysqli, $contentTable, 'require_paid') ? 'require_paid' : null,
  ];

  $select = [];
  $select[] = $cols['id'] ? "`{$cols['id']}` AS id" : "0 AS id";
  $select[] = $cols['title'] ? "`{$cols['title']}` AS title" : "CONCAT('Content #', id) AS title";
  $select[] = $cols['type'] ? "`{$cols['type']}` AS content_type" : "'link' AS content_type";
  $select[] = $cols['description'] ? "`{$cols['description']}` AS description" : "'' AS description";
  $select[] = $cols['file_path'] ? "`{$cols['file_path']}` AS file_path" : "'' AS file_path";
  $select[] = $cols['url'] ? "`{$cols['url']}` AS url" : "'' AS url";
  $select[] = $cols['require_paid'] ? "`{$cols['require_paid']}` AS require_paid" : "0 AS require_paid";

  $where = "module_id = ?";

  if ($cols['active']) {
    $where .= " AND (`{$cols['active']}` IS NULL OR `{$cols['active']}` IN (1,'1','active','Active','ACTIVE','yes','YES'))";
  }

  $orderBy = $cols['sort_order'] ? "`{$cols['sort_order']}` ASC, id ASC" : "id ASC";

  $sql = "
    SELECT " . implode(', ', $select) . "
    FROM `$contentTable`
    WHERE $where
    ORDER BY $orderBy
  ";

  $st = $mysqli->prepare($sql);
  $st->bind_param('i', $module_id);
  $st->execute();
  $rs = $st->get_result();

  while ($r = $rs->fetch_assoc()) {
    $items[] = $r;
  }

  $st->close();
}

/* Selected content */
$selected_id = (int)($_GET['content_id'] ?? 0);
$selected = null;

if ($items) {
  foreach ($items as $it) {
    if ((int)$it['id'] === $selected_id) {
      $selected = $it;
      break;
    }
  }

  if (!$selected) {
    $selected = $items[0];
  }
}

$PAGE_TITLE = 'Lessons';
$ACTIVE_MENU = 'lessons';
require_once __DIR__ . '/studentlayout_top.php';
?>

<div class="d-flex flex-column flex-lg-row justify-content-between align-items-lg-center gap-3 mb-4">
  <div>
    <h2 class="section-title mb-1"><?= h($module['title'] ?? 'Module') ?></h2>
    <div class="text-muted small">
      <?= h($module['course_name'] ?? ('Course #' . $course_id)) ?>
      · Module ID: <?= (int)$module_id ?>
    </div>
  </div>

  <div class="d-flex gap-2">
    <a href="/elms/student/modules.php" class="btn btn-outline-secondary btn-sm rounded-pill">
      <i class="bi bi-arrow-left me-1"></i> Back
    </a>

    <a href="/elms/student/assessments/index.php?module_id=<?= (int)$module_id ?>" class="btn btn-primary btn-sm rounded-pill">
      <i class="bi bi-clipboard-check me-1"></i> Assessments
    </a>
  </div>
</div>

<?php if (!$contentTable): ?>

  <div class="card soft-card">
    <div class="card-body text-center py-5">
      <i class="bi bi-folder-x fs-1 text-danger d-block mb-3"></i>
      <h2 class="h5 fw-bold">Content table not found</h2>
      <p class="text-muted mb-0">Need lms_content table with module_id column.</p>
    </div>
  </div>

<?php elseif (!$items): ?>

  <div class="card soft-card">
    <div class="card-body text-center py-5">
      <i class="bi bi-journal-x fs-1 text-muted d-block mb-3"></i>
      <h2 class="h5 fw-bold">No lessons added yet</h2>
      <p class="text-muted mb-0">
        Admin has not added PDF / video / link / text content for this module yet.
      </p>
      <div class="small text-muted mt-3">
        Current content table: <strong><?= h($contentTable) ?></strong>
      </div>
    </div>
  </div>

<?php else: ?>

  <div class="row g-4">

    <div class="col-xl-4">
      <div class="card soft-card lesson-list-card">
        <div class="card-header bg-white border-0 pt-4 px-4">
          <div class="d-flex justify-content-between align-items-center">
            <div>
              <h3 class="section-title">Lesson List</h3>
              <div class="text-muted small"><?= count($items) ?> item(s)</div>
            </div>
          </div>
        </div>

        <div class="card-body px-4 pb-4">
          <?php foreach ($items as $it): ?>
            <?php
              $id = (int)$it['id'];
              $active = ($selected && (int)$selected['id'] === $id) ? 'active' : '';
              $type = strtolower((string)($it['content_type'] ?? 'link'));
            ?>

            <a class="lesson-link <?= $active ?>"
               href="/elms/student/module_content.php?course_id=<?= (int)$course_id ?>&module_id=<?= (int)$module_id ?>&content_id=<?= $id ?>">
              <div class="lesson-icon">
                <i class="bi <?= h(icon_for_type($type)) ?>"></i>
              </div>

              <div class="flex-grow-1">
                <div class="lesson-title"><?= h($it['title'] ?? 'Untitled') ?></div>
                <div class="lesson-meta">
                  <?= h(strtoupper($type)) ?>
                </div>
              </div>
            </a>
          <?php endforeach; ?>
        </div>
      </div>
    </div>

    <div class="col-xl-8">
      <div class="card soft-card">
        <div class="card-body p-4">

          <?php if ($selected): ?>
            <?php
              $type = strtolower((string)($selected['content_type'] ?? 'link'));
              $file = content_href($selected['file_path'] ?? '');
              $url  = content_href($selected['url'] ?? '');
              $open = $url ?: $file;
              $desc = (string)($selected['description'] ?? '');
            ?>

            <div class="d-flex flex-column flex-md-row justify-content-between gap-3 mb-4">
              <div>
                <span class="badge <?= h(badge_for_type($type)) ?> rounded-pill mb-2">
                  <?= h(strtoupper($type)) ?>
                </span>
                <h3 class="h4 fw-black mb-1"><?= h($selected['title'] ?? 'Lesson') ?></h3>

                <?php if (!empty($selected['require_paid'])): ?>
                  <div class="small text-warning">
                    <i class="bi bi-lock-fill me-1"></i> This content may require completed payment.
                  </div>
                <?php endif; ?>
              </div>

              <?php if ($open): ?>
                <a href="<?= h($open) ?>" target="_blank" rel="noopener" class="btn btn-primary rounded-pill align-self-start">
                  <i class="bi bi-box-arrow-up-right me-1"></i> Open
                </a>
              <?php endif; ?>
            </div>

            <?php if ($desc): ?>
              <div class="lesson-description mb-4">
                <?= nl2br(h(strip_tags($desc))) ?>
              </div>
            <?php endif; ?>

            <?php if ($type === 'video' && $open): ?>

              <div class="ratio ratio-16x9 rounded-4 overflow-hidden bg-dark">
                <?php if (preg_match('#\.(mp4|webm|mov|mkv)$#i', $open)): ?>
                  <video src="<?= h($open) ?>" controls style="width:100%;height:100%;"></video>
                <?php else: ?>
                  <iframe src="<?= h($open) ?>" allowfullscreen></iframe>
                <?php endif; ?>
              </div>

            <?php elseif ($type === 'pdf' && $open): ?>

              <div class="pdf-box">
                <iframe src="<?= h($open) ?>"></iframe>
              </div>

            <?php elseif ($type === 'link' && $open): ?>

              <div class="open-box text-center">
                <i class="bi bi-link-45deg fs-1 text-primary d-block mb-3"></i>
                <h4 class="fw-bold">External Learning Link</h4>
                <p class="text-muted">Click the button below to open this lesson.</p>
                <a href="<?= h($open) ?>" target="_blank" rel="noopener" class="btn btn-primary rounded-pill">
                  Open Link
                </a>
              </div>

            <?php elseif ($type === 'text'): ?>

              <div class="text-content-box">
                <?php if ($desc): ?>
                  <?= nl2br(h(strip_tags($desc))) ?>
                <?php else: ?>
                  <div class="text-muted">No text content available.</div>
                <?php endif; ?>
              </div>

            <?php elseif (in_array($type, ['quiz', 'game'], true) && $open): ?>

              <div class="open-box text-center">
                <i class="bi <?= $type === 'quiz' ? 'bi-question-circle' : 'bi-controller' ?> fs-1 text-primary d-block mb-3"></i>
                <h4 class="fw-bold"><?= $type === 'quiz' ? 'Quiz' : 'Game Activity' ?></h4>
                <p class="text-muted">Click below to start.</p>
                <a href="<?= h($open) ?>" target="_blank" rel="noopener" class="btn btn-primary rounded-pill">
                  <?= $type === 'quiz' ? 'Start Quiz' : 'Start Game' ?>
                </a>
              </div>

            <?php elseif ($open): ?>

              <div class="open-box text-center">
                <i class="bi bi-file-earmark fs-1 text-primary d-block mb-3"></i>
                <h4 class="fw-bold">Learning File</h4>
                <p class="text-muted">Open or download this content file.</p>
                <a href="<?= h($open) ?>" target="_blank" rel="noopener" class="btn btn-primary rounded-pill">
                  Open File
                </a>
              </div>

            <?php else: ?>

              <div class="alert alert-info mb-0">
                No file or URL attached for this lesson.
              </div>

            <?php endif; ?>

          <?php endif; ?>

        </div>
      </div>
    </div>

  </div>

<?php endif; ?>

<style>
  .fw-black{
    font-weight:900;
  }

  .lesson-list-card{
    position:sticky;
    top:96px;
  }

  .lesson-link{
    display:flex;
    gap:12px;
    padding:13px;
    border:1px solid rgba(15,23,42,.08);
    border-radius:16px;
    color:#0f172a;
    text-decoration:none;
    background:#fff;
    margin-bottom:10px;
    transition:.15s ease;
  }

  .lesson-link:hover{
    transform:translateY(-1px);
    box-shadow:0 12px 25px rgba(15,23,42,.08);
  }

  .lesson-link.active{
    border-color:#2563eb;
    background:#eef4ff;
  }

  .lesson-icon{
    width:42px;
    height:42px;
    border-radius:14px;
    background:#f1f5f9;
    color:#2563eb;
    display:grid;
    place-items:center;
    flex:0 0 auto;
    font-size:20px;
  }

  .lesson-link.active .lesson-icon{
    background:#2563eb;
    color:#fff;
  }

  .lesson-title{
    font-weight:800;
    line-height:1.25;
  }

  .lesson-meta{
    font-size:12px;
    color:#64748b;
    margin-top:2px;
  }

  .lesson-description{
    background:#f8fafc;
    border:1px solid rgba(15,23,42,.08);
    border-radius:18px;
    padding:16px;
    color:#334155;
  }

  .pdf-box{
    width:100%;
    height:72vh;
    border:1px solid rgba(15,23,42,.1);
    border-radius:18px;
    overflow:hidden;
    background:#f8fafc;
  }

  .pdf-box iframe{
    width:100%;
    height:100%;
    border:0;
  }

  .open-box{
    border:1px dashed rgba(37,99,235,.35);
    background:#f8fafc;
    border-radius:22px;
    padding:50px 20px;
  }

  .text-content-box{
    background:#fff;
    border:1px solid rgba(15,23,42,.08);
    border-radius:18px;
    padding:20px;
    line-height:1.75;
  }

  @media(max-width: 1200px){
    .lesson-list-card{
      position:static;
    }
  }
</style>

<?php require_once __DIR__ . '/studentlayout_bottom.php'; ?>