<?php
/* ============================================================================
   Reports — single page with independent pagination + date range filter
   Keeps your admin layout & left sidebar. (Now with 3 quick-link buttons)
   ========================================================================== */

if (session_status() === PHP_SESSION_NONE) { session_start(); }

define('APP_ROOT', dirname(__DIR__, 2)); // .../elms
require_once APP_ROOT . '/includes/auth.php';
require_role(['super_admin','admin','branch_admin','course_coordinator','coordinator','lecturer']);
require_once APP_ROOT . '/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 'DB connection not initialized'; exit;
}
@$mysqli->set_charset('utf8mb4');

/* ---------------- helpers ---------------- */
function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8'); }
function gi($k){ return (isset($_GET[$k]) && $_GET[$k] !== '' ? (int)$_GET[$k] : null); }
function gd($k){ // date (YYYY-MM-DD) or null
  $v = trim((string)($_GET[$k] ?? ''));
  if ($v==='' || !preg_match('/^\d{4}-\d{2}-\d{2}$/',$v)) return null;
  return $v;
}
function table_exists(mysqli $db, string $t): bool {
  $t=$db->real_escape_string($t);
  if ($rs=$db->query("SHOW TABLES LIKE '{$t}'")) { $ok=$rs->num_rows>0; $rs->free(); return $ok; }
  return false;
}
function col_exists(mysqli $db, string $t, string $c): bool {
  $t=$db->real_escape_string($t); $c=$db->real_escape_string($c);
  if ($rs=$db->query("SHOW COLUMNS FROM `{$t}` LIKE '{$c}'")) { $ok=$rs->num_rows>0; $rs->free(); return $ok; }
  return false;
}
function label_col(mysqli $db,string $t,array $cands): string {
  if ($rs=$db->query("SHOW COLUMNS FROM `{$t}`")) {
    $cols=[]; while($r=$rs->fetch_assoc()) $cols[]=$r['Field']; $rs->free();
    foreach($cands as $c) if (in_array($c,$cols,true)) return $c;
  }
  return 'id';
}
function mk_url(array $extra): string {
  $q=$_GET; foreach($extra as $k=>$v){ if($v===null){ unset($q[$k]); } else { $q[$k]=$v; } }
  return '?'.http_build_query($q);
}

/* ---------------- inputs ---------------- */
$course_id     = gi('course_id');
$batch_id      = gi('batch_id');
$assessment_id = gi('assessment_id');
$quiz_id       = gi('quiz_id');
$student_id    = gi('student_id');

$date_from = gd('date_from'); // YYYY-MM-DD or null
$date_to   = gd('date_to');

$per_opts = [10,20,30,50,100];
$per_page_q = isset($_GET['per_page_q']) ? (int)$_GET['per_page_q'] : 10;
$per_page_a = isset($_GET['per_page_a']) ? (int)$_GET['per_page_a'] : 10;
if (!in_array($per_page_q,$per_opts,true)) $per_page_q = 10;
if (!in_array($per_page_a,$per_opts,true)) $per_page_a = 10;

$page_q  = max(1,(int)($_GET['page_q'] ?? 1));
$page_a  = max(1,(int)($_GET['page_a'] ?? 1));
$off_q   = ($page_q-1)*$per_page_q;
$off_a   = ($page_a-1)*$per_page_a;

/* ---------------- schema discovery ---------------- */
$STUD_TBL = table_exists($mysqli,'studentss') ? 'studentss' : (table_exists($mysqli,'students') ? 'students' : 'studentss');
$studName = label_col($mysqli,$STUD_TBL,['full_name','name','title']);
$studRef  = label_col($mysqli,$STUD_TBL,['reference_no','ref_no','student_ref']);

$ASSESS_TBL = 'lms_assessments';
$SUB_TBL    = 'lms_submissions';
$BATCH_TBL  = table_exists($mysqli,'batches') ? 'batches' : null;
$ENR_TBL    = table_exists($mysqli,'enrollments') ? 'enrollments'
            : (table_exists($mysqli,'lms_enrollments') ? 'lms_enrollments'
            : (table_exists($mysqli,'student_batches') ? 'student_batches' : null));

$subTimeCol = col_exists($mysqli,$SUB_TBL,'submitted_at') ? 'submitted_at'
            : (col_exists($mysqli,$SUB_TBL,'created_at') ? 'created_at' : null);
