<?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);
$content_id = (int)($_POST['content_id'] ?? 0);
$done       = (int)($_POST['done'] ?? 0); // 1 or 0

if ($content_id<=0){ http_response_code(400); echo json_encode(['ok'=>0,'err'=>'bad content_id']); exit; }

/* authorise: content must be in student’s course */
$stu = $mysqli->query("SELECT id, course_id FROM studentss WHERE id=$student_id")->fetch_assoc();
if (!$stu){ http_response_code(403); echo json_encode(['ok'=>0,'err'=>'student not found']); exit; }

$sql = "SELECT c.id, m.id mid, m.course_id cid FROM lms_content c 
        JOIN lms_modules m ON m.id=c.module_id WHERE c.id=$content_id";
$row = $mysqli->query($sql)->fetch_assoc();
if (!$row || (int)$row['cid'] !== (int)$stu['course_id']){
  http_response_code(403); echo json_encode(['ok'=>0,'err'=>'no access']); exit;
}

if ($done){
  // upsert
  $st=$mysqli->prepare("INSERT INTO lms_progress(student_id,content_id,status,completed_at)
                        VALUES(?,?,1,NOW())
                        ON DUPLICATE KEY UPDATE status=VALUES(status), completed_at=VALUES(completed_at)");
  $st->bind_param('ii',$student_id,$content_id); $st->execute(); $st->close();
} else {
  $st=$mysqli->prepare("DELETE FROM lms_progress WHERE student_id=? AND content_id=?");
  $st->bind_param('ii',$student_id,$content_id); $st->execute(); $st->close();
}

/* recompute module/course percentages */
$module_id = (int)$row['mid'];
$tot = $mysqli->query("SELECT COUNT(*) FROM lms_content WHERE module_id=$module_id AND active=1")->fetch_row()[0] ?? 0;
$doneCnt = $mysqli->query("SELECT COUNT(*) FROM lms_progress p JOIN lms_content c ON c.id=p.content_id
                           WHERE p.student_id=$student_id AND c.module_id=$module_id AND c.active=1")->fetch_row()[0] ?? 0;
$modPct = $tot? round($doneCnt*100/$tot) : 0;

/* badge: starter (first completion) */
$allDoneForStu = $mysqli->query("SELECT COUNT(*) FROM lms_progress WHERE student_id=$student_id")->fetch_row()[0] ?? 0;
if ($done && (int)$allDoneForStu===1){
  $mysqli->query("INSERT IGNORE INTO lms_student_badges(student_id,badge_id)
                  SELECT $student_id, id FROM lms_badges WHERE code='starter'");
}
/* badge: module_finisher (complete all items in module) */
if ($done && $tot>0 && (int)$doneCnt===(int)$tot){
  $mysqli->query("INSERT IGNORE INTO lms_student_badges(student_id,badge_id)
                  SELECT $student_id, id FROM lms_badges WHERE code='module_finisher'");
}

echo json_encode(['ok'=>1,'module_pct'=>$modPct,'module_done'=>$doneCnt,'module_total'=>$tot]);
