<?php declare(strict_types=1);
/* ============================================================================
 * Lecturer → Assessments (robust + self-debugging)
 * File: /elms/lecturer/assessments/index.php
 * ----------------------------------------------------------------------------
 * - ?debug=1  : turn on display_errors + mysqli exceptions
 * - ?showall=1: ignore lecturer scoping (for quick sanity checks)
 * - Minimal dependencies: falls back to plain HTML if layout files are missing
 * ========================================================================== */

define('APP_ROOT', dirname(__DIR__, 1));  // .../elms

// ---------- DEBUG SWITCH ----------
$DEBUG = isset($_GET['debug']) && $_GET['debug'] === '1';
if ($DEBUG) {
  ini_set('display_errors', '1');
  ini_set('display_startup_errors', '1');
  error_reporting(E_ALL);
  mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
}

// ---------- BOOTSTRAP ----------
if (session_status() === PHP_SESSION_NONE) session_start();

$auth = APP_ROOT.'/includes/auth.php';
if (is_file($auth)) {
  require_once $auth;
  if (function_exists('require_role')) {
    // allow lecturer + admins to view this page
    require_role(['lecturer','course_coordinator','coordinator','branch_admin','admin','super_admin']);
  }
}

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

// helpers
function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8'); }
function t_exists(mysqli $db,string $t):bool {
  $t=$db->real_escape_string($t);
  $sql="SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='$t' LIMIT 1";
  if ($rs=$db->query($sql)) { $ok=(bool)$rs->fetch_row(); $rs->free(); return $ok; }
  return false;
}
function c_exists(mysqli $db,string $t,string $c):bool {
  $t=$db->real_escape_string($t); $c=$db->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 ($rs=$db->query($sql)) { $ok=(bool)$rs->fetch_row(); $rs->free(); return $ok; }
  return false;
}

// ---------- WHO AM I ----------
$me = (int)($_SESSION['user_id'] ?? 0);

// ---------- DETECT TABLES/COLUMNS (matches your DB dump) ----------
$SUB_TBL = 'lms_submissions';   // has: id, assessment_id, student_id, batch_id, submitted_at, workflow_status
$A_TBL   = 'lms_assessments';   // has: id, title, course_id
$STU_TBL = t_exists($mysqli,'studentss') ? 'studentss' : (t_exists($mysqli,'students')?'students':null);
$B_TBL   = t_exists($mysqli,'batches')   ? 'batches'   : null;

$S_ID    = 'id';
$S_AID   = 'assessment_id';
$S_SID   = 'student_id';
$S_BID   = 'batch_id';
$S_SUBAT = c_exists($mysqli,$SUB_TBL,'submitted_at') ? 'submitted_at' : (c_exists($mysqli,$SUB_TBL,'created_at') ? 'created_at' : 'id');
$S_WF    = c_exists($mysqli,$SUB_TBL,'workflow_status') ? 'workflow_status' : (c_exists($mysqli,$SUB_TBL,'status') ? 'status' : null);

$STU_NAME = $STU_TBL ? (c_exists($mysqli,$STU_TBL,'full_name') ? 'full_name' : (c_exists($mysqli,$STU_TBL,'name')?'name':'id')) : null;
$B_LABEL  = $B_TBL   ? (c_exists($mysqli,$B_TBL,'batch_name') ? 'batch_name' : (c_exists($mysqli,$B_TBL,'name')?'name':'id')) : null;

// ---------- LECTURER SCOPE ----------
$myBatches = []; $myCourses = [];
if ($me > 0 && t_exists($mysqli,'lecturer_batches')) {
  $st=$mysqli->prepare("SELECT batch_id FROM lecturer_batches WHERE lecturer_id=?");
  $st->bind_param('i',$me); $st->execute();
  if ($rs=$st->get_result()) { while($r=$rs->fetch_row()) $myBatches[(int)$r[0]]=1; $rs->free(); }
  $st->close();
}
if ($me > 0 && t_exists($mysqli,'lecturer_courses')) {
  $st=$mysqli->prepare("SELECT course_id FROM lecturer_courses WHERE lecturer_id=?");
  $st->bind_param('i',$me); $st->execute();
  if ($rs=$st->get_result()) { while($r=$rs->fetch_row()) $myCourses[(int)$r[0]]=1; $rs->free(); }
  $st->close();
}
$batchList  = $myBatches ? implode(',', array_map('intval', array_keys($myBatches))) : 'NULL';
$courseList = $myCourses ? implode(',', array_map('intval', array_keys($myCourses))) : 'NULL';

$SHOW_ALL = isset($_GET['showall']) && $_GET['showall']==='1';

// ---------- BUILD QUERY ----------
$where = [];
if (!$SHOW_ALL) {                   // normal: items this lecturer can grade
  if ($S_WF) $where[] = "s.`$S_WF` IN ('submitted','needs_correction')";
  if ($batchList!=='NULL')   $where[] = "s.`$S_BID` IN ($batchList)";
  if ($courseList!=='NULL')  $where[] = "a.`course_id` IN ($courseList)";
  if (!$where)               $where[] = "1=0"; // no scope → nothing
} else {                             // debug: show the last 100 regardless of scope
  if ($S_WF) $where[] = "1=1";
  else       $where[] = "1=1";
}

