<?php
session_start();
require_once __DIR__ . '/../includes/db.php';

ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

/* -------- single mysqli handle -------- */
$db = isset($mysqli) ? $mysqli : (isset($conn) ? $conn : null);
if (!$db) { die("DB connection missing."); }
$db->set_charset('utf8mb4');

/* -------- must have an active exam session -------- */
if (!isset($_SESSION['student_id'], $_SESSION['exam_id'], $_SESSION['q_list'])) {
  header('Location: index.php'); exit;
}

/* -------- safe defaults -------- */
$student_id   = (int)($_SESSION['student_id'] ?? 0);
$exam_id      = (int)($_SESSION['exam_id'] ?? 0);
$qids         = $_SESSION['q_list'] ?? [];
$answers      = $_SESSION['answers'] ?? [];
$total        = count($qids);
$score        = 0;

$examCourse    = '';
$examUnit      = '';
$moduleName    = '';
$isFinal       = false;
$isEvaluation  = false;
$passed        = false;
$gradeLetter   = '';
$displayStatus = '';
$studentReg    = '';
$studentName   = '';
$referenceNo   = '';

if ($total <= 0) {
  echo "No questions in session. Please contact administrator.";
  exit;
}

/* -------- helpers -------- */
function hasColumn(mysqli $db, string $table, string $column): bool {
  $sql = "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
          WHERE TABLE_SCHEMA = DATABASE()
            AND TABLE_NAME=? AND COLUMN_NAME=? LIMIT 1";
  $st = $db->prepare($sql);
  if (!$st) return false;
  $st->bind_param("ss", $table, $column);
  $st->execute();
  $r = $st->get_result();
  $ok = ($r && $r->num_rows > 0);
  $st->close();
  return $ok;
}

function stmt_bind(mysqli_stmt $stmt, string $types, array &$vals): void {
  $refs = [];
  foreach ($vals as $k => &$v) { $refs[$k] = &$v; }
  $stmt->bind_param($types, ...$refs);
}

function tableExists(mysqli $db, string $table): bool {
  $st = $db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.TABLES
                      WHERE TABLE_SCHEMA = DATABASE()
                        AND TABLE_NAME=? LIMIT 1");
  $st->bind_param("s", $table);
  $st->execute();
  $r = $st->get_result();
  $ok = ($r && $r->num_rows > 0);
  $st->close();
  return $ok;
}

function mapNumToLetter($v): string {
  if (is_numeric($v)) {
    $n = (int)$v;
    return $n===1 ? 'A' : ($n===2 ? 'B' : ($n===3 ? 'C' : ($n===4 ? 'D' : '')));
  }
  $v = strtoupper(trim((string)$v));
  return in_array($v, ['A','B','C','D'], true) ? $v : '';
}

function parseCorrectSet(array $row): array {
  foreach (['correct_answers','correct_answer','correct_option','correct'] as $c) {
    if (array_key_exists($c, $row) && trim((string)$row[$c]) !== '') {
      $raw = strtoupper((string)$row[$c]);
      $parts = strpos($raw, ',') !== false ? explode(',', $raw) : [$raw];
      $parts = array_map('mapNumToLetter', $parts);
      $parts = array_values(array_filter($parts, fn($x)=>in_array($x, ['A','B','C','D'], true)));
      return array_values(array_unique($parts));
    }
  }
  return [];
}

/* scale to 100 */
function to100(int $score, int $total): float {
  if ($total <= 0) return 0.0;
  return round(($score / $total) * 100.0, 2);
}

/* ✅ grading table (always use this; no generic pass/fail logic) */
function grade_by_pct(float $pct): array {
  if ($pct >= 75) return ['A', 'Distinction', true];
  if ($pct >= 65) return ['B', 'Merit', true];
  if ($pct >= 55) return ['C', 'Credit', true];
  if ($pct >= 40) return ['S', 'Pass', true];
  return ['F', 'Fail', false];
}

/* -------- fetch correct answers -------- */
$selectCols = ['id'];
foreach (['correct_answers','correct_answer','correct_option','correct'] as $c) {
  if (hasColumn($db, 'questions', $c)) $selectCols[] = $c;
}

$phIds      = implode(',', array_fill(0, $total, '?'));
$typesIds   = str_repeat('i', $total);
$selectQSql = "SELECT " . implode(',', array_map(fn($c)=>"`$c`", $selectCols))
            . " FROM `questions` WHERE `id` IN ($phIds)";

$st = $db->prepare($selectQSql);
if (!$st) { die("Prepare failed (questions): ".$db->error); }

$qids = array_map('intval', (array)$qids);
$valsIds = $qids;
stmt_bind($st, $typesIds, $valsIds);

$st->execute();
$rs = $st->get_result();
$correctMap = [];
while ($row = $rs->fetch_assoc()) {
  $correctMap[(int)$row['id']] = parseCorrectSet($row);
}
$st->close();

