<?php
// includes/class-qcm-session.php

class QCM_Session {
    
    /**
     * Génère 20 questions aléatoires
     */
    public static function generate_quiz($user_id) {
        $all_questions = qcm_get_questions_bank();
        
        // Sélectionner 20 questions aléatoires
        shuffle($all_questions);
        $selected = array_slice($all_questions, 0, 20);
        
        // Mélanger les réponses pour chaque question
        $quiz = [];
        foreach ($selected as $q) {
            $quiz[] = self::shuffle_question($q);
        }
        
        // Stocker dans transient (expire 2h)
        $session_key = 'qcm_session_' . $user_id;
        set_transient($session_key, [
            'questions' => $quiz,
            'started_at' => time(),
            'user_id' => $user_id
        ], 2 * HOUR_IN_SECONDS);
        
        // Retourner questions SANS les bonnes réponses
        return array_map(function($q) {
            return [
                'id' => $q['id'],
                'question' => $q['question'],
                'answers' => $q['shuffled_answers']
            ];
        }, $quiz);
    }
    
    /**
     * Mélange les réponses et track la bonne
     */
    private static function shuffle_question($question) {
        $answers = $question['answers'];
        $correct_answer = $answers[$question['correct']];
        
        // Mélanger
        shuffle($answers);
        
        // Trouver le nouvel index de la bonne réponse
        $new_correct_index = array_search($correct_answer, $answers);
        
        return [
            'id' => $question['id'],
            'question' => $question['question'],
            'shuffled_answers' => $answers,
            'correct_index' => $new_correct_index,
            'original_correct' => $question['correct']
        ];
    }
    
    /**
     * Récupère la session
     */
    public static function get_session($user_id) {
        return get_transient('qcm_session_' . $user_id);
    }
    
    /**
     * Supprime la session
     */
    public static function clear_session($user_id) {
        delete_transient('qcm_session_' . $user_id);
    }
}