$fileCol    = col_exists($mysqli,$SUB_TBL,'file_path') ? 'file_path'
            : (col_exists($mysqli,$SUB_TBL,'file') ? 'file'
            : (col_exists($mysqli,$SUB_TBL,'file_name') ? 'file_name' : null));
$scoreExpr  = "COALESCE(s.final_score,s.provisional_score,s.score)";
$statusExpr = "COALESCE(s.workflow_status,s.status)";

/* Quiz tables */
$QUIZ_ATT=null; $QUIZ_TBL=null; $quizScoreCol=null; $quizTimeCol=null; $quizQuizIdCol='quiz_id'; $quizTitleCol='title';
foreach ( [['quiz_attempts','quizzes'], ['mcq_attempts','mcq_quizzes'], ['lms_quiz_attempts','lms_quizzes']] as $p ){
  if (table_exists($mysqli,$p[0]) && table_exists($mysqli,$p[1])) { $QUIZ_ATT=$p[0]; $QUIZ_TBL=$p[1]; break; }
}
if ($QUIZ_TBL) $quizTitleCol = col_exists($mysqli,$QUIZ_TBL,'title') ? 'title' : (col_exists($mysqli,$QUIZ_TBL,'name') ? 'name' : 'id');
if ($QUIZ_ATT){
  foreach (['score','marks_obtained','result','percentage'] as $c) if (col_exists($mysqli,$QUIZ_ATT,$c)) { $quizScoreCol=$c; break; }
  foreach (['attempted_at','submitted_at','created_at'] as $c) if (col_exists($mysqli,$QUIZ_ATT,$c)) { $quizTimeCol=$c; break; }
  foreach (['quiz_id','test_id','paper_id'] as $c) if (col_exists($mysqli,$QUIZ_ATT,$c)) { $quizQuizIdCol=$c; break; }
}

/* ---------------- WHERE builders ---------------- */
function w_quiz(array $opts): string {
  $w=[];
  if ($opts['quiz_id']    !== null) $w[] = "a.`".$opts['quizIdCol']."`=".(int)$opts['quiz_id'];
  if ($opts['student_id'] !== null) $w[] = "a.student_id=".(int)$opts['student_id'];
  if ($opts['batch_id']   !== null && $opts['enr']) $w[] = "EXISTS(SELECT 1 FROM `".$opts['enr']."` e WHERE e.student_id=a.student_id AND e.batch_id=".(int)$opts['batch_id'].")";
  if ($opts['course_id']  !== null && $opts['enr'] && $opts['enr_has_course']) $w[] = "EXISTS(SELECT 1 FROM `".$opts['enr']."` e2 WHERE e2.student_id=a.student_id AND e2.course_id=".(int)$opts['course_id'].")";
  if ($opts['date_from'] !== null) $w[] = "a.`".$opts['timeCol']."` >= '".$opts['date_from']."'";
  if ($opts['date_to']   !== null) $w[] = "a.`".$opts['timeCol']."` <= '".$opts['date_to']."'";
  return $w ? ('WHERE '.implode(' AND ',$w)) : '';
}
function w_assess(array $opts): string {
  $w=[];
  if ($opts['assessment_id'] !== null) $w[] = "s.assessment_id=".(int)$opts['assessment_id'];
  if ($opts['batch_id']      !== null) $w[] = "s.batch_id=".(int)$opts['batch_id'];
  if ($opts['student_id']    !== null) $w[] = "s.student_id=".(int)$opts['student_id'];
  if ($opts['course_id']     !== null && $opts['ass_has_course']) $w[] = "a.course_id=".(int)$opts['course_id'];
  if ($opts['timeCol'] !== null) {
    if ($opts['date_from'] !== null) $w[] = $opts['timeCol']." >= '".$opts['date_from']."'";
    if ($opts['date_to']   !== null) $w[] = $opts['timeCol']." <= '".$opts['date_to']."'";
  }
  return $w ? ('WHERE '.implode(' AND ',$w)) : '';
}

/* ---------------- build safe date SQLs ---------------- */
$fromSQL = $date_from ? $date_from.' 00:00:00' : null;
$toSQL   = $date_to   ? $date_to.' 23:59:59'   : null;

