<?php
// /elms/student/index.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/index.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 money_lkr(float $amount): string {
  return 'LKR ' . number_format($amount, 2);
}

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

$student = null;

$studentCols = "id, full_name, academic_email, center_reg_no, reference_no, mobile, 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'] ?? '');

$studentName = $student['full_name'] ?? 'Student';

/* Courses + batches */
$courses = [];
$courseIds = [];
$batchNames = [];

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 = ?
    ORDER BY b.id DESC
  ";

  $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;
        $courses[$cid] = $r['course_name'] ?: ('Course #' . $cid);
      }

      if (!empty($r['batch_name'])) {
        $batchNames[] = $r['batch_name'];
      } elseif (!empty($r['batch_code'])) {
        $batchNames[] = $r['batch_code'];
      }
    }

    $st->close();
  }
}

/* Fallback studentss.course_id */
if (!$courseIds && !empty($student['course_id'])) {
  $cid = (int)$student['course_id'];
  $courseIds[$cid] = $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;
    $courses[$cid] = $r['course_name'] ?? ('Course #' . $cid);
  }
}

/* Module count */
$moduleCount = 0;
$moduleTable = null;

foreach (['course_modules', 'lms_modules'] as $tbl) {
  if (table_exists($mysqli, $tbl) && col_exists($mysqli, $tbl, 'id') && col_exists($mysqli, $tbl, 'course_id')) {
    $moduleTable = $tbl;
    break;
  }
}

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

/* Assessment count */
$pendingAssessments = 0;
$assessmentTable = null;

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

if ($assessmentTable) {
  $idCol = col_exists($mysqli, $assessmentTable, 'id') ? 'id' : 'assessment_id';
  $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);

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

  if ($courseCol && $courseIds) {
    $ids = implode(',', array_map('intval', array_values($courseIds)));
    $where[] = "`$courseCol` IN ($ids)";
  }

  $whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

  $q = $mysqli->query("SELECT COUNT(*) AS n FROM `$assessmentTable` $whereSql");
  $r = $q ? $q->fetch_assoc() : null;
  $pendingAssessments = (int)($r['n'] ?? 0);
}

/* Payments summary */
$totalPaid = 0.0;

if (table_exists($mysqli, 'payments')) {
  $amountCol = col_exists($mysqli, 'payments', 'amount') ? 'amount' : null;
  $studentCol = col_exists($mysqli, 'payments', 'student_id') ? 'student_id' : null;

  if ($amountCol && $studentCol) {
    $st = $mysqli->prepare("SELECT COALESCE(SUM(`$amountCol`),0) AS paid FROM payments WHERE `$studentCol`=?");
    $st->bind_param('i', $student_id);
    $st->execute();
    $r = $st->get_result()->fetch_assoc();
    $st->close();
    $totalPaid = (float)($r['paid'] ?? 0);
  }
}

$paymentStatus = $totalPaid > 0 ? 'Paid' : 'Pending';

/* Recent notices placeholder */
$notices = [];

foreach (['lms_notices', 'notices', 'student_notices'] as $tbl) {
  if (!table_exists($mysqli, $tbl)) continue;

  $titleCol = col_exists($mysqli, $tbl, 'title') ? 'title' : (col_exists($mysqli, $tbl, 'subject') ? 'subject' : null);
  $bodyCol = col_exists($mysqli, $tbl, 'message') ? 'message' : (col_exists($mysqli, $tbl, 'body') ? 'body' : (col_exists($mysqli, $tbl, 'description') ? 'description' : null));
  $dateCol = col_exists($mysqli, $tbl, 'created_at') ? 'created_at' : (col_exists($mysqli, $tbl, 'date') ? 'date' : 'id');

  if (!$titleCol) continue;

  $sql = "SELECT `$titleCol` AS title";
  $sql .= $bodyCol ? ", `$bodyCol` AS body" : ", '' AS body";
  $sql .= " FROM `$tbl` ORDER BY `$dateCol` DESC LIMIT 3";

  $q = $mysqli->query($sql);
  while ($q && $r = $q->fetch_assoc()) {
    $notices[] = $r;
  }

  break;
}

