<?php
chdir('../');
session_start();
require_once('public/connection.php');

// ✅ FIX: Always verify identity from session — never trust POST for student_id
if (!isset($_SESSION['student_id'])) {
    http_response_code(401);
    echo "Unauthorized";
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $student_id = (int) $_SESSION['student_id'];           // ← from verified session
    $exam_id    = (int) ($_POST['exam_id'] ?? 0);
    $count      = (int) ($_POST['count']   ?? 0);

    if ($exam_id > 0) {
        // 1. Insert a malpractice log
        $stmt = $conn->prepare("INSERT INTO malpractice_logs (student_id, exam_id, warning_count, log_time) VALUES (?, ?, ?, NOW())");
        $stmt->bind_param("iii", $student_id, $exam_id, $count);
        $stmt->execute();

        // 2. Flag student if count reaches 3
        if ($count >= 3) {
            $stmtFlag = $conn->prepare("UPDATE students SET flagged = 1 WHERE id = ?");
            $stmtFlag->bind_param("i", $student_id);
            $stmtFlag->execute();
        }

        http_response_code(200);
        echo "Recorded";
    } else {
        http_response_code(400);
        echo "Missing exam_id";
    }
} else {
    http_response_code(405);
    echo "Method not allowed";
}
?>