/* ---------------- CSV export ---------------- */
if (isset($_GET['export']) && $_GET['export']==='csv') {
  $kind = isset($_GET['kind']) ? $_GET['kind'] : 'assess';
  header('Content-Type: text/csv; charset=utf-8');
  header('Content-Disposition: attachment; filename="report_'.$kind.'_'.date('Ymd_His').'.csv"');
  $out = fopen('php://output','w');

  if ($kind==='quiz' && $QUIZ_ATT && $QUIZ_TBL && $quizScoreCol && $quizTimeCol) {
    $enr_has_course = ($ENR_TBL && col_exists($mysqli,$ENR_TBL,'course_id'));
    $w = w_quiz([
      'quiz_id'=>$quiz_id,'student_id'=>$student_id,'batch_id'=>$batch_id,'course_id'=>$course_id,
      'enr'=>$ENR_TBL,'enr_has_course'=>$enr_has_course,'quizIdCol'=>$quizQuizIdCol,
      'timeCol'=>$quizTimeCol,'date_from'=>$fromSQL,'date_to'=>$toSQL
    ]);
    $sql = "SELECT q.`$quizTitleCol` AS quiz_title, COALESCE(st.`$studName`,'(unknown)') AS student_name,
                   COALESCE(st.`$studRef`,'—') AS ref_no, a.`$quizTimeCol` AS attempted_at, a.`$quizScoreCol` AS score
            FROM `$QUIZ_ATT` a
            JOIN `$QUIZ_TBL` q ON q.id=a.`$quizQuizIdCol`
            LEFT JOIN `$STUD_TBL`  st ON st.id=a.student_id
            $w
            ORDER BY a.`$quizTimeCol` DESC, a.id DESC
            LIMIT $off_q,$per_page_q";
    $rows=[]; if ($rs=$mysqli->query($sql)) { while($r=$rs->fetch_assoc()) $rows[]=$r; $rs->free(); }
    fputcsv($out, ['Quiz','Student','Ref','Attempted','Score']);
    foreach($rows as $r) fputcsv($out, [$r['quiz_title'],$r['student_name'],$r['ref_no'],$r['attempted_at'],$r['score']]);
    exit;
  }

  $ass_has_course = col_exists($mysqli,$ASSESS_TBL,'course_id');
  $timeWhereCol = $subTimeCol ? "s.`$subTimeCol`" : null;
  $w = w_assess([
    'assessment_id'=>$assessment_id,'batch_id'=>$batch_id,'student_id'=>$student_id,'course_id'=>$course_id,
    'ass_has_course'=>$ass_has_course,'timeCol'=>$timeWhereCol,'date_from'=>$fromSQL,'date_to'=>$toSQL
  ]);
  $batchJoin = $BATCH_TBL ? "LEFT JOIN `$BATCH_TBL` b ON b.id=s.batch_id" : "";
  $batchName = $BATCH_TBL ? label_col($mysqli,$BATCH_TBL,['batch_name','name','title']) : null;
  $batchSel  = $batchName ? ", b.`$batchName` AS batch_name" : ", s.batch_id AS batch_name";
  $fileSel   = $fileCol ? ", s.`$fileCol` AS file_path" : ", NULL AS file_path";
  $timeExpr  = $subTimeCol ? "s.`$subTimeCol`" : "s.id";

  $sql = "SELECT COALESCE(a.title, CONCAT('Assessment #', s.assessment_id)) AS assessment,
                 COALESCE(st.`$studName`,'(unknown)') AS student_name,
                 COALESCE(st.`$studRef`,'—') AS ref_no,
                 $timeExpr AS submitted_at, $statusExpr AS status, $scoreExpr AS score
                 $batchSel $fileSel
          FROM `$SUB_TBL` s
          LEFT JOIN `$ASSESS_TBL` a ON a.id=s.assessment_id
          LEFT JOIN `$STUD_TBL`  st ON st.id=s.student_id
          $batchJoin
          $w
          ORDER BY $timeExpr DESC, s.id DESC
          LIMIT $off_a,$per_page_a";
  $rows=[]; if ($rs=$mysqli->query($sql)) { while($r=$rs->fetch_assoc()) $rows[]=$r; $rs->free(); }
  fputcsv($out, ['Assessment','Batch','Student','Ref','Submitted','Score','Status','File']);
  foreach($rows as $r) fputcsv($out, [$r['assessment'],$r['batch_name'],$r['student_name'],$r['ref_no'],$r['submitted_at'],$r['score'],$r['status'], !empty($r['file_path'])?'yes':'']);
  exit;
}

