<?php
// /elms/lecturer/assessments/index.php — Assessments list (Pending by default)
declare(strict_types=1);
@header('Content-Type: text/html; charset=utf-8');
date_default_timezone_set('Asia/Colombo');

/* -------------------- SESSION (cookie scope fix) -------------------- */
/* Make sure the same session cookie is visible to ALL ELMS pages */
if (session_status() === PHP_SESSION_NONE) {
  $isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
             || (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443);
  session_set_cookie_params([
    'lifetime' => 0,
    'path'     => '/elms/',                 // IMPORTANT: not /student or /lecturer
    'domain'   => 'admin.edencampus.lk',    // EXACT host you use
    'secure'   => $isHttps,
    'httponly' => true,
    'samesite' => 'Lax',
  ]);
  session_start();
}

/* -------------------- DIAGNOSTIC (optional) -------------------- */
/* Visit this page with ?debug=1 to see your current $_SESSION keys */
if (isset($_GET['debug'])) {
  header('Content-Type: text/plain; charset=utf-8');
  echo "SESSION DUMP\n------------\n";
  print_r($_SESSION);
  exit;
}

/* ------------------------- AUTH GUARD -------------------------- */
/* Accept user id / role from multiple possible keys used across ELMS */
$uid =
  ($_SESSION['elms_user_id'] ?? null) ??
  ($_SESSION['user']['id']   ?? null) ??
  ($_SESSION['user_id']      ?? null) ??
  ($_SESSION['staff_id']     ?? null) ??
  ($_SESSION['lecturer_id']  ?? null);

$roleCandidates = [
  $_SESSION['role_code']        ?? null,
  $_SESSION['elms_role_code']   ?? null,
  $_SESSION['user']['role']     ?? null,
  $_SESSION['role']             ?? null,
  $_SESSION['user_role']        ?? null,
  $_SESSION['designation']      ?? null,
  $_SESSION['type']             ?? null,
  $_SESSION['user_type']        ?? null,
];
$role = strtolower((string)array_values(array_filter($roleCandidates))[0] ?? '');

$allowedRoles = ['lecturer','teacher','instructor','faculty','course_coordinator','coordinator','admin','super_admin','branch_admin','staff'];
$allowed = ($uid && ($role && in_array($role, $allowedRoles, true))) || isset($_SESSION['lecturer_id']);

if (!$allowed) {
  http_response_code(403);
  echo 'Forbidden';
  exit;
}

/* ----------------------- DB BOOTSTRAP -------------------------- */
function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); }

$ROOT = rtrim($_SERVER['DOCUMENT_ROOT'] ?? dirname(__DIR__,2), '/');
$tried=[]; $try=function(string $p)use(&$tried){ $tried[]=$p; if(is_file($p)){ require_once $p; return true; } return false; };
$try($ROOT.'/elms/includes/db.php') || $try(__DIR__.'/../../includes/db.php') || $try(__DIR__.'/../includes/db.php');

if (!isset($mysqli) || !($mysqli instanceof mysqli)) { if (isset($conn) && $conn instanceof mysqli) $mysqli = $conn; }
if (!isset($mysqli) || !($mysqli instanceof mysqli)) { http_response_code(500); echo "<h3>DB not initialized</h3><pre>".esc(implode("\n",$tried))."</pre>"; exit; }
@$mysqli->set_charset('utf8mb4');

/* ------------------------- UTILITIES --------------------------- */
function col_exists(mysqli $db,string $t,string $c):bool{
  $t=str_replace('`','``',$t); $c=$db->real_escape_string($c);
  $r=$db->query("SHOW COLUMNS FROM `$t` LIKE '$c'"); $ok=$r && $r->num_rows>0; if($r) $r->free(); return $ok;
}

/* --------------- DYNAMIC TABLE/COLUMN DISCOVERY --------------- */
$assTitleCol = col_exists($mysqli,'lms_assessments','title') ? 'title'
              : (col_exists($mysqli,'lms_assessments','name') ? 'name' : 'id');

$studentTable = 'studentss';
if ($mysqli->query("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='studentss'")->num_rows === 0) {
  if ($mysqli->query("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='students'")->num_rows > 0) {
    $studentTable='students';
  }
}
$stuNameCol   = col_exists($mysqli,$studentTable,'full_name') ? 'full_name'
              : (col_exists($mysqli,$studentTable,'name') ? 'name' : 'id');

/* Submission columns to detect publication */
$HAS_WF   = col_exists($mysqli,'lms_submissions','workflow_status');
$HAS_PUB1 = col_exists($mysqli,'lms_submissions','is_published');
$HAS_PUB2 = col_exists($mysqli,'lms_submissions','published');
$HAS_REL  = col_exists($mysqli,'lms_submissions','release_at');
$HAS_FIN  = col_exists($mysqli,'lms_submissions','final_score');

