<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
header('Content-Type: application/json');
require_once __DIR__ . '/../../includes/student_auth.php';
require_student();
require_once __DIR__ . '/../../includes/db.php';

$student_id = (int)($_SESSION['student_id'] ?? 0);
$quiz_id = (int)($_POST['quiz_id'] ?? 0);
$score   = (int)($_POST['score'] ?? 0);
$max     = max(1,(int)($_POST['max'] ?? 100));
if ($quiz_id<=0){ http_response_code(400); echo json_encode(['ok'=>0,'err'=>'bad quiz_id']); exit; }

$q = $mysqli->query("SELECT id, pass_score, course_id FROM lms_quizzes WHERE id=$quiz_id")->fetch_assoc();
if (!$q){ http_response_code(404); echo json_encode(['ok'=>0,'err'=>'quiz not found']); exit; }

/* ensure student belongs to this course */
$stu = $mysqli->query("SELECT course_id FROM studentss WHERE id=$student_id")->fetch_assoc();
if (!$stu || (int)$stu['course_id'] !== (int)$q['course_id']){
  http_response_code(403); echo json_encode(['ok'=>0,'err'=>'no access']); exit;
}

$passed = (!is_null($q['pass_score']) && $score >= (int)$q['pass_score']) ? 1 : 0;

$st=$mysqli->prepare("INSERT INTO lms_quiz_attempts(student_id,quiz_id,score,max_score,passed)
                      VALUES(?,?,?,?,?)");
$st->bind_param('iiiii',$student_id,$quiz_id,$score,$max,$passed);
$st->execute(); $st->close();

/* award quiz_ace if passed */
if ($passed){
  $mysqli->query("INSERT IGNORE INTO lms_student_badges(student_id,badge_id)
                  SELECT $student_id, id FROM lms_badges WHERE code='quiz_ace'");
}

echo json_encode(['ok'=>1,'passed'=>$passed]);