/* ---------------- Query data for page ---------------- */
/* QUIZ */
$quizRows=[]; $quizTotal=0;
if ($QUIZ_ATT && $QUIZ_TBL && $quizScoreCol && $quizTimeCol) {
  $enr_has_course = ($ENR_TBL && col_exists($mysqli,$ENR_TBL,'course_id'));
  $w = w_quiz([
    'quiz_id'=>$quiz_id,'student_id'=>$student_id,'batch_id'=>$batch_id,'course_id'=>$course_id,
    'enr'=>$ENR_TBL,'enr_has_course'=>$enr_has_course,'quizIdCol'=>$quizQuizIdCol,
    'timeCol'=>$quizTimeCol,'date_from'=>$fromSQL,'date_to'=>$toSQL
  ]);
  $sqlC = "SELECT COUNT(*) AS c
           FROM `$QUIZ_ATT` a
           JOIN `$QUIZ_TBL` q ON q.id=a.`$quizQuizIdCol`
           $w";
  if ($rs=$mysqli->query($sqlC)) { $r=$rs->fetch_assoc(); $quizTotal=(int)$r['c']; $rs->free(); }

  $sql = "SELECT q.`$quizTitleCol` AS quiz_title,
                 COALESCE(st.`$studName`,'(unknown)') AS student_name,
                 COALESCE(st.`$studRef`,'—')          AS ref_no,
                 a.`$quizTimeCol` AS attempted_at,
                 a.`$quizScoreCol` AS score
          FROM `$QUIZ_ATT` a
          JOIN `$QUIZ_TBL` q ON q.id=a.`$quizQuizIdCol`
          LEFT JOIN `$STUD_TBL`  st ON st.id=a.student_id
          $w
          ORDER BY a.`$quizTimeCol` DESC, a.id DESC
          LIMIT $off_q,$per_page_q";
  if ($rs=$mysqli->query($sql)) { while($r=$rs->fetch_assoc()) $quizRows[]=$r; $rs->free(); }
}

/* ASSESSMENTS */
$assRows=[]; $assTotal=0;
$ass_has_course = col_exists($mysqli,$ASSESS_TBL,'course_id');
$timeWhereCol = $subTimeCol ? "s.`$subTimeCol`" : null;
$w = w_assess([
  'assessment_id'=>$assessment_id,'batch_id'=>$batch_id,'student_id'=>$student_id,'course_id'=>$course_id,
  'ass_has_course'=>$ass_has_course,'timeCol'=>$timeWhereCol,'date_from'=>$fromSQL,'date_to'=>$toSQL
]);
$sqlC = "SELECT COUNT(*) AS c
         FROM `$SUB_TBL` s
         LEFT JOIN `$ASSESS_TBL` a ON a.id=s.assessment_id
         $w";
if ($rs=$mysqli->query($sqlC)) { $r=$rs->fetch_assoc(); $assTotal=(int)$r['c']; $rs->free(); }

$batchJoin = $BATCH_TBL ? "LEFT JOIN `$BATCH_TBL` b ON b.id=s.batch_id" : "";
$batchName = $BATCH_TBL ? label_col($mysqli,$BATCH_TBL,['batch_name','name','title']) : null;
$batchSel  = $batchName ? ", b.`$batchName` AS batch_name" : ", s.batch_id AS batch_name";
$fileSel   = $fileCol ? ", s.`$fileCol` AS file_path" : ", NULL AS file_path";
$timeExpr  = $subTimeCol ? "s.`$subTimeCol`" : "s.id";

$sql = "SELECT COALESCE(a.title, CONCAT('Assessment #', s.assessment_id)) AS assessment,
               COALESCE(st.`$studName`, '(unknown)') AS student_name,
               COALESCE(st.`$studRef`, '—')         AS ref_no,
               $timeExpr AS submitted_at, $statusExpr AS status, $scoreExpr AS score
               $batchSel $fileSel
        FROM `$SUB_TBL` s
        LEFT JOIN `$ASSESS_TBL` a ON a.id=s.assessment_id
        LEFT JOIN `$STUD_TBL`  st ON st.id=s.student_id
        $batchJoin
        $w
        ORDER BY $timeExpr DESC, s.id DESC
        LIMIT $off_a,$per_page_a";
if ($rs=$mysqli->query($sql)) { while($r=$rs->fetch_assoc()) $assRows[]=$r; $rs->free(); }

/* ---------------- page ---------------- */
$PAGE_TITLE  = 'Reports';
$ACTIVE_MENU = 'reports';
require APP_ROOT . '/includes/admin_layout_top.php';
?>