/* --------------------------- FILTERS --------------------------- */
$search = trim((string)($_GET['q'] ?? ''));
$limit  = max(1, min(100, (int)($_GET['limit'] ?? 20)));
$view   = ($_GET['view'] ?? 'pending'); // pending | all

/* -------- BUILD WHERE for "Pending only" (not published) ------- */
$pubParts = [];
if ($HAS_WF)   $pubParts[] = "LOWER(s.workflow_status) IN ('released','published','approved','graded_final')";
if ($HAS_PUB1) $pubParts[] = "s.is_published = 1";
if ($HAS_PUB2) $pubParts[] = "s.published = 1";
if ($HAS_REL)  $pubParts[] = "s.release_at IS NOT NULL";
$PUBLISHED_SQL = $pubParts ? '('.implode(' OR ', $pubParts).')' : '0';

$PENDING_SQL = 'NOT '.$PUBLISHED_SQL;
if ($PUBLISHED_SQL === '0') {
  $PENDING_SQL = $HAS_FIN ? 's.final_score IS NULL' : '1';
}

/* ---------------------------- QUERY ---------------------------- */
$sql = "
SELECT
  s.id              AS submission_id,
  s.student_id,
  s.assessment_id,
  s.batch_id,
  s.submitted_at,
  a.$assTitleCol    AS assessment_title,
  st.$stuNameCol    AS student_name
FROM lms_submissions s
JOIN lms_assessments a ON a.id = s.assessment_id
JOIN $studentTable  st ON st.id = s.student_id
";
$w=[]; $params=[]; $types='';

if ($view !== 'all') { $w[] = $PENDING_SQL; }
if ($search!==''){
  $w[]="(st.$stuNameCol LIKE ? OR a.$assTitleCol LIKE ?)";
  $like="%$search%"; $params[]=$like; $params[]=$like; $types.='ss';
}
if ($w) $sql.=" WHERE ".implode(' AND ',$w);
$sql.=" ORDER BY s.submitted_at DESC, s.id DESC LIMIT ?"; $params[]=$limit; $types.='i';

$st=$mysqli->prepare($sql);
$st->bind_param($types, ...$params);
$st->execute();
$rows=$st->get_result()->fetch_all(MYSQLI_ASSOC);
$st->close();

