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

require_once '../../config/database.php';
require_once '../../includes/access_control.php';

// Check if user is logged in and is a teacher
require_teacher();

try {
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $exam_name = trim($_POST['exam_name']);
        $class_id = (int)$_POST['class_id'];
        $subject_id = (int)$_POST['subject_id'];
        $exam_date = $_POST['exam_date'];
        $total_marks = (int)$_POST['total_marks'];
        $topics = trim($_POST['topics']);
        $questions_per_topic = (int)$_POST['questions_per_topic'];
        $difficulty_level = $_POST['difficulty_level'];
        
        // Validate input
        if (empty($exam_name) || empty($class_id) || empty($subject_id) || empty($exam_date) || empty($topics)) {
            echo json_encode(['success' => false, 'message' => 'সকল প্রয়োজনীয় তথ্য পূরণ করুন']);
            exit();
        }
        
        // Split topics
        $topic_list = array_map('trim', explode(',', $topics));
        
        // Create exam
        $pdo->beginTransaction();
        
        try {
            // Insert exam record
            $stmt = $pdo->prepare("
                INSERT INTO exams (name, class_id, exam_date, total_marks, description) 
                VALUES (?, ?, ?, ?, ?)
            ");
            $stmt->execute([$exam_name, $class_id, $exam_date, $total_marks, '1 ক্লিকে তৈরি প্রশ্নপত্র']);
            $exam_id = $pdo->lastInsertId();
            
            // Insert exam subject
            $stmt = $pdo->prepare("
                INSERT INTO exam_subjects (exam_id, subject_id, max_marks) 
                VALUES (?, ?, ?)
            ");
            $stmt->execute([$exam_id, $subject_id, $total_marks]);
            
            // Generate questions for each topic
            $total_questions = 0;
            
            foreach ($topic_list as $topic) {
                if (!empty($topic)) {
                    // Generate MCQ questions
                    $mcq_questions = generateQuestionsForTopic($topic, 'mcq', $questions_per_topic, $difficulty_level);
                    foreach ($mcq_questions as $question) {
                        $stmt = $pdo->prepare("
                            INSERT INTO exam_questions (exam_id, subject_id, question_text, question_type, option_a, option_b, option_c, option_d, correct_answer, marks, chapter_topic, difficulty_level)
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                        ");
                        $stmt->execute([
                            $exam_id, 
                            $subject_id, 
                            $question['question'], 
                            'mcq',
                            $question['options']['A'], 
                            $question['options']['B'], 
                            $question['options']['C'], 
                            $question['options']['D'], 
                            $question['correct_answer'], 
                            $question['marks'],
                            $topic,
                            $difficulty_level
                        ]);
                        $total_questions++;
                    }
                    
                    // Generate short questions
                    $short_questions = generateQuestionsForTopic($topic, 'short', ceil($questions_per_topic/2), $difficulty_level);
                    foreach ($short_questions as $question) {
                        $stmt = $pdo->prepare("
                            INSERT INTO exam_questions (exam_id, subject_id, question_text, question_type, marks, chapter_topic, difficulty_level)
                            VALUES (?, ?, ?, ?, ?, ?, ?)
                        ");
                        $stmt->execute([
                            $exam_id, 
                            $subject_id, 
                            $question['question'], 
                            'short',
                            $question['marks'],
                            $topic,
                            $difficulty_level
                        ]);
                        $total_questions++;
                    }
                }
            }
            
            $pdo->commit();
            
            echo json_encode([
                'success' => true, 
                'message' => 'প্রশ্নপত্র সফলভাবে তৈরি হয়েছে',
                'exam_id' => $exam_id,
                'question_count' => $total_questions
            ]);
            
        } catch (Exception $e) {
            $pdo->rollBack();
            throw $e;
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}

// Function to generate questions for a topic
function generateQuestionsForTopic($topic, $type, $count, $difficulty) {
    $questions = [];
    
    // Sample questions patterns
    if ($type === 'mcq') {
        for ($i = 1; $i <= $count; $i++) {
            $questions[] = [
                'question' => "$topic সম্পর্কিত প্রশ্ন #$i",
                'options' => [
                    'A' => "উত্তর বিকল্প A ($topic)",
                    'B' => "উত্তর বিকল্প B ($topic)",
                    'C' => "উত্তর বিকল্প C ($topic)",
                    'D' => "উত্তর বিকল্প D ($topic)"
                ],
                'correct_answer' => ['A', 'B', 'C', 'D'][rand(0, 3)],
                'marks' => $difficulty === 'easy' ? 1 : ($difficulty === 'medium' ? 2 : 3)
            ];
        }
    } else if ($type === 'short') {
        for ($i = 1; $i <= $count; $i++) {
            $questions[] = [
                'question' => "$topic সম্পর্কিত সংক্ষিপ্ত প্রশ্ন #$i",
                'marks' => $difficulty === 'easy' ? 2 : ($difficulty === 'medium' ? 3 : 5)
            ];
        }
    }
    
    return $questions;
}