<!-- ========== NEW: Quick Report Buttons (tracking / simple / full) ========== -->
<div class="card mb-3">
  <div class="card-body d-flex flex-wrap gap-2">
    <a class="btn btn-primary" href="./tracking_sheet.php">Tracking Sheet</a>
    <a class="btn btn-outline-primary" href="./simple_report.php">Simple Report</a>
    <a class="btn btn-outline-primary" href="./student_full_report.php">Full Report</a>
  </div>
</div>
<!-- ======================================================================== -->

<div class="card mb-3">
  <div class="card-body">
    <form class="row g-2" method="get">
      <div class="col-md-2"><label class="form-label">Course ID</label>
        <input class="form-control" name="course_id" value="<?php echo esc($course_id); ?>" placeholder="optional"></div>
      <div class="col-md-2"><label class="form-label">Batch ID</label>
        <input class="form-control" name="batch_id" value="<?php echo esc($batch_id); ?>" placeholder="optional"></div>
      <div class="col-md-2"><label class="form-label">Quiz ID</label>
        <input class="form-control" name="quiz_id" value="<?php echo esc($quiz_id); ?>" placeholder="optional"></div>
      <div class="col-md-2"><label class="form-label">Assessment ID</label>
        <input class="form-control" name="assessment_id" value="<?php echo esc($assessment_id); ?>" placeholder="optional"></div>
      <div class="col-md-2"><label class="form-label">Student ID</label>
        <input class="form-control" name="student_id" value="<?php echo esc($student_id); ?>" placeholder="optional"></div>
      <div class="col-md-2 d-none d-md-block"></div>
      <div class="col-md-2"><label class="form-label">From (date)</label>
        <input class="form-control" type="date" name="date_from" value="<?php echo esc($date_from); ?>"></div>
      <div class="col-md-2"><label class="form-label">To (date)</label>
        <input class="form-control" type="date" name="date_to" value="<?php echo esc($date_to); ?>"></div>
      <div class="col-md-2 d-grid align-items-end">
        <button class="btn btn-primary mt-4">Apply</button>
      </div>
      <div class="col-md-2 d-grid align-items-end">
        <a class="btn btn-outline-secondary mt-4" href="<?php echo esc(strtok($_SERVER['REQUEST_URI'],'?')); ?>">Reset</a>
      </div>
    </form>
    <div class="text-muted small mt-2">Tip: use date range + IDs to narrow lists. Newest rows show first.</div>
  </div>
</div>

<div class="card mb-3">
  <div class="card-header d-flex justify-content-between align-items-center">
    <div class="d-flex align-items-center gap-2">
      <strong>Latest Quiz Marks</strong>
      <form method="get" class="d-flex align-items-center gap-1 ms-3">
        <?php foreach(['course_id','batch_id','quiz_id','assessment_id','student_id','date_from','date_to','page_a','per_page_a'] as $keep): ?>
          <input type="hidden" name="<?php echo $keep; ?>" value="<?php echo esc($_GET[$keep] ?? ''); ?>">
        <?php endforeach; ?>
        <span class="small text-muted">Rows</span>
        <select name="per_page_q" class="form-select form-select-sm" style="width:auto" onchange="this.form.submit()">
          <?php foreach([10,20,30,50,100] as $n): ?>
            <option value="<?php echo (int)$n; ?>" <?php echo $per_page_q==$n?'selected':''; ?>><?php echo (int)$n; ?></option>
          <?php endforeach; ?>
        </select>
      </form>
    </div>
    <a class="btn btn-sm btn-outline-secondary" href="<?php echo esc(mk_url(['export'=>'csv','kind'=>'quiz'])); ?>">Export CSV</a>
  </div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-sm align-middle mb-0">
        <thead class="table-light">
          <tr><th>Quiz</th><th>Student</th><th>Ref</th><th>Attempted</th><th>Score</th></tr>
        </thead>
        <tbody>
        <?php if(!$QUIZ_ATT || !$QUIZ_TBL): ?>
          <tr><td colspan="5" class="text-center text-muted">Quiz tables not found.</td></tr>
        <?php elseif(!$quizRows): ?>
          <tr><td colspan="5" class="text-center text-muted">No attempts.</td></tr>
        <?php else: foreach($quizRows as $q): ?>
          <tr>
            <td><?php echo esc($q['quiz_title']); ?></td>
            <td><?php echo esc($q['student_name']); ?></td>
            <td><?php echo esc($q['ref_no']); ?></td>
            <td><?php echo esc($q['attempted_at']); ?></td>
            <td><?php echo $q['score']!=='' ? (float)$q['score'] : 0; ?></td>
          </tr>
        <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
    <?php $qPages=max(1,(int)ceil($quizTotal/$per_page_q)); if($qPages>1): ?>
      <div class="d-flex justify-content-between align-items-center p-2 small text-muted">
        <div>Showing <?php echo min($quizTotal, $off_q+1); ?>–<?php echo min($quizTotal, $off_q + count($quizRows)); ?> of <?php echo (int)$quizTotal; ?></div>
        <div class="btn-group">
          <a class="btn btn-sm btn-outline-secondary <?php echo $page_q<=1?'disabled':''; ?>" href="<?php echo esc(mk_url(['page_q'=>max(1,$page_q-1)])); ?>">Prev</a>
          <a class="btn btn-sm btn-outline-secondary <?php echo $page_q>=$qPages?'disabled':''; ?>" href="<?php echo esc(mk_url(['page_q'=>min($qPages,$page_q+1)])); ?>">Next</a>
        </div>
      </div>
    <?php endif; ?>
  </div>
