<?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;
        $question_ids = isset($_POST['question_ids']) ? json_decode($_POST['question_ids'], true) : [];
        
        if ($exam_id <= 0 || empty($question_ids)) {
            echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
            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' => 'Exam not found']);
            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' => 'Subject not found for this exam']);
            exit();
        }
        
        $subject_id = $exam_subject['subject_id'];
        
        // Import questions
        $imported_count = 0;
        foreach ($question_ids as $question_id) {
            // Get question from bank
            $stmt = $pdo->prepare("SELECT * FROM question_bank WHERE id = ?");
            $stmt->execute([$question_id]);
            $question = $stmt->fetch();
            
            if ($question) {
                // Check if question already exists in this exam
                $stmt = $pdo->prepare("SELECT id FROM exam_questions WHERE exam_id = ? AND question_text = ?");
                $stmt->execute([$exam_id, $question['question_text']]);
                $existing = $stmt->fetch();
                
                if (!$existing) {
                    // Insert question into exam
                    if ($question['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, is_starred)
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                        ");
                        $stmt->execute([
                            $exam_id,
                            $subject_id,
                            $question['question_text'],
                            $question['question_type'],
                            $question['option_a'],
                            $question['option_b'],
                            $question['option_c'],
                            $question['option_d'],
                            $question['correct_answer'],
                            $question['marks'],
                            $question['chapter_topic'],
                            $question['difficulty_level'],
                            $question['is_starred']
                        ]);
                    } else {
                        $stmt = $pdo->prepare("
                            INSERT INTO exam_questions (exam_id, subject_id, question_text, question_type, marks, chapter_topic, difficulty_level, is_starred)
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                        ");
                        $stmt->execute([
                            $exam_id,
                            $subject_id,
                            $question['question_text'],
                            $question['question_type'],
                            $question['marks'],
                            $question['chapter_topic'],
                            $question['difficulty_level'],
                            $question['is_starred']
                        ]);
                    }
                    $imported_count++;
                }
            }
        }
        
        echo json_encode([
            'success' => true, 
            'message' => "$imported_count টি প্রশ্ন সফলভাবে আনা হয়েছে"
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}