/* --------------------------- PAGE VARS ------------------------- */
$PAGE_TITLE='Assessments';
$nowStr=date('Y-m-d H:i:s').' (Sri Lanka)';
$baseLecturer = dirname($_SERVER['PHP_SELF']);             // /elms/lecturer/assessments
$linkDashboard = rtrim($baseLecturer.'/../index.php','/'); // /elms/lecturer/index.php
$linkAssess    = $_SERVER['PHP_SELF'];                     // current
$linkLogout    = rtrim($baseLecturer.'/../logout.php','/');// /elms/lecturer/logout.php
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?= esc($PAGE_TITLE) ?> – EdenCampus</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  :root{
    --bg:#0b1524; --bg2:#0e1a2e; --text:#d7e3ff; --muted:#8fa3c9;
    --brand:#6c5ce7; --brand2:#9b88ff; --card:#ffffff; --ink:#111827;
    --line:#e5e7eb; --pill:#eef2ff;
  }
  *{box-sizing:border-box}
  html,body{height:100%}
  body{margin:0;font:14px/1.5 system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,Cantarell,"Noto Sans",Arial,"Apple Color Emoji","Segoe UI Emoji";}
  .shell{display:flex; min-height:100vh; background:#f6f8ff;}
  .sidebar{width:260px; background:linear-gradient(180deg,var(--bg),var(--bg2)); color:var(--text); padding:18px 16px; position:sticky; top:0; height:100vh;}
  .brand{font-weight:800; font-size:22px; letter-spacing:.3px; margin-bottom:10px}
  .rolebox{font-size:12px; color:var(--muted); text-transform:uppercase; letter-spacing:.7px; margin-bottom:14px}
  .nav a{display:flex; align-items:center; gap:10px; padding:10px 12px; color:var(--text); text-decoration:none; border-radius:12px; margin:3px 0}
  .nav a:hover{background:rgba(255,255,255,.06)}
  .nav a.active{background:linear-gradient(90deg,var(--brand),var(--brand2)); color:#fff}
  .nav .emoji{width:22px; text-align:center}
  .main{flex:1; padding:24px 28px}
  .toprow{display:flex; gap:10px; align-items:end; justify-content:space-between; margin-bottom:14px}
  .title{margin:0; font-size:22px; color:#111; font-weight:700}
  .time{color:#6b7280; font-size:12px}
  .card{background:var(--card); border:1px solid var(--line); border-radius:16px; box-shadow:0 6px 14px rgba(17,24,39,.04)}
  .card .body{padding:14px}
  .row{display:flex; flex-wrap:wrap; gap:10px}
  .col{flex:1 1 320px}
  .input,.select,.btn{height:38px; padding:8px 10px; border-radius:10px; border:1px solid var(--line); font-size:14px; width:100%}
  .btn{background:var(--brand); color:#fff; border:none; cursor:pointer}
  .btn:hover{filter:brightness(1.05)}
  .tablewrap{overflow:auto}
  table{width:100%; border-collapse:collapse; color:var(--ink)}
  thead th{background:#f2f4ff; text-align:left; font-weight:700; font-size:13px; padding:12px}
  tbody td{border-top:1px solid var(--line); padding:12px}
  .td-right{text-align:right}
  .pill{display:inline-block; background:var(--pill); color:#3730a3; font-weight:600; font-size:12px; padding:4px 10px; border-radius:999px}
  .btn-sm{display:inline-block; padding:7px 12px; border-radius:10px; font-size:13px; background:var(--brand); color:#fff; text-decoration:none}
  .tabs{display:flex; gap:8px; margin-top:8px}
  .tab{display:inline-block; padding:6px 10px; border:1px solid var(--line); border-radius:10px; text-decoration:none; color:#111; background:#fff}
  .tab.active{background:#eef2ff; color:#3730a3; font-weight:700}
  footer{margin-top:18px; color:#6b7280; font-size:12px}
  @media (max-width:900px){ .sidebar{display:none}; .main{padding:16px} }
</style>
</head>
<body>
<div class="shell">
  <!-- LEFT SIDEBAR -->
  <aside class="sidebar">
    <div class="brand">Lecturer</div>
    <div class="rolebox"><?= strtoupper(esc($role)) ?></div>
    <nav class="nav">
      <a href="<?= esc($linkDashboard) ?>"><span class="emoji">🏠</span><span>Dashboard</span></a>
      <a class="active" href="<?= esc($linkAssess) ?>"><span class="emoji">📝</span><span>Assessments</span></a>
      <a href="<?= esc($linkLogout) ?>"><span class="emoji">🔒</span><span>Logout</span></a>
    </nav>
  </aside>

  <!-- MAIN -->
  <main class="main">
    <div class="toprow">
      <h2 class="title">Assessments</h2>
      <div class="time"><?= esc($nowStr) ?></div>
    </div>

    <section class="card" style="margin-bottom:14px">
      <div class="body">
        <form class="row" method="get">
          <div class="col"><input class="input" name="q" placeholder="Search student / assessment" value="<?= esc($search) ?>"></div>
          <div style="width:160px"><select class="select" name="limit">
            <?php foreach([10,20,50,100] as $opt): ?>
              <option value="<?= $opt ?>" <?= $opt===$limit?'selected':'' ?>>Show <?= $opt ?></option>
            <?php endforeach; ?>
          </select></div>
          <div style="width:140px">
            <select class="select" name="view">
              <option value="pending" <?= $view!=='all'?'selected':'' ?>>Pending only</option>
              <option value="all" <?= $view==='all'?'selected':'' ?>>All</option>
            </select>
          </div>
          <div style="width:120px"><button class="btn">Apply</button></div>
        </form>
        <div class="tabs">
          <a class="tab <?= $view!=='all'?'active':'' ?>" href="?<?= http_build_query(['q'=>$search,'limit'=>$limit,'view'=>'pending']) ?>">Pending</a>
          <a class="tab <?= $view==='all'?'active':'' ?>" href="?<?= http_build_query(['q'=>$search,'limit'=>$limit,'view'=>'all']) ?>">All</a>
        </div>
      </div>
    </section>

    <section class="card">
      <div class="tablewrap">
        <table>
          <thead>
            <tr>
              <th>Student</th>
              <th>Assessment</th>
              <th>Batch</th>
              <th>Submitted</th>
              <th class="td-right">Action</th>
            </tr>
          </thead>
          <tbody>
          <?php if(!$rows): ?>
            <tr><td colspan="5" style="text-align:center; color:#6b7280; padding:28px">No items.</td></tr>
          <?php else: foreach($rows as $r): ?>
            <tr>
              <td><?= esc($r['student_name'] ?? ('#'.$r['student_id'])) ?></td>
              <td><?= esc($r['assessment_title'] ?? ('#'.$r['assessment_id'])) ?></td>
              <td><span class="pill"><?= (int)$r['batch_id'] ?></span></td>
              <td style="color:#6b7280; font-size:12px"><?= esc($r['submitted_at'] ?? '') ?></td>
              <td class="td-right"><a class="btn-sm" href="grade.php?id=<?= (int)$r['submission_id'] ?>">Grade</a></td>
            </tr>
          <?php endforeach; endif; ?>
          </tbody>
        </table>
      </div>
    </section>

    <footer>© <?= date('Y') ?> EdenCampus</footer>
  </main>
</div>
</body>
</html>
