<?php
// super-safe diagnostics: no strict_types, no role checks
if (session_status()===PHP_SESSION_NONE) session_start();

function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES,'UTF-8'); }
function tryreq($p){ if(is_file($p)){ require_once $p; return $p; } return null; }

$trace = [];

// Find db.php using the real folder layout: /elms/lecturer/assessments/grade_diag.php
$trace[] = __DIR__.'/../../includes/db.php';
$trace[] = __DIR__.'/../../../includes/db.php';
$trace[] = ($_SERVER['DOCUMENT_ROOT']??'').'/elms/includes/db.php';

$loaded = null;
foreach ($trace as $p) { if ($loaded = tryreq($p)) break; }

header('Content-Type: text/html; charset=utf-8');
echo "<h3>grade_diag.php</h3>";

if (!isset($mysqli) || !($mysqli instanceof mysqli)) {
  echo "<div style='color:#b91c1c'><b>DB NOT INITIALIZED</b></div>";
  echo "<pre>Looked for:\n".esc(implode("\n",$trace))."</pre>";
  exit;
}
@$mysqli->set_charset('utf8mb4');
echo "<div style='color:#065f46'><b>DB OK</b> (loaded from: ".esc($loaded).")</div>";

$id = (int)($_GET['id'] ?? 0);
$sid = (int)($_GET['sid'] ?? 0);
$aid = (int)($_GET['aid'] ?? 0);
if (!$id && (!$sid || !$aid)) {
  echo "<p>Pass <code>?id=SUBMISSION_ID</code> (e.g. <code>?id=45</code>)</p>";
  exit;
}

try {
  if ($id) {
    $sql = "SELECT s.*, st.full_name AS student_name, a.title AS assessment_title
            FROM lms_submissions s
            JOIN studentss st ON st.id = s.student_id
            JOIN lms_assessments a ON a.id = s.assessment_id
            WHERE s.id=? LIMIT 1";
    $st=$mysqli->prepare($sql); $st->bind_param('i',$id);
  } else {
    $sql = "SELECT s.*, st.full_name AS student_name, a.title AS assessment_title
            FROM lms_submissions s
            JOIN studentss st ON st.id = s.student_id
            JOIN lms_assessments a ON a.id = s.assessment_id
            WHERE s.student_id=? AND s.assessment_id=? ORDER BY s.id DESC LIMIT 1";
    $st=$mysqli->prepare($sql); $st->bind_param('ii',$sid,$aid);
  }
  $st->execute(); $row = $st->get_result()->fetch_assoc(); $st->close();

  if(!$row){ echo "<div>No row found.</div>"; exit; }

  echo "<h4>Row:</h4><pre>".esc(print_r($row,true))."</pre>";
  echo "<p style='color:#065f46'>✅ Diagnosis OK. Now replace this with grade.php (below) and use the same query string (?id=45).</p>";
} catch (Throwable $e) {
  echo "<pre style='color:#b91c1c'>ERROR: ".$e->getMessage()."</pre>";
}