</div>

<div class="card">
  <div class="card-header d-flex justify-content-between align-items-center">
    <div class="d-flex align-items-center gap-2">
      <strong>Latest Assessment / Project Submissions</strong>
      <form method="get" class="d-flex align-items-center gap-1 ms-3">
        <?php foreach(['course_id','batch_id','quiz_id','assessment_id','student_id','date_from','date_to','page_q','per_page_q'] as $keep): ?>
          <input type="hidden" name="<?php echo $keep; ?>" value="<?php echo esc($_GET[$keep] ?? ''); ?>">
        <?php endforeach; ?>
        <span class="small text-muted">Rows</span>
        <select name="per_page_a" class="form-select form-select-sm" style="width:auto" onchange="this.form.submit()">
          <?php foreach([10,20,30,50,100] as $n): ?>
            <option value="<?php echo (int)$n; ?>" <?php echo $per_page_a==$n?'selected':''; ?>><?php echo (int)$n; ?></option>
          <?php endforeach; ?>
        </select>
      </form>
    </div>
    <a class="btn btn-sm btn-outline-secondary" href="<?php echo esc(mk_url(['export'=>'csv','kind'=>'assess'])); ?>">Export CSV</a>
  </div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-sm align-middle mb-0">
        <thead class="table-light">
          <tr><th>Assessment</th><th>Batch</th><th>Student</th><th>Ref</th><th>Submitted</th><th>Score</th><th>Status</th><th>File</th></tr>
        </thead>
        <tbody>
        <?php if(!$assRows): ?>
          <tr><td colspan="8" class="text-center text-muted">No data.</td></tr>
        <?php else: foreach($assRows as $r): ?>
          <tr>
            <td><?php echo esc($r['assessment']); ?></td>
            <td><?php echo esc(isset($r['batch_name'])?$r['batch_name']:''); ?></td>
            <td><?php echo esc($r['student_name']); ?></td>
            <td><?php echo esc($r['ref_no']); ?></td>
            <td><?php echo esc($r['submitted_at']); ?></td>
            <td><?php echo ($r['score']!=='') ? (float)$r['score'] : '—'; ?></td>
            <td class="text-uppercase small"><?php echo esc($r['status']); ?></td>
            <td><?php echo !empty($r['file_path']) ? '<span class="badge bg-success">File</span>' : '—'; ?></td>
          </tr>
        <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
    <?php $aPages=max(1,(int)ceil($assTotal/$per_page_a)); if($aPages>1): ?>
      <div class="d-flex justify-content-between align-items-center p-2 small text-muted">
        <div>Showing <?php echo min($assTotal, $off_a+1); ?>–<?php echo min($assTotal, $off_a + count($assRows)); ?> of <?php echo (int)$assTotal; ?></div>
        <div class="btn-group">
          <a class="btn btn-sm btn-outline-secondary <?php echo $page_a<=1?'disabled':''; ?>" href="<?php echo esc(mk_url(['page_a'=>max(1,$page_a-1)])); ?>">Prev</a>
          <a class="btn btn-sm btn-outline-secondary <?php echo $page_a>=$aPages?'disabled':''; ?>" href="<?php echo esc(mk_url(['page_a'=>min($aPages,$page_a+1)])); ?>">Next</a>
        </div>
      </div>
    <?php endif; ?>
  </div>
</div>

<?php require APP_ROOT . '/includes/admin_layout_bottom.php'; ?>
