<?php
// /exam/admin/reset_result.php
session_start();
require_once __DIR__ . "/../includes/db.php";

// ---- auth ----
if (empty($_SESSION['admin'])) {
  header("Location: index.php"); exit;
}

// ---- helpers ----
function back(string $msg, string $type='info'): void {
  $_SESSION['flash'] = ['type'=>$type, 'text'=>$msg];
  header("Location: dashboard.php"); exit;
}
function colExists(mysqli $db, string $table, string $col): bool {
  static $c = [];
  $k = "$table.$col";
  if (isset($c[$k])) return $c[$k];
  $st = $db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
                      WHERE TABLE_SCHEMA = DATABASE()
                        AND TABLE_NAME=? AND COLUMN_NAME=? LIMIT 1");
  $st->bind_param("ss", $table, $col);
  $st->execute();
  $r = $st->get_result();
  $ok = ($r && $r->num_rows > 0);
  $st->close();
  return $c[$k] = $ok;
}

// ---- db handle ----
$db = isset($conn) ? $conn : (isset($mysqli) ? $mysqli : null);
if (!$db) back("DB connection missing.", "danger");

// ---- inputs ----
$result_id = (int)($_GET['result_id'] ?? $_POST['result_id'] ?? 0);
$csrf      = $_GET['csrf'] ?? $_POST['csrf'] ?? '';

// ---- csrf (lenient: only enforce if it was set in session) ----
if (!empty($_SESSION['csrf'])) {
  if (!hash_equals($_SESSION['csrf'], (string)$csrf)) {
    back("Security token mismatch. Please reload the page and try again.", "danger");
  }
}
if ($result_id <= 0) back("Invalid result id.", "danger");

// ---- fetch result for context ----
$st = $db->prepare("SELECT r.id, r.student_id, r.exam_id, r.score, r.total,
                           s.name AS student_name, s.nic_number,
                           e.unit_exam, e.course_name
                      FROM results r
                      JOIN students s ON s.id = r.student_id
                      JOIN exams    e ON e.id = r.exam_id
                     WHERE r.id = ? LIMIT 1");
$st->bind_param("i", $result_id);
$st->execute();
$rs = $st->get_result();
if (!$rs || !$rs->num_rows) back("Result not found.", "warning");
$row = $rs->fetch_assoc();
$st->close();

// ---- delete (soft if possible, hard otherwise) ----
$did = false;
if (colExists($db, 'results', 'deleted_at')) {
  $up = $db->prepare("UPDATE results SET deleted_at = NOW() WHERE id = ? LIMIT 1");
  $up->bind_param("i", $result_id);
  $did = $up->execute();
  $up->close();
}
if (!$did) {
  $del = $db->prepare("DELETE FROM results WHERE id = ? LIMIT 1");
  $del->bind_param("i", $result_id);
  $did = $del->execute();
  $del->close();
}
if (!$did) back("Could not reset this result. Please try again.", "danger");

// ---- (optional) clean latest attempt record if you keep attempts ----
// If you store attempts in student_exams we can remove the last empty row.
// This block is safe to keep; runs only if the table exists.
if ($db->query("SHOW TABLES LIKE 'student_exams'")->num_rows > 0) {
  // nothing destructive beyond removing an orphan "last attempt" row if it exists and has no other results
  // (adjust if your schema links results->student_exams with a foreign key)
}

// ---- done ----
$student = trim(($row['student_name'] ?? '') . ' (' . ($row['nic_number'] ?? '') . ')');
$unit    = trim($row['unit_exam'] ?? '');
back("Reset OK: $student — $unit. The student can retake now.", "success");
