<?php
// /elms/student/modules.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('/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;
}

$student_id = (int)$_SESSION['student_id'];

/* 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;
}

/* Get student course ids */
$courseIds = [];
$courses = [];
$batches = [];

if (table_exists($mysqli, 'enrollments') && table_exists($mysqli, 'batches')) {
  $sql = "
    SELECT DISTINCT
      b.id AS batch_id,
      b.batch_name,
      b.batch_code,
      b.course_id,
      c.course_name
    FROM enrollments e
    INNER JOIN batches b ON b.id = e.batch_id
    LEFT JOIN courses c ON c.id = b.course_id
    WHERE e.student_id = ?
      AND b.course_id IS NOT NULL
    ORDER BY b.id DESC
  ";

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

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

    while ($row = $rs->fetch_assoc()) {
      $cid = (int)($row['course_id'] ?? 0);

      if ($cid > 0) {
        $courseIds[$cid] = $cid;
        $courses[$cid] = [
          'id' => $cid,
          'course_name' => $row['course_name'] ?: ('Course #' . $cid),
        ];

        $batches[$cid][] = [
          'batch_id' => (int)$row['batch_id'],
          'batch_name' => $row['batch_name'] ?: ($row['batch_code'] ?: 'Batch'),
          'batch_code' => $row['batch_code'] ?? '',
        ];
      }
    }

    $st->close();
  }
}

/* Fallback: studentss.course_id */
if (!$courseIds && !empty($student['course_id'])) {
  $cid = (int)$student['course_id'];
  $courseIds[$cid] = $cid;

  $courseName = 'Course #' . $cid;

  if (table_exists($mysqli, 'courses')) {
    $q = $mysqli->query("SELECT course_name FROM courses WHERE id={$cid} LIMIT 1");
    $r = $q ? $q->fetch_assoc() : null;
    if ($r && !empty($r['course_name'])) {
      $courseName = $r['course_name'];
    }
  }

  $courses[$cid] = [
    'id' => $cid,
    'course_name' => $courseName,
  ];
}

/* Choose correct modules table */
$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;

  if ($courseIds) {
    $ids = implode(',', array_map('intval', array_values($courseIds)));
    $q = $mysqli->query("SELECT COUNT(*) AS n FROM `$tbl` WHERE course_id IN ($ids)");
    $r = $q ? $q->fetch_assoc() : null;

    if ((int)($r['n'] ?? 0) > 0) {
      $moduleTable = $tbl;
      break;
    }
  }

  if ($moduleTable === null) {
    $moduleTable = $tbl;
  }
}

$titleCol = null;
$orderCol = null;

if ($moduleTable) {
  $titleCol = col_exists($mysqli, $moduleTable, 'title') ? 'title' : (col_exists($mysqli, $moduleTable, 'name') ? 'name' : 'id');
  $orderCol = col_exists($mysqli, $moduleTable, 'sort_order') ? 'sort_order' : 'id';
}

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

/* Assessment table */
$assessmentTable = null;
foreach (['lms_assessments', 'assessments', 'assignments', 'course_assessments'] as $tbl) {
  if (table_exists($mysqli, $tbl)) {
    $assessmentTable = $tbl;
    break;
  }
}

/* Fetch modules */
$modulesByCourse = [];
$totalModules = 0;
$totalContent = 0;
$totalAssessments = 0;

if ($courseIds && $moduleTable) {
  $ids = implode(',', array_map('intval', array_values($courseIds)));

  $sql = "
    SELECT
      m.id,
      m.course_id,
      m.`$titleCol` AS title,
      COALESCE(ms.semester_no, 1) AS semester_no
    FROM `$moduleTable` m
    LEFT JOIN elms_module_semesters ms ON ms.module_id = m.id
    WHERE m.course_id IN ($ids)
    ORDER BY m.course_id ASC, semester_no ASC, m.`$orderCol` ASC, m.id ASC
  ";

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

  while ($q && $m = $q->fetch_assoc()) {
    $mid = (int)$m['id'];
    $cid = (int)$m['course_id'];
    $sem = (int)($m['semester_no'] ?? 1);
    if ($sem <= 0) $sem = 1;

    $m['content_count'] = 0;
    $m['assessment_count'] = 0;

    if (!isset($modulesByCourse[$cid])) {
      $modulesByCourse[$cid] = [];
    }

    if (!isset($modulesByCourse[$cid][$sem])) {
      $modulesByCourse[$cid][$sem] = [];
    }

    $modulesByCourse[$cid][$sem][$mid] = $m;
    $totalModules++;
  }
}

