<?php
/* /elms/lecturer/grade_queue.php */
declare(strict_types=1);
if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_role(['lecturer','super_admin','branch_admin']); // adjust roles

$lecturer_id = (int)($_SESSION['lecturer_id'] ?? $_SESSION['user']['id'] ?? 0);

function t_exists(string $t): bool {
  global $mysqli;
  $st=$mysqli->prepare("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=?");
  $st->bind_param('s',$t); $st->execute();
  $ok=(bool)$st->get_result()->fetch_row(); $st->close(); return $ok;
}
function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); }

$sql = "
SELECT
  s.id, s.assessment_id, s.student_id, s.batch_id, s.submitted_at,
  a.title AS assess_title,
  st.full_name AS student_name,
  COALESCE(b.batch_name, b.name, CONCAT('Batch ', b.id)) AS batch_label
FROM lms_submissions s
JOIN lms_assessments a ON a.id = s.assessment_id
JOIN studentss st      ON st.id = s.student_id
JOIN batches b         ON b.id = s.batch_id
WHERE s.workflow_status IN ('submitted','resubmitted')
  AND (
        a.lecturer_id = ?
     ".(t_exists('lecturer_batches') ? " OR EXISTS (SELECT 1 FROM lecturer_batches lb WHERE lb.lecturer_id=? AND lb.batch_id=s.batch_id) " : "")."
     ".(t_exists('lecturer_courses') ? " OR EXISTS (SELECT 1 FROM lecturer_courses lc WHERE lc.lecturer_id=? AND lc.course_id=a.course_id) " : "")."
      )
ORDER BY s.submitted_at ASC
LIMIT 100";

$params = [$lecturer_id];
$types  = "i";
if (t_exists('lecturer_batches')) { $params[]=$lecturer_id; $types.="i"; }
if (t_exists('lecturer_courses')) { $params[]=$lecturer_id; $types.="i"; }

$st = $mysqli->prepare($sql);
$st->bind_param($types, ...$params);
$st->execute();
$res = $st->get_result();
$rows = $res->fetch_all(MYSQLI_ASSOC);
$st->close();
?>
<!doctype html><meta charset="utf-8"><title>To Grade</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<div class="container py-4">
  <h3 class="mb-3">To Grade</h3>
  <?php if (!$rows): ?>
    <div class="alert alert-info">Nothing to grade right now.</div>
  <?php else: ?>
    <div class="table-responsive">
      <table class="table table-sm align-middle">
        <thead class="table-light">
          <tr><th>Student</th><th>Assessment</th><th>Batch</th><th>Submitted</th><th></th></tr>
        </thead>
        <tbody>
          <?php foreach ($rows as $r): ?>
            <tr>
              <td><?= esc($r['student_name']) ?></td>
              <td><?= esc($r['assess_title']) ?></td>
              <td><?= esc($r['batch_label']) ?></td>
              <td class="small text-muted"><?= esc($r['submitted_at']) ?></td>
              <td class="text-end">
                <a class="btn btn-sm btn-primary"
                   href="grade.php?submission_id=<?= (int)$r['id'] ?>">Open</a>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  <?php endif; ?>
</div>