$sql = "SELECT
          s.`$S_ID`      AS submission_id,
          s.`$S_AID`     AS assessment_id,
          s.`$S_SID`     AS student_id,
          s.`$S_BID`     AS batch_id,
          s.`$S_SUBAT`   AS submitted_at,
          ".($S_WF ? "s.`$S_WF` AS wf_status," : "'' AS wf_status,")."
          a.title        AS assess_title,
          a.course_id    AS course_id
          ".($B_TBL   ? ", b.`$B_LABEL`  AS batch_label"   : ", NULL AS batch_label")."
          ".($STU_TBL ? ", st.`$STU_NAME` AS student_name" : ", NULL AS student_name")."
        FROM `$SUB_TBL` s
        JOIN `$A_TBL` a ON a.id = s.`$S_AID`
        ".($B_TBL   ? "LEFT JOIN `$B_TBL`   b  ON b.id  = s.`$S_BID`"   : "")."
        ".($STU_TBL ? "LEFT JOIN `$STU_TBL` st ON st.id = s.`$S_SID`" : "")."
        WHERE ".implode(' AND ', $where)."
        ORDER BY s.`$S_SUBAT` DESC
        LIMIT ".($SHOW_ALL? "100" : "200");

$rows=[]; $errMsg='';
try {
  if ($rs = $mysqli->query($sql)) {
    while ($r = $rs->fetch_assoc()) $rows[] = $r;
    $rs->free();
  } else {
    $errMsg = 'Query failed: '.$mysqli->error;
  }
} catch (Throwable $e) {
  $errMsg = 'SQL Exception: '.$e->getMessage();
}

// ---------- LAYOUT (fallback to plain HTML if missing) ----------
$PAGE_TITLE  = 'Lecturer Assessments';
$ACTIVE_MENU = 'lecturer_assess';
$haveLayout  = is_file(APP_ROOT.'/includes/admin_layout_top.php') && is_file(APP_ROOT.'/includes/admin_layout_bottom.php');
if ($haveLayout) require APP_ROOT.'/includes/admin_layout_top.php';
?>
<?php if(!$haveLayout): ?>
<!doctype html><html><head><meta charset="utf-8"><title><?= esc($PAGE_TITLE) ?></title>
<style>
  body{font-family:system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif;margin:20px;background:#f7f7fb}
  .card{background:#fff;border:1px solid #e5e7eb;border-radius:14px;box-shadow:0 1px 2px rgba(0,0,0,.04);padding:12px;margin:10px 0}
  .muted{color:#6b7280}
  .btn{display:inline-block;padding:.35rem .6rem;border:1px solid #d1d5db;border-radius:8px;background:#fff;text-decoration:none;color:#111827}
  .btn-primary{border-color:#2563eb;background:#2563eb;color:#fff}
  .badges .badge{display:inline-block;margin-right:6px;padding:2px 8px;background:#eef2ff;border-radius:999px;color:#3b5bdb;font-size:.8rem}
</style>
</head><body>
<h2><?= esc($PAGE_TITLE) ?></h2>
<?php endif; ?>

<div class="card">
  <div><strong>Grading queue</strong>
    <?php if($SHOW_ALL): ?><span class="badges"><span class="badge">showing ALL (debug)</span></span><?php endif; ?>
    <?php if($DEBUG): ?><span class="badges"><span class="badge">debug</span></span><?php endif; ?>
  </div>
  <?php if ($errMsg!==''): ?>
    <div class="muted" style="white-space:pre-wrap;color:#b91c1c"><strong>Error:</strong> <?= esc($errMsg) ?></div>
    <div class="muted" style="white-space:pre-wrap"><strong>SQL:</strong> <?= esc($sql) ?></div>
  <?php elseif (!$rows): ?>
    <div class="muted">Nothing to grade.</div>
    <?php if(!$SHOW_ALL): ?>
      <div class="muted">Tip: append <code>?debug=1&showall=1</code> to quickly check data ignoring lecturer scoping.</div>
    <?php endif; ?>
  <?php else: ?>
    <?php foreach ($rows as $r): ?>
      <div class="card" style="margin:8px 0">
        <div><strong><?= esc($r['assess_title'] ?? ('Assessment #'.(int)$r['assessment_id'])) ?></strong></div>
        <div class="muted">
          <?php if(!empty($r['student_name'])): ?>Student: <?= esc($r['student_name']) ?> · <?php endif; ?>
          <?php if(!empty($r['batch_label'])): ?>Batch: <?= esc($r['batch_label']) ?> · <?php endif; ?>
          Submitted: <?= esc($r['submitted_at']) ?>
          <?php if(!empty($r['wf_status'])): ?> · Status: <?= esc($r['wf_status']) ?><?php endif; ?>
        </div>
        <?php
          // If your grading UI is elsewhere, change the URL here.
          $gradeUrl = '/elms/admin/assessments/grade.php?assessment_id='.(int)$r['assessment_id'].'&batch_id='.(int)$r['batch_id'];
        ?>
        <div style="margin-top:6px">
          <a class="btn btn-primary" href="<?= esc($gradeUrl) ?>">Grade</a>
        </div>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>
</div>

<?php
if ($haveLayout) require APP_ROOT.'/includes/admin_layout_bottom.php';
else echo '</body></html>';
