<?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_id = isset($_POST['exam_id']) ? (int)$_POST['exam_id'] : 0;
        $chapter_topic = isset($_POST['chapter_topic']) ? trim($_POST['chapter_topic']) : '';
        $question_count = isset($_POST['question_count']) ? (int)$_POST['question_count'] : 5;
        $question_type = isset($_POST['question_type']) ? $_POST['question_type'] : 'mcq';
        $difficulty_level = isset($_POST['difficulty_level']) ? $_POST['difficulty_level'] : 'medium';
        
        if ($exam_id <= 0 || empty($chapter_topic)) {
            echo json_encode(['success' => false, 'message' => 'পরীক্ষা এবং অধ্যায়/টপিক নির্বাচন করুন']);
            exit();
        }
        
        // Get exam details to get subject_id
        $stmt = $pdo->prepare("SELECT * FROM exams WHERE id = ?");
        $stmt->execute([$exam_id]);
        $exam = $stmt->fetch();
        
        if (!$exam) {
            echo json_encode(['success' => false, 'message' => 'পরীক্ষা পাওয়া যায়নি']);
            exit();
        }
        
        // Get subject_id from exam_subjects
        $stmt = $pdo->prepare("SELECT subject_id FROM exam_subjects WHERE exam_id = ? LIMIT 1");
        $stmt->execute([$exam_id]);
        $exam_subject = $stmt->fetch();
        
        if (!$exam_subject) {
            echo json_encode(['success' => false, 'message' => 'এই পরীক্ষার জন্য বিষয় পাওয়া যায়নি']);
            exit();
        }
        
        $subject_id = $exam_subject['subject_id'];
        
        // Get subject name
        $stmt = $pdo->prepare("SELECT name FROM subjects WHERE id = ?");
        $stmt->execute([$subject_id]);
        $subject = $stmt->fetch();
        $subject_name = $subject ? $subject['name'] : 'অজানা বিষয়';
        
        // Generate questions (simulated AI generation)
        $generated_questions = generateQuestions($subject_name, $chapter_topic, $question_count, $question_type, $difficulty_level);
        
        // Save questions to exam
        $saved_questions = [];
        foreach ($generated_questions as $question) {
            if ($question_type === 'mcq') {
                $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'], 
                    $question_type, 
                    $question['options']['A'], 
                    $question['options']['B'], 
                    $question['options']['C'], 
                    $question['options']['D'], 
                    $question['correct_answer'], 
                    $question['marks'],
                    $chapter_topic,
                    $difficulty_level
                ]);
            } else {
                $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'], 
                    $question_type, 
                    $question['marks'],
                    $chapter_topic,
                    $difficulty_level
                ]);
            }
            
            $saved_questions[] = [
                'id' => $pdo->lastInsertId(),
                'question' => $question['question'],
                'type' => $question_type,
                'marks' => $question['marks']
            ];
        }
        
        echo json_encode([
            'success' => true, 
            'message' => "$question_count টি প্রশ্ন সফলভাবে তৈরি ও সংরক্ষণ হয়েছে",
            'questions' => $saved_questions
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}

// Function to simulate question generation
function generateQuestions($subject, $topic, $count, $type, $difficulty) {
    $questions = [];
    
    // Sample questions for different subjects
    $sample_questions = [
        'গণিত' => [
            'mcq' => [
                'easy' => [
                    [
                        'question' => "$topic এর সাধারণ সমীকরণ কোনটি?",
                        'options' => ['A' => 'ax + b = 0', 'B' => 'ax² + bx + c = 0', 'C' => 'ax³ + bx² + cx + d = 0', 'D' => 'ax⁴ + bx³ + cx² + dx + e = 0'],
                        'correct_answer' => 'B',
                        'marks' => 1
                    ],
                    [
                        'question' => "$topic এর মূল সংখ্যা কয়টি?",
                        'options' => ['A' => '1', 'B' => '2', 'C' => '3', 'D' => '4'],
                        'correct_answer' => 'B',
                        'marks' => 1
                    ]
                ],
                'medium' => [
                    [
                        'question' => "$topic এর মূলদ্বয়ের যোগফল কত?",
                        'options' => ['A' => '-b/a', 'B' => 'b/a', 'C' => '-a/b', 'D' => 'a/b'],
                        'correct_answer' => 'A',
                        'marks' => 2
                    ],
                    [
                        'question' => "$topic এর মূলদ্বয়ের গুণফল কত?",
                        'options' => ['A' => 'c/a', 'B' => '-c/a', 'C' => 'a/c', 'D' => '-a/c'],
                        'correct_answer' => 'A',
                        'marks' => 2
                    ]
                ],
                'hard' => [
                    [
                        'question' => "$topic এর সাহায্যে গঠিত সমীকরণের মূলদ্বয় α এবং β হলে, α² + β² এর মান কত?",
                        'options' => ['A' => '(b²-2ac)/a²', 'B' => '(b²+2ac)/a²', 'C' => '(2ac-b²)/a²', 'D' => '(-b²-2ac)/a²'],
                        'correct_answer' => 'A',
                        'marks' => 3
                    ]
                ]
            ],
            'short' => [
                'easy' => [
                    [
                        'question' => "$topic এর সাধারণ সমীকরণ লিখুন।",
                        'marks' => 2
                    ]
                ],
                'medium' => [
                    [
                        'question' => "$topic এর মূলদ্বয়ের যোগফল ও গুণফল নির্ণয় করুন।",
                        'marks' => 3
                    ]
                ],
                'hard' => [
                    [
                        'question' => "$topic এর সাহায্যে গঠিত সমীকরণের মূলদ্বয় α এবং β হলে, α² + β² নির্ণয় করুন।",
                        'marks' => 5
                    ]
                ]
            ],
            'long' => [
                'easy' => [
                    [
                        'question' => "$topic এর বিস্তারিত ব্যাখ্যা দিন এবং এর ব্যবহার দেখান।",
                        'marks' => 8
                    ]
                ],
                'medium' => [
                    [
                        'question' => "$topic এর সম্পূর্ণ বিবরণ দিন, প্রয়োগ ও উদাহরণসহ।",
                        'marks' => 10
                    ]
                ],
                'hard' => [
                    [
                        'question' => "$topic এর উপর ভিত্তি করে একটি গাণিতিক সমস্যা সৃষ্টি ও সমাধান করুন।",
                        'marks' => 15
                    ]
                ]
            ]
        ],
        'বাংলা' => [
            'mcq' => [
                'easy' => [
                    [
                        'question' => "$topic এর সঠিক বানান কোনটি?",
                        'options' => ['A' => '', 'B' => '', 'C' => '', 'D' => ''],
                        'correct_answer' => 'A',
                        'marks' => 1
                    ]
                ],
                'medium' => [
                    [
                        'question' => "$topic শব্দের সমার্থক শব্দ কোনটি?",
                        'options' => ['A' => '', 'B' => '', 'C' => '', 'D' => ''],
                        'correct_answer' => 'B',
                        'marks' => 2
                    ]
                ],
                'hard' => [
                    [
                        'question' => "$topic শব্দের বিপরীতার্থক শব্দ কোনটি?",
                        'options' => ['A' => '', 'B' => '', 'C' => '', 'D' => ''],
                        'correct_answer' => 'C',
                        'marks' => 3
                    ]
                ]
            ],
            'short' => [
                'easy' => [
                    [
                        'question' => "$topic শব্দের অর্থ লিখুন।",
                        'marks' => 2
                    ]
                ],
                'medium' => [
                    [
                        'question' => "$topic শব্দের ব্যবহার দেখান।",
                        'marks' => 3
                    ]
                ],
                'hard' => [
                    [
                        'question' => "$topic শব্দের ব্যুৎপত্তি ব্যাখ্যা করুন।",
                        'marks' => 5
                    ]
                ]
            ],
            'long' => [
                'easy' => [
                    [
                        'question' => "$topic বিষয়ক একটি ছোট গল্প লিখুন।",
                        'marks' => 8
                    ]
                ],
                'medium' => [
                    [
                        'question' => "$topic বিষয়ক একটি প্রবন্ধ লিখুন।",
                        'marks' => 10
                    ]
                ],
                'hard' => [
                    [
                        'question' => "$topic বিষয়ক একটি নিবন্ধ লিখুন এবং এর সামাজিক গুরুত্ব আলোচনা করুন।",
                        'marks' => 15
                    ]
                ]
            ]
        ],
        'ইংরেজি' => [
            'mcq' => [
                'easy' => [
                    [
                        'question' => "What is the meaning of '$topic'?",
                        'options' => ['A' => '', 'B' => '', 'C' => '', 'D' => ''],
                        'correct_answer' => 'A',
                        'marks' => 1
                    ]
                ],
                'medium' => [
                    [
                        'question' => "What is the synonym of '$topic'?",
                        'options' => ['A' => '', 'B' => '', 'C' => '', 'D' => ''],
                        'correct_answer' => 'B',
                        'marks' => 2
                    ]
                ],
                'hard' => [
                    [
                        'question' => "What is the antonym of '$topic'?",
                        'options' => ['A' => '', 'B' => '', 'C' => '', 'D' => ''],
                        'correct_answer' => 'C',
                        'marks' => 3
                    ]
                ]
            ],
            'short' => [
                'easy' => [
                    [
                        'question' => "Write the meaning of '$topic'.",
                        'marks' => 2
                    ]
                ],
                'medium' => [
                    [
                        'question' => "Use '$topic' in a sentence.",
                        'marks' => 3
                    ]
                ],
                'hard' => [
                    [
                        'question' => "Explain the etymology of '$topic'.",
                        'marks' => 5
                    ]
                ]
            ],
            'long' => [
                'easy' => [
                    [
                        'question' => "Write a short story on '$topic'.",
                        'marks' => 8
                    ]
                ],
                'medium' => [
                    [
                        'question' => "Write an essay on '$topic'.",
                        'marks' => 10
                    ]
                ],
                'hard' => [
                    [
                        'question' => "Write a comprehensive article on '$topic' and discuss its social importance.",
                        'marks' => 15
                    ]
                ]
            ]
        ]
    ];
    
    // Get sample questions for the subject or use default
    $subject_questions = $sample_questions[$subject] ?? $sample_questions['গণিত'];
    $difficulty_questions = $subject_questions[$type] ?? $subject_questions['mcq'];
    $level_questions = $difficulty_questions[$difficulty] ?? $difficulty_questions['medium'];
    
    // Generate questions
    for ($i = 0; $i < min($count, count($level_questions)); $i++) {
        $questions[] = $level_questions[$i % count($level_questions)];
    }
    
    // If we need more questions, duplicate with modifications
    while (count($questions) < $count) {
        $base_question = $level_questions[count($questions) % count($level_questions)];
        $new_question = $base_question;
        
        // Modify question text slightly
        $new_question['question'] = str_replace($topic, $topic . " (" . (count($questions) + 1) . ")", $new_question['question']);
        
        $questions[] = $new_question;
    }
    
    return $questions;
}