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

header('Content-Type: application/json');

$db = isset($mysqli) ? $mysqli : (isset($conn) ? $conn : null);
if (!$db) { echo json_encode(['ok'=>false,'error'=>'DB connection missing']); exit; }

function tableExists(mysqli $db, string $t): bool {
  $st=$db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? LIMIT 1");
  $st->bind_param("s",$t); $st->execute(); $r=$st->get_result(); return ($r && $r->num_rows>0);
}
function colExists(mysqli $db, string $t, string $c): bool {
  $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",$t,$c); $st->execute(); $r=$st->get_result(); return ($r && $r->num_rows>0);
}

$student_id  = (int)($_POST['student_id'] ?? 0);
$course_id   = (int)($_POST['course_id'] ?? 0);
$referenceNo = trim($_POST['reference_no'] ?? '');
$modsJson    = $_POST['modules'] ?? '';

if (!$student_id || !$course_id || $modsJson==='') {
  echo json_encode(['ok'=>false,'error'=>'Missing parameters']); exit;
}

$mods = json_decode($modsJson, true);
if (!is_array($mods)) { echo json_encode(['ok'=>false,'error'=>'Bad modules payload']); exit; }

// course name (for exam mapping/creation)
$courseName = '';
$st = $db->prepare("SELECT course_name FROM courses WHERE id=? LIMIT 1");
$st->bind_param("i",$course_id); $st->execute();
if ($r=$st->get_result()->fetch_assoc()) $courseName = (string)$r['course_name'];
$st->close();

$hasStatus   = tableExists($db,'results') && colExists($db,'results','status');
$hasModName  = tableExists($db,'results') && colExists($db,'results','module_name');
$hasRefNo    = tableExists($db,'results') && colExists($db,'results','reference_no');

foreach ($mods as $moduleName => $score) {
  $score = (int)$score;
  if ($score < 0) $score = 0; if ($score > 100) $score = 100;
  $grade = ($score >= 40) ? 'P' : 'F';
  $status= ($score >= 40) ? 'Pass' : 'Fail';

  // find or create an exam row for this module
  $exam_id = 0;
  $st = $db->prepare("SELECT id FROM exams WHERE (unit_exam = ? OR title = ?) AND (course_id = ? OR course_name = ?) LIMIT 1");
  $st->bind_param("ssis", $moduleName, $moduleName, $course_id, $courseName);
  $st->execute();
  $er = $st->get_result();
  if ($er && $er->num_rows) {
    $exam_id = (int)$er->fetch_column();
  } else {
    // create a minimal exam row (so results.exam_id is valid)
    $ins = $db->prepare("INSERT INTO exams (course_id, unit_id, title, course_name, unit_exam, exam_type, pass_mark) VALUES (?,?,?,?,?,'evaluation',40)");
    $null = null;
    $ins->bind_param("iisss", $course_id, $null, $moduleName, $courseName, $moduleName);
    if ($ins->execute()) { $exam_id = $ins->insert_id; }
    $ins->close();
  }
  $st->close();

  if ($exam_id <= 0) { continue; }

  // upsert result
  $sel = $db->prepare("SELECT id FROM results WHERE student_id=? AND exam_id=? LIMIT 1");
  $sel->bind_param("ii",$student_id,$exam_id);
  $sel->execute();
  $rid = 0; $rs = $sel->get_result(); if ($rs && $rs->num_rows) $rid = (int)$rs->fetch_column();
  $sel->close();

  $now = date('Y-m-d H:i:s');

  if ($rid) {
    // UPDATE
    $sql = "UPDATE results SET score=?, total=100, date_taken=?, grade=?";
    $types = "iss"; $args = [$score, $now, $grade];
    if ($hasStatus)  { $sql .= ", status=?";      $types.="s"; $args[]=$status; }
    if ($hasModName) { $sql .= ", module_name=?"; $types.="s"; $args[]=$moduleName; }
    if ($hasRefNo)   { $sql .= ", reference_no=?";$types.="s"; $args[]=$referenceNo; }
    $sql .= " WHERE id=?";
    $types .= "i"; $args[] = $rid;

    $up = $db->prepare($sql);
    $up->bind_param($types, ...$args);
    $up->execute(); $up->close();
  } else {
    // INSERT
    $cols  = "student_id, exam_id, score, total, date_taken, grade";
    $ph    = "?,?,?,?,?,?";
    $types = "iiiiss";
    $args  = [$student_id, $exam_id, $score, 100, $now, $grade];
    if ($hasStatus)  { $cols.=",status";      $ph.=",?"; $types.="s"; $args[]=$status; }
    if ($hasModName) { $cols.=",module_name"; $ph.=",?"; $types.="s"; $args[]=$moduleName; }
    if ($hasRefNo)   { $cols.=",reference_no";$ph.=",?"; $types.="s"; $args[]=$referenceNo; }

    $ins = $db->prepare("INSERT INTO results ($cols) VALUES ($ph)");
    $ins->bind_param($types, ...$args);
    $ins->execute(); $ins->close();
  }
}

echo json_encode(['ok'=>true]);