/* Page layout */
$PAGE_TITLE = 'Dashboard';
$ACTIVE_MENU = 'dashboard';
require_once __DIR__ . '/studentlayout_top.php';
?>

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

  <div class="col-md-6 col-xl-3">
    <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">My Modules</div>
          <div class="stat-value"><?= (int)$moduleCount ?></div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-md-6 col-xl-3">
    <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)$pendingAssessments ?></div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-md-6 col-xl-3">
    <div class="card stat-card">
      <div class="card-body d-flex align-items-center gap-3">
        <div class="stat-icon">
          <i class="bi bi-credit-card"></i>
        </div>
        <div>
          <div class="stat-label">Payment</div>
          <div class="stat-value" style="font-size:18px;">
            <?= h($paymentStatus) ?>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-md-6 col-xl-3">
    <div class="card stat-card">
      <div class="card-body d-flex align-items-center gap-3">
        <div class="stat-icon">
          <i class="bi bi-person-check"></i>
        </div>
        <div>
          <div class="stat-label">LMS Status</div>
          <div class="stat-value" style="font-size:18px;">
            <?= h($student['lms_status'] ?? 'Active') ?>
          </div>
        </div>
      </div>
    </div>
  </div>

</div>

<div class="row g-4">

  <div class="col-xl-8">
    <div class="card soft-card mb-4">
      <div class="card-body">
        <div class="d-flex justify-content-between align-items-start mb-3">
          <div>
            <h2 class="section-title">My Course</h2>
            <div class="text-muted small">Your enrolled course and batch details</div>
          </div>
          <a href="/elms/student/modules.php" class="btn btn-primary btn-sm">
            Open Modules
          </a>
        </div>

        <?php if (!$courses): ?>
          <div class="alert alert-warning mb-0">
            Course enrollment not found. Please contact your coordinator.
          </div>
        <?php else: ?>
          <div class="row g-3">
            <?php foreach ($courses as $cid => $cname): ?>
              <div class="col-md-6">
                <div class="border rounded-4 p-3 h-100">
                  <div class="fw-bold"><?= h($cname) ?></div>
                  <div class="small text-muted mt-1">Course ID: <?= (int)$cid ?></div>
                  <?php if ($batchNames): ?>
                    <div class="mt-2">
                      <?php foreach (array_unique($batchNames) as $bn): ?>
                        <span class="badge badge-soft-blue rounded-pill me-1"><?= h($bn) ?></span>
                      <?php endforeach; ?>
                    </div>
                  <?php endif; ?>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <div class="card soft-card">
      <div class="card-body">
        <div class="d-flex justify-content-between align-items-center mb-3">
          <div>
            <h2 class="section-title">Quick Actions</h2>
            <div class="text-muted small">Common student portal actions</div>
          </div>
        </div>

        <div class="row g-3">
          <div class="col-md-4">
            <a href="/elms/student/modules.php" class="btn btn-outline-primary w-100 py-3 rounded-4">
              <i class="bi bi-journal-bookmark d-block fs-3 mb-1"></i>
              My Modules
            </a>
          </div>

          <div class="col-md-4">
            <a href="/elms/student/assessments/index.php" class="btn btn-outline-primary w-100 py-3 rounded-4">
              <i class="bi bi-clipboard-check d-block fs-3 mb-1"></i>
              Assessments
            </a>
          </div>

          <div class="col-md-4">
            <a href="/elms/student/payments.php" class="btn btn-outline-primary w-100 py-3 rounded-4">
              <i class="bi bi-credit-card d-block fs-3 mb-1"></i>
              Payments
            </a>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-xl-4">

    <div class="card soft-card mb-4">
      <div class="card-body">
        <h2 class="section-title mb-3">Student Profile</h2>

        <div class="mb-3">
          <div class="small text-muted">Name</div>
          <div class="fw-bold"><?= h($studentName) ?></div>
        </div>

        <div class="mb-3">
          <div class="small text-muted">Center Reg No</div>
          <div class="fw-bold"><?= h($student['center_reg_no'] ?? '-') ?></div>
        </div>

        <div class="mb-3">
          <div class="small text-muted">Reference No</div>
          <div class="fw-bold"><?= h($student['reference_no'] ?? '-') ?></div>
        </div>

        <div class="mb-0">
          <div class="small text-muted">Academic Email</div>
          <div class="fw-bold text-break"><?= h($student['academic_email'] ?? '-') ?></div>
        </div>
      </div>
    </div>

    <div class="card soft-card">
      <div class="card-body">
        <div class="d-flex justify-content-between align-items-center mb-3">
          <h2 class="section-title">Latest Notices</h2>
          <a href="/elms/student/notices.php" class="small text-decoration-none">View all</a>
        </div>

        <?php if (!$notices): ?>
          <div class="text-muted small">No notices available yet.</div>
        <?php else: ?>
          <?php foreach ($notices as $notice): ?>
            <div class="border-bottom pb-3 mb-3">
              <div class="fw-bold"><?= h($notice['title'] ?? 'Notice') ?></div>
              <?php if (!empty($notice['body'])): ?>
                <div class="small text-muted mt-1">
                  <?= h(mb_strimwidth(strip_tags((string)$notice['body']), 0, 90, '...')) ?>
                </div>
              <?php endif; ?>
            </div>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>
    </div>

  </div>

</div>

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