<?php
session_start();
include "db.php";
header('Content-Type: application/json');

if(!isset($_SESSION['user_id'])){
 echo json_encode(['error'=>'Auth required']); exit;
}

$user_id=(int)$_SESSION['user_id'];
$course_id=(int)$_POST['course_id'];
$module_id=(int)$_POST['module_id'];

/* QUIZ */
$q=$conn->prepare("SELECT * FROM quizzes WHERE module_id=?");
$q->bind_param("i",$module_id);
$q->execute();
$quiz=$q->get_result()->fetch_assoc();
if(!$quiz){ echo json_encode(['error'=>'Quiz missing']); exit; }

$pass_mark=$quiz['pass_mark'];

/* QUESTIONS */
$qs=$conn->prepare("SELECT id FROM quiz_questions WHERE quiz_id=?");
$qs->bind_param("i",$quiz['id']);
$qs->execute();
$r=$qs->get_result();

$total=$r->num_rows; $correct=0;

while($q=$r->fetch_assoc()){
 $qid=$q['id'];
 $opt=(int)($_POST["q$qid"]??0);
 if(!$opt) continue;
 $c=$conn->prepare(
  "SELECT is_correct FROM quiz_options WHERE id=? AND question_id=?"
 );
 $c->bind_param("ii",$opt,$qid);
 $c->execute();
 $res=$c->get_result()->fetch_assoc();
 if($res && $res['is_correct']) $correct++;
}

$score=$total?round(($correct/$total)*100):0;
$passed=$score>=$pass_mark;

/* SAVE */
$val=$passed?100:$score;
$conn->query(
 "REPLACE INTO user_module_progress
  (user_id,course_id,module_id,completed)
  VALUES ($user_id,$course_id,$module_id,$val)"
);

/* NEXT MODULE */
$m=$conn->query(
 "SELECT id FROM modules WHERE course_id=$course_id ORDER BY module_order"
)->fetch_all(MYSQLI_ASSOC);

$next=null; $isLast=true;
for($i=0;$i<count($m);$i++){
 if($m[$i]['id']==$module_id && isset($m[$i+1])){
  $next=$m[$i+1]['id']; $isLast=false;
 }
}

echo json_encode([
 'score'=>$score,
 'passed'=>$passed,
 'pass_mark'=>$pass_mark,
 'next_module'=>$next,
 'is_last'=>$isLast
]);
