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

try {
    $pdo = getDB();

    // Sample questions data based on sample_questions.csv
    $questions = [
        [
            'title' => 'What is PHP?',
            'content' => 'PHP is a server-side scripting language used for web development.',
            'question_type' => 'mcq_single',
            'difficulty' => 'easy',
            'points' => 1,
            'category_name' => 'Programming',
            'explanation' => 'PHP stands for PHP: Hypertext Preprocessor',
            'hints' => 'Server-side, Scripting, Web development',
            'instructor_id' => 1,
            'status' => 'approved',
            'options' => [
                ['text' => 'PHP: Hypertext Preprocessor', 'correct' => true],
                ['text' => 'Personal Home Page', 'correct' => false],
                ['text' => 'Pre-Hypertext Processor', 'correct' => false],
                ['text' => 'Public HTML Page', 'correct' => false]
            ]
        ],
        [
            'title' => 'What does HTML stand for?',
            'content' => 'HTML stands for [blank].',
            'question_type' => 'fill_blanks',
            'difficulty' => 'easy',
            'points' => 1,
            'category_name' => 'Web Development',
            'explanation' => 'HyperText Markup Language',
            'hints' => 'HyperText, Markup, Language',
            'instructor_id' => 1,
            'status' => 'approved'
        ],
        [
            'title' => 'Which of the following are programming languages?',
            'content' => 'Select all that apply:',
            'question_type' => 'mcq_multiple',
            'difficulty' => 'medium',
            'points' => 2,
            'category_name' => 'Programming',
            'explanation' => 'Multiple programming languages were listed',
            'hints' => 'Look for languages used for software development',
            'instructor_id' => 1,
            'status' => 'approved',
            'options' => [
                ['text' => 'Python', 'correct' => true],
                ['text' => 'JavaScript', 'correct' => true],
                ['text' => 'HTML', 'correct' => false],
                ['text' => 'CSS', 'correct' => false],
                ['text' => 'Java', 'correct' => true]
            ]
        ],
        [
            'title' => 'What is the capital of France?',
            'content' => 'What is the capital city of France?',
            'question_type' => 'short_answer',
            'difficulty' => 'easy',
            'points' => 1,
            'category_name' => 'Geography',
            'explanation' => 'Paris is the capital and most populous city of France',
            'hints' => 'European country, Famous landmarks',
            'instructor_id' => 1,
            'status' => 'approved'
        ],
        [
            'title' => 'Match the HTTP status codes:',
            'content' => 'Match the status codes with their meanings:',
            'question_type' => 'matching',
            'difficulty' => 'medium',
            'points' => 3,
            'category_name' => 'Web Development',
            'explanation' => 'HTTP status codes indicate the result of an HTTP request',
            'hints' => '200 OK, 404 Not Found, 500 Internal Server Error',
            'instructor_id' => 1,
            'status' => 'approved',
            'matching_pairs' => [
                '200' => 'OK',
                '404' => 'Not Found',
                '500' => 'Internal Server Error'
            ]
        ],
        [
            'title' => 'Write a function to calculate factorial',
            'content' => 'Write a recursive function in JavaScript that calculates the factorial of a number.',
            'question_type' => 'code',
            'difficulty' => 'hard',
            'points' => 5,
            'category_name' => 'Programming',
            'explanation' => 'Factorial of n is n * (n-1) * ... * 1',
            'hints' => 'Recursion, Base case, Mathematical function',
            'instructor_id' => 1,
            'status' => 'approved'
        ],
        [
            'title' => 'Is PHP case-sensitive?',
            'content' => 'True or False: PHP is a case-sensitive programming language.',
            'question_type' => 'true_false',
            'difficulty' => 'medium',
            'points' => 1,
            'category_name' => 'Programming',
            'explanation' => 'PHP is not case-sensitive for variable names but is for function names',
            'hints' => 'Variable names, Function names, Case sensitivity',
            'instructor_id' => 1,
            'status' => 'approved',
            'correct_option' => 1  // 1 = False (correct answer is False)
        ]
    ];

    // Ensure question categories exist
    $categories = [
        ['name' => 'Programming', 'slug' => 'programming'],
        ['name' => 'Web Development', 'slug' => 'web-development'],
        ['name' => 'Geography', 'slug' => 'geography']
    ];

    foreach ($categories as $category) {
        $stmt = $pdo->prepare("SELECT id FROM question_categories WHERE slug = ?");
        $stmt->execute([$category['slug']]);
        $existing = $stmt->fetch();

        if (!$existing) {
            $stmt = $pdo->prepare("INSERT INTO question_categories (name, slug, is_active) VALUES (?, ?, TRUE)");
            $stmt->execute([$category['name'], $category['slug']]);
            echo "Added category: " . $category['name'] . "\n";
        }
    }

    // Insert questions
    foreach ($questions as $question) {
        // Get category ID
        $stmt = $pdo->prepare("SELECT id FROM question_categories WHERE name = ?");
        $stmt->execute([$question['category_name']]);
        $category = $stmt->fetch();
        $categoryId = $category ? $category['id'] : null;

        // Check if question already exists
        $stmt = $pdo->prepare("SELECT id FROM questions WHERE title = ? AND instructor_id = ?");
        $stmt->execute([$question['title'], $question['instructor_id']]);
        $existing = $stmt->fetch();

        if (!$existing) {
            $hints = array_map('trim', explode(',', $question['hints']));
            $hints = array_filter($hints);

            $stmt = $pdo->prepare("
                INSERT INTO questions (
                    title, content, question_type, difficulty, points,
                    category_id, instructor_id, explanation, hints,
                    status, review_status, is_shared, created_at, updated_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'approved', TRUE, NOW(), NOW())
            ");
            $stmt->execute([
                $question['title'],
                $question['content'],
                $question['question_type'],
                $question['difficulty'],
                $question['points'],
                $categoryId,
                $question['instructor_id'],
                $question['explanation'],
                json_encode($hints),
                $question['status']
            ]);

            $questionId = $pdo->lastInsertId();
            echo "Added question: " . $question['title'] . " (ID: $questionId)\n";

            // Insert options if they exist
            if (isset($question['options']) && !empty($question['options'])) {
                foreach ($question['options'] as $index => $option) {
                    $stmt = $pdo->prepare("
                        INSERT INTO question_options (question_id, option_text, is_correct, sort_order)
                        VALUES (?, ?, ?, ?)
                    ");
                    $stmt->execute([$questionId, $option['text'], $option['correct'] ? 1 : 0, $index]);
                }
                echo "  - Added " . count($question['options']) . " options\n";
            }

            // Insert matching pairs if they exist
            if (isset($question['matching_pairs']) && !empty($question['matching_pairs'])) {
                $index = 0;
                foreach ($question['matching_pairs'] as $left => $right) {
                    $stmt = $pdo->prepare("
                        INSERT INTO question_options (question_id, option_text, option_value, sort_order)
                        VALUES (?, ?, ?, ?)
                    ");
                    $stmt->execute([$questionId, $left, $right, $index]);
                    $index++;
                }
                echo "  - Added " . count($question['matching_pairs']) . " matching pairs\n";
            }

            // Handle true_false
            if ($question['question_type'] === 'true_false') {
                $correctIndex = isset($question['correct_option']) ? $question['correct_option'] : 1; // Default to False
                $options = ['True', 'False'];
                foreach ($options as $index => $optionText) {
                    $isCorrect = ($index === $correctIndex) ? 1 : 0;
                    $stmt = $pdo->prepare("
                        INSERT INTO question_options (question_id, option_text, is_correct, sort_order)
                        VALUES (?, ?, ?, ?)
                    ");
                    $stmt->execute([$questionId, $optionText, $isCorrect, $index]);
                }
                echo "  - Added true/false options\n";
            }

        } else {
            echo "Question already exists: " . $question['title'] . "\n";
        }
    }

    echo "Sample questions setup completed successfully.\n";

} catch (PDOException $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
?>