<?php
// This script generates up to 3 shuffled sets of exam papers with shuffled questions and options.
// Usage: Include or run this script during exam creation or assignment to generate shuffled sets.

function generateShuffledExamSets(PDO $pdo, int $exam_id, int $max_sets = 3): array {
    // Fetch all questions and options for the exam
    $stmt = $pdo->prepare("SELECT q.id as question_id, q.question_text, o.id as option_id, o.option_text 
                           FROM questions q 
                           JOIN options o ON q.id = o.question_id 
                           WHERE q.exam_id = ?");
    $stmt->execute([$exam_id]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Organize questions and options
    $questions = [];
    foreach ($rows as $row) {
        $qid = $row['question_id'];
        if (!isset($questions[$qid])) {
            $questions[$qid] = [
                'question_text' => $row['question_text'],
                'options' => []
            ];
        }
        $questions[$qid]['options'][] = [
            'option_id' => $row['option_id'],
            'option_text' => $row['option_text']
        ];
    }

    $sets = [];
    for ($set_num = 1; $set_num <= $max_sets; $set_num++) {
        // Shuffle questions keys
        $question_keys = array_keys($questions);
        shuffle($question_keys);

        $shuffled_questions = [];
        foreach ($question_keys as $key) {
            $options = $questions[$key]['options'];
            shuffle($options);
            $shuffled_questions[$key] = [
                'question_text' => $questions[$key]['question_text'],
                'options' => $options
            ];
        }
        $sets[$set_num] = $shuffled_questions;
    }

    return $sets;
}

// Example usage:
// $host = 'localhost';
// $dbname = 'mcq_exam_portal';
// $user = 'root';
// $pass = '';
// try {
//     $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $pass);
//     $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// } catch (PDOException $e) {
//     die("Database connection failed: " . $e->getMessage());
// }
// $exam_id = 1; // Set your exam ID here
// $shuffled_sets = generateShuffledExamSets($pdo, $exam_id);
// print_r($shuffled_sets);
?>