/* -------- marking -------- */
for ($i=0; $i<$total; $i++) {
  $qid = (int)$qids[$i];
  $chosen  = array_values(array_unique(array_map(fn($x)=>strtoupper(trim((string)$x)), (array)($answers[$i] ?? [])))); sort($chosen);
  $correct = array_values(array_unique(array_map(fn($x)=>strtoupper(trim((string)$x)), $correctMap[$qid] ?? []))); sort($correct);
  if (!empty($correct) && $chosen === $correct) $score++;
}
$mark100 = to100($score, $total);

/* -------- exam info (with optional unit name) -------- */
$unitsTable    = tableExists($db, 'units');
$hasExamUnitId = hasColumn($db, 'exams', 'unit_id');

if ($unitsTable && $hasExamUnitId) {
  $ex = $db->prepare("
    SELECT e.unit_exam, e.course_name, e.title, u.name AS unit_name
    FROM exams e
    LEFT JOIN units u ON u.id = e.unit_id
    WHERE e.id = ? LIMIT 1
  ");
} else {
  $ex = $db->prepare("
    SELECT e.unit_exam, e.course_name, e.title
    FROM exams e
    WHERE e.id = ? LIMIT 1
  ");
}
$ex->bind_param('i', $exam_id);
$ex->execute();
$er = $ex->get_result();
if ($er && $er->num_rows) {
  $row = $er->fetch_assoc();
  $examUnit   = (string)($row['unit_exam'] ?? '');
  $examCourse = (string)($row['course_name'] ?? '');
  $moduleName = $row['unit_name'] ?? '';
  if ($moduleName === '') $moduleName = $row['unit_exam'] ?? '';
  if ($moduleName === '') $moduleName = $row['title'] ?? '';
}
$ex->close();

/* -------- student info (robust) -------- */
$st = $db->prepare("SELECT * FROM students WHERE id=? LIMIT 1");
$st->bind_param("i", $student_id);
$st->execute();
$rs = $st->get_result();
if ($rs && $rs->num_rows) {
  $row = $rs->fetch_assoc();

  $first = $row['first_name'] ?? ($row['firstname'] ?? '');
  $last  = $row['last_name']  ?? ($row['lastname']  ?? '');
  $full  = trim($first . ' ' . $last);

  $studentName =
    (!empty($row['name'])         ? $row['name'] :
    (!empty($row['full_name'])    ? $row['full_name'] :
    (!empty($row['student_name']) ? $row['student_name'] :
    ($full ?: ''))));

  $studentReg =
    $row['course_reg_no']
    ?? $row['reference_no']
    ?? $row['register_no']
    ?? $row['reg_no']
    ?? $row['enrollment_no']
    ?? $row['nic_number']
    ?? '';

  $referenceNo =
    $row['reference_no']
    ?? $row['course_reg_no']
    ?? $row['register_no']
    ?? $row['reg_no']
    ?? $row['nic_number']
    ?? '';
}
$st->close();

if ($studentReg === '' && !empty($_SESSION['student_nic'])) {
  $studentReg = $_SESSION['student_nic'];
}

/* -------- grading (✅ no generic pass/fail; always from table) -------- */
$isEvaluation = (bool)preg_match('/evaluation\s*test/i', (string)$examUnit);
$isFinal      = (bool)preg_match('/final\s*exam/i', (string)$examUnit);

// if you want to apply the same table to ANY exam type, this is enough:
[$gradeLetter, $displayStatus, $passed] = grade_by_pct((float)$mark100);

/* -------- save result (dynamic columns) -------- */
$now = date('Y-m-d H:i:s');

$hasDate    = hasColumn($db, 'results', 'date_taken');
$hasGrade   = hasColumn($db, 'results', 'grade');
$hasStatus  = hasColumn($db, 'results', 'status');
$hasModName = hasColumn($db, 'results', 'module_name');
$hasRefNo   = hasColumn($db, 'results', 'reference_no');
$hasPct     = hasColumn($db, 'results', 'percentage');  // optional
$hasMark100 = hasColumn($db, 'results', 'mark100');     // optional

$cols  = ['student_id','exam_id','score','total'];
$types = 'iiii';
$vals  = [ $student_id, $exam_id, $score, $total ];

if ($hasDate)    { $cols[]='date_taken';   $types.='s'; $vals[]=$now; }
if ($hasGrade)   { $cols[]='grade';        $types.='s'; $vals[]=$gradeLetter; }
if ($hasStatus)  { $cols[]='status';       $types.='s'; $vals[]=$displayStatus; }
if ($hasModName) { $cols[]='module_name';  $types.='s'; $vals[]=$moduleName; }
if ($hasRefNo)   { $cols[]='reference_no'; $types.='s'; $vals[]=$referenceNo; }
if ($hasPct)     { $cols[]='percentage';   $types.='d'; $vals[]=$mark100; }
if ($hasMark100) { $cols[]='mark100';      $types.='d'; $vals[]=$mark100; }

if (tableExists($db, 'student_exams')) {
  $attempt = 1;
  $chk = $db->prepare("SELECT MAX(attempt_no) AS last_attempt FROM student_exams WHERE student_id=? AND exam_id=?");
  if ($chk) {
    $chk->bind_param("ii", $student_id, $exam_id);
    $chk->execute();
    $r = $chk->get_result();
    if ($r && ($row = $r->fetch_assoc()) && $row['last_attempt']) {
      $attempt = (int)$row['last_attempt'] + 1;
    }
    $chk->close();

    $insExam = $db->prepare("INSERT INTO student_exams (student_id, exam_id, attempt_no) VALUES (?,?,?)");
    if ($insExam) {
      $insExam->bind_param("iii", $student_id, $exam_id, $attempt);
      $insExam->execute();
      $insExam->close();
    }
  }
}

$colList   = implode(',', array_map(fn($c)=>"`$c`", $cols));
$phResults = implode(',', array_fill(0, count($cols), '?'));
$insertSql = "INSERT INTO `results` ($colList) VALUES ($phResults)";

$ins = $db->prepare($insertSql);
if (!$ins) {
  die("Insert prepare failed: ".$db->error." | SQL: ".$insertSql);
}
$valsInsert = $vals;
stmt_bind($ins, $types, $valsInsert);

if (!$ins->execute()) {
  die("Insert execute failed: ".$ins->error);
}
$ins->close();

/* -------- clear session -------- */
unset($_SESSION['q_list'], $_SESSION['current_index'], $_SESSION['answers'], $_SESSION['exam_id']);
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>EDEN CAMPUS Exam Result</title>
  <link href="../assets/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
  <style>
    body { padding: 1rem; }
    .card { margin-top: 1rem; }
    .logo { max-height: 60px; }
    .header-title { font-weight: bold; font-size: 1.2rem; }
  </style>
</head>
<body>
<div class="container" style="max-width:640px">
  <div id="resultCard" class="card shadow-sm">
    <div class="card-header text-center">
      <img src="../assets/img/edencampus.png" alt="Eden Logo" class="logo mb-2"><br>
      <span class="header-title">EDEN CAMPUS EXAM RESULT SHEET</span>
    </div>
    <div class="card-body">
      <p><strong>Student Name:</strong> <?= htmlspecialchars($studentName ?: 'N/A') ?></p>
      <p><strong>Register No:</strong> <?= htmlspecialchars($studentReg ?: 'N/A') ?></p>
      <p><strong>Course:</strong> <?= htmlspecialchars($examCourse ?: 'N/A') ?></p>
      <p><strong>Unit:</strong> <?= htmlspecialchars($moduleName ?: $examUnit ?: 'N/A') ?></p>
      <p><strong>Marks:</strong> <?= number_format($mark100, 2) ?> / 100</p>

      <!-- ✅ Status always from grading table -->
      <p><strong>Status:</strong>
        <?php
          $statusText = $displayStatus; // Distinction/Merit/Credit/Pass/Fail
          $gradeText  = " (Grade " . htmlspecialchars($gradeLetter) . ")";
          $badgeClass = $passed ? 'bg-success' : 'bg-danger';
        ?>
        <span class="badge <?= $badgeClass ?>"><?= htmlspecialchars($statusText) ?><?= $gradeText ?></span>
      </p>

      <?php if (!$passed): ?>
        <div class="alert alert-warning">
          You did not meet the pass criteria. Please contact the administrator to redo the exam.
        </div>
        <div class="alert alert-info">
          📲 <strong>Action Required:</strong><br>
          After clicking <b>Copy as Image</b>, kindly send your result screenshot to the Eden Campus Administrator via WhatsApp.<br>
          <strong>Contact:</strong> +94 77 743 0703
        </div>
      <?php endif; ?>

      <a class="btn btn-primary" href="index.php">Back to Login</a>
      <button id="copyBtn" class="btn btn-success">Copy as Image</button>
      <a class="btn btn-outline-secondary" href="logout.php">Logout</a>
    </div>
  </div>
</div>

<script>
(function(){
  const btn = document.getElementById("copyBtn");
  const card = document.getElementById("resultCard");

  function downloadBlobPNG(blob, filename='result.png'){
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = filename;
    document.body.appendChild(a);
    a.click();
    a.remove();
    URL.revokeObjectURL(url);
  }

  btn.addEventListener("click", function () {
    html2canvas(card).then(canvas => {
      if (!canvas) return alert('Could not render image.');
      canvas.toBlob(function(blob) {
        if (!blob) return alert('Failed to export image.');
        if (navigator.clipboard && window.ClipboardItem) {
          const item = new ClipboardItem({ "image/png": blob });
          navigator.clipboard.write([item]).then(() => {
            alert("Result copied as image! You can paste it into WhatsApp.");
          }).catch(() => downloadBlobPNG(blob));
        } else {
          downloadBlobPNG(blob);
        }
      });
    });
  });
})();
</script>
</body>
</html>