/* Add content counts */
if ($contentTable && $modulesByCourse) {
  $allModuleIds = [];

  foreach ($modulesByCourse as $cid => $sems) {
    foreach ($sems as $sem => $mods) {
      foreach ($mods as $mid => $m) {
        $allModuleIds[] = (int)$mid;
      }
    }
  }

  if ($allModuleIds) {
    $midList = implode(',', array_map('intval', $allModuleIds));

    $activeSql = '';
    if (col_exists($mysqli, $contentTable, 'active')) {
      $activeSql = " AND active IN (1,'1','active','Active','ACTIVE')";
    }

    $q = $mysqli->query("
      SELECT module_id, COUNT(*) AS n
      FROM `$contentTable`
      WHERE module_id IN ($midList)
      $activeSql
      GROUP BY module_id
    ");

    while ($q && $r = $q->fetch_assoc()) {
      $mid = (int)$r['module_id'];
      $cnt = (int)$r['n'];
      $totalContent += $cnt;

      foreach ($modulesByCourse as $cid => $sems) {
        foreach ($sems as $sem => $mods) {
          if (isset($modulesByCourse[$cid][$sem][$mid])) {
            $modulesByCourse[$cid][$sem][$mid]['content_count'] = $cnt;
          }
        }
      }
    }
  }
}

/* Add assessment counts */
if ($assessmentTable && $modulesByCourse) {
  $moduleCol = col_exists($mysqli, $assessmentTable, 'module_id') ? 'module_id' : null;
  $courseCol = col_exists($mysqli, $assessmentTable, 'course_id') ? 'course_id' : null;
  $activeCol = col_exists($mysqli, $assessmentTable, 'active') ? 'active' : (col_exists($mysqli, $assessmentTable, 'is_active') ? 'is_active' : null);

  if ($moduleCol) {
    $allModuleIds = [];

    foreach ($modulesByCourse as $cid => $sems) {
      foreach ($sems as $sem => $mods) {
        foreach ($mods as $mid => $m) {
          $allModuleIds[] = (int)$mid;
        }
      }
    }

    if ($allModuleIds) {
      $midList = implode(',', array_map('intval', $allModuleIds));
      $where = "`$moduleCol` IN ($midList)";

      if ($activeCol) {
        $where .= " AND `$activeCol` IN (1,'1','active','Active','ACTIVE','yes','YES')";
      }

      $q = $mysqli->query("
        SELECT `$moduleCol` AS module_id, COUNT(*) AS n
        FROM `$assessmentTable`
        WHERE $where
        GROUP BY `$moduleCol`
      ");

      while ($q && $r = $q->fetch_assoc()) {
        $mid = (int)$r['module_id'];
        $cnt = (int)$r['n'];
        $totalAssessments += $cnt;

        foreach ($modulesByCourse as $cid => $sems) {
          foreach ($sems as $sem => $mods) {
            if (isset($modulesByCourse[$cid][$sem][$mid])) {
              $modulesByCourse[$cid][$sem][$mid]['assessment_count'] = $cnt;
            }
          }
        }
      }
    }
  } elseif ($courseCol && $courseIds) {
    $ids = implode(',', array_map('intval', array_values($courseIds)));
    $where = "`$courseCol` IN ($ids)";

    if ($activeCol) {
      $where .= " AND `$activeCol` IN (1,'1','active','Active','ACTIVE','yes','YES')";
    }

    $q = $mysqli->query("
      SELECT `$courseCol` AS course_id, COUNT(*) AS n
      FROM `$assessmentTable`
      WHERE $where
      GROUP BY `$courseCol`
    ");

    while ($q && $r = $q->fetch_assoc()) {
      $cid = (int)$r['course_id'];
      $cnt = (int)$r['n'];
      $totalAssessments += $cnt;
    }
  }
}

$PAGE_TITLE = 'My Modules';
$ACTIVE_MENU = 'modules';
require_once __DIR__ . '/studentlayout_top.php';
?>

<div class="row g-4 mb-4">

  <div class="col-md-4">
    <div class="card stat-card">
      <div class="card-body d-flex align-items-center gap-3">
        <div class="stat-icon">
          <i class="bi bi-journal-bookmark"></i>
        </div>
        <div>
          <div class="stat-label">Total Modules</div>
          <div class="stat-value"><?= (int)$totalModules ?></div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-md-4">
    <div class="card stat-card">
      <div class="card-body d-flex align-items-center gap-3">
        <div class="stat-icon">
          <i class="bi bi-play-circle"></i>
        </div>
        <div>
          <div class="stat-label">Lessons / Content</div>
          <div class="stat-value"><?= (int)$totalContent ?></div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-md-4">
    <div class="card stat-card">
      <div class="card-body d-flex align-items-center gap-3">
        <div class="stat-icon">
          <i class="bi bi-clipboard-check"></i>
        </div>
        <div>
          <div class="stat-label">Assessments</div>
          <div class="stat-value"><?= (int)$totalAssessments ?></div>
        </div>
      </div>
    </div>
  </div>

</div>

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

  <div class="card soft-card">
    <div class="card-body text-center py-5">
      <i class="bi bi-info-circle fs-1 text-warning d-block mb-3"></i>
      <h2 class="h5 fw-bold">Course enrollment not found</h2>
      <p class="text-muted mb-0">
        This student is not linked with a course or batch. Please check studentss.course_id or enrollments table.
      </p>
    </div>
  </div>

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

  <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">Modules table not found</h2>
      <p class="text-muted mb-0">
        Need course_modules or lms_modules table with id and course_id columns.
      </p>
    </div>
  </div>

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

  <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 modules added yet</h2>
      <p class="text-muted mb-0">
        Modules were not found for this student's course.
      </p>
      <div class="small text-muted mt-3">
        Current module table: <strong><?= h($moduleTable) ?></strong>
      </div>
    </div>
  </div>

<?php else: ?>

  <?php foreach ($courseIds as $cid): ?>
    <?php
      $courseName = $courses[$cid]['course_name'] ?? ('Course #' . $cid);
      $courseBatchList = $batches[$cid] ?? [];
      $semGroups = $modulesByCourse[$cid] ?? [];
    ?>

    <div class="card soft-card mb-4">
      <div class="card-body">

        <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"><?= h($courseName) ?></h2>
            <div class="text-muted small mt-1">
              Course ID: <?= (int)$cid ?>
              <?php if ($courseBatchList): ?>
                ·
                <?php foreach ($courseBatchList as $b): ?>
                  <span class="badge badge-soft-blue rounded-pill me-1">
                    <?= h($b['batch_name']) ?>
                  </span>
                <?php endforeach; ?>
              <?php endif; ?>
            </div>
          </div>

          <div class="d-flex gap-2">
            <a href="/elms/student/assessments/index.php" class="btn btn-outline-primary btn-sm rounded-pill">
              <i class="bi bi-clipboard-check me-1"></i> Assessments
            </a>
          </div>
        </div>

        <?php if (!$semGroups): ?>
          <div class="alert alert-warning mb-0">
            No modules found for this course.
          </div>
        <?php else: ?>

          <?php foreach ($semGroups as $semNo => $mods): ?>
            <div class="mb-4">
              <div class="d-flex align-items-center gap-2 mb-3">
                <div style="width:38px;height:38px;border-radius:14px;background:#eef4ff;color:#2563eb;display:grid;place-items:center;">
                  <i class="bi bi-layers"></i>
                </div>
                <div>
                  <div class="fw-black fw-bold">Semester <?= (int)$semNo ?></div>
                  <div class="small text-muted"><?= count($mods) ?> module(s)</div>
                </div>
              </div>

              <div class="row g-3">
                <?php foreach ($mods as $m): ?>
                  <?php
                    $mid = (int)$m['id'];
                    $contentCount = (int)($m['content_count'] ?? 0);
                    $assessmentCount = (int)($m['assessment_count'] ?? 0);
                  ?>

                  <div class="col-md-6 col-xl-4">
                    <div class="border rounded-4 p-3 h-100 bg-white module-card">
                      <div class="d-flex gap-3">
                        <div style="width:46px;height:46px;border-radius:16px;background:#f1f5f9;color:#1e3a8a;display:grid;place-items:center;flex:0 0 auto;">
                          <i class="bi bi-journal-code fs-4"></i>
                        </div>

                        <div class="flex-grow-1">
                          <div class="fw-bold mb-1">
                            <?= h($m['title']) ?>
                          </div>

                          <div class="d-flex flex-wrap gap-2 mb-3">
                            <span class="badge badge-soft-blue rounded-pill">
                              <?= (int)$contentCount ?> Lesson(s)
                            </span>

                            <span class="badge badge-soft-yellow rounded-pill">
                              <?= (int)$assessmentCount ?> Assessment(s)
                            </span>
                          </div>

                          <div class="d-flex flex-wrap gap-2">
                            <a href="/elms/student/module_content.php?module_id=<?= $mid ?>&course_id=<?= (int)$cid ?>"
                               class="btn btn-primary btn-sm rounded-pill">
                              <i class="bi bi-play-circle me-1"></i> Start Learning
                            </a>

                            <a href="/elms/student/assessments/index.php?module_id=<?= $mid ?>"
                               class="btn btn-outline-secondary btn-sm rounded-pill">
                              <i class="bi bi-clipboard-check me-1"></i> Tasks
                            </a>
                          </div>

                          <div class="small text-muted mt-3">
                            Module ID: <?= $mid ?>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>

                <?php endforeach; ?>
              </div>
            </div>
          <?php endforeach; ?>

        <?php endif; ?>

      </div>
    </div>

  <?php endforeach; ?>

<?php endif; ?>

<style>
  .module-card{
    transition:.15s ease;
  }

  .module-card:hover{
    transform:translateY(-2px);
    box-shadow:0 14px 28px rgba(15,23,42,.08);
  }

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

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