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

// Check if user is logged in and is admin/teacher
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_role'], ['admin', 'teacher'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

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

try {
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $online_exam_id = $_POST['online_exam_id'] ?? null;
        $subject_id = $_POST['subject_id'] ?? null;
        $topic = $_POST['topic'] ?? '';
        $question_count = $_POST['question_count'] ?? 5;
        $question_type = $_POST['question_type'] ?? 'mcq';
        
        if (!$online_exam_id || !$subject_id || empty($topic)) {
            echo json_encode(['success' => false, 'message' => 'Required fields are missing']);
            exit();
        }
        
        // Get subject name
        $stmt = $pdo->prepare("SELECT name FROM subjects WHERE id = ?");
        $stmt->execute([$subject_id]);
        $subject = $stmt->fetch();
        
        if (!$subject) {
            echo json_encode(['success' => false, 'message' => 'Subject not found']);
            exit();
        }
        
        // Generate AI questions (simulated - in a real implementation, this would call an AI service)
        $generated_questions = generateAIQuestions($subject['name'], $topic, $question_count, $question_type);
        
        // Save questions to database
        $saved_questions = [];
        foreach ($generated_questions as $question) {
            if ($question_type === 'mcq') {
                $stmt = $pdo->prepare("INSERT INTO online_exam_questions (online_exam_id, subject_id, question_text, question_type, option_a, option_b, option_c, option_d, correct_answer, marks) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([
                    $online_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']
                ]);
            } else {
                $stmt = $pdo->prepare("INSERT INTO online_exam_questions (online_exam_id, subject_id, question_text, question_type, marks) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([
                    $online_exam_id, 
                    $subject_id, 
                    $question['question'], 
                    $question_type, 
                    $question['marks']
                ]);
            }
            
            $saved_questions[] = [
                'id' => $pdo->lastInsertId(),
                'question' => $question['question'],
                'type' => $question_type,
                'marks' => $question['marks']
            ];
        }
        
        echo json_encode([
            'success' => true, 
            'message' => 'Questions generated and saved successfully',
            '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 AI question generation
function generateAIQuestions($subject, $topic, $count, $type) {
    $questions = [];
    
    // Sample questions for different subjects
    $sample_questions = [
        'গণিত' => [
            'mcq' => [
                [
                    'question' => '2 + 2 = ?',
                    'options' => ['A' => '3', 'B' => '4', 'C' => '5', 'D' => '6'],
                    'correct_answer' => 'B',
                    'marks' => 1
                ],
                [
                    'question' => 'What is the value of π (pi) approximately?',
                    'options' => ['A' => '3.14', 'B' => '2.71', 'C' => '1.41', 'D' => '1.73'],
                    'correct_answer' => 'A',
                    'marks' => 1
                ],
                [
                    'question' => 'What is the area of a circle with radius r?',
                    'options' => ['A' => '2πr', 'B' => 'πr²', 'C' => 'πd', 'D' => '2r'],
                    'correct_answer' => 'B',
                    'marks' => 2
                ]
            ],
            'short' => [
                [
                    'question' => 'Define Pythagorean theorem.',
                    'marks' => 3
                ],
                [
                    'question' => 'What is the formula for calculating the area of a triangle?',
                    'marks' => 2
                ]
            ],
            'long' => [
                [
                    'question' => 'Explain the concept of calculus and its applications in real life.',
                    'marks' => 10
                ],
                [
                    'question' => 'Describe the properties of different types of triangles.',
                    'marks' => 8
                ]
            ]
        ],
        'বাংলা' => [
            'mcq' => [
                [
                    'question' => 'Who wrote the national anthem of Bangladesh?',
                    'options' => ['A' => 'Kazi Nazrul Islam', 'B' => 'Rabindranath Tagore', 'C' => 'Jasim Uddin', 'D' => 'Al Mahmud'],
                    'correct_answer' => 'B',
                    'marks' => 1
                ],
                [
                    'question' => '"সোনার বাংলা" কবিতাটি কে রচনা করেছেন?',
                    'options' => ['A' => 'রবীন্দ্রনাথ ঠাকুর', 'B' => 'কাজী নজরুল ইসলাম', 'C' => 'জসীম উদদীন', 'D' => 'ফররুখ আহমেদ'],
                    'correct_answer' => 'A',
                    'marks' => 1
                ]
            ],
            'short' => [
                [
                    'question' => 'Define the term "সমাস" with an example.',
                    'marks' => 3
                ]
            ],
            'long' => [
                [
                    'question' => 'Discuss the literary contributions of Kazi Nazrul Islam.',
                    'marks' => 10
                ]
            ]
        ],
        'ইংরেজি' => [
            'mcq' => [
                [
                    'question' => 'What is the synonym of "happy"?',
                    'options' => ['A' => 'Sad', 'B' => 'Joyful', 'C' => 'Angry', 'D' => 'Tired'],
                    'correct_answer' => 'B',
                    'marks' => 1
                ],
                [
                    'question' => 'Which is the correct sentence?',
                    'options' => ['A' => 'She don\'t like apples', 'B' => 'She doesn\'t likes apples', 'C' => 'She doesn\'t like apples', 'D' => 'She not like apples'],
                    'correct_answer' => 'C',
                    'marks' => 1
                ]
            ],
            'short' => [
                [
                    'question' => 'Write the past tense of "go".',
                    'marks' => 1
                ]
            ],
            'long' => [
                [
                    'question' => 'Write an essay on "The Importance of English in Modern World".',
                    'marks' => 15
                ]
            ]
        ]
    ];
    
    // Get sample questions for the subject or use default
    $subject_questions = $sample_questions[$subject] ?? $sample_questions['গণিত'];
    $type_questions = $subject_questions[$type] ?? $subject_questions['mcq'];
    
    // Generate questions
    for ($i = 0; $i < min($count, count($type_questions)); $i++) {
        $questions[] = $type_questions[$i];
    }
    
    // If we need more questions, duplicate and modify
    while (count($questions) < $count) {
        $base_question = $type_questions[array_rand($type_questions)];
        $new_question = $base_question;
        
        // Modify question slightly for variation
        if ($type === 'mcq') {
            // Change numbers in math questions
            $new_question['question'] = str_replace(
                ['2 + 2', 'π', 'πr²'], 
                ['3 + 3', '3.14', '2πr'], 
                $new_question['question']
            );
        }
        
        $questions[] = $new_question;
    }
    
    return $questions;
}
?>