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

try {
    $pdo = getDB();

    // Get sample exams
    $sampleExams = [
        'PHP Fundamentals Quiz' => [
            'categories' => ['Programming'],
            'difficulties' => ['easy', 'medium'],
            'target_questions' => 4
        ],
        'Advanced JavaScript Certification' => [
            'categories' => ['Programming', 'Web Development'],
            'difficulties' => ['medium', 'hard'],
            'target_questions' => 5
        ],
        'Database Design Midterm' => [
            'categories' => ['Programming'],
            'difficulties' => ['medium', 'hard'],
            'target_questions' => 4
        ],
        'Web Development Practice Test' => [
            'categories' => ['Web Development', 'Programming'],
            'difficulties' => ['easy', 'medium'],
            'target_questions' => 5
        ]
    ];

    foreach ($sampleExams as $examTitle => $config) {
        // Get exam ID
        $stmt = $pdo->prepare("SELECT id FROM exams WHERE title = ?");
        $stmt->execute([$examTitle]);
        $exam = $stmt->fetch();

        if (!$exam) {
            echo "Exam not found: $examTitle\n";
            continue;
        }

        $examId = $exam['id'];
        echo "Processing exam: $examTitle (ID: $examId)\n";

        // Check if exam already has questions
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM exam_questions WHERE exam_id = ?");
        $stmt->execute([$examId]);
        $existingCount = $stmt->fetch()['count'];

        if ($existingCount > 0) {
            echo "  - Exam already has $existingCount questions, skipping\n";
            continue;
        }

        // Get category IDs
        $categoryIds = [];
        foreach ($config['categories'] as $categoryName) {
            $stmt = $pdo->prepare("SELECT id FROM question_categories WHERE name = ?");
            $stmt->execute([$categoryName]);
            $category = $stmt->fetch();
            if ($category) {
                $categoryIds[] = $category['id'];
            }
        }

        // Get available questions
        $placeholders = str_repeat('?,', count($categoryIds) - 1) . '?';
        $placeholders2 = str_repeat('?,', count($config['difficulties']) - 1) . '?';

        $query = "
            SELECT q.id, q.title, q.points, q.difficulty, qc.name as category_name
            FROM questions q
            LEFT JOIN question_categories qc ON q.category_id = qc.id
            WHERE q.category_id IN ($placeholders)
            AND q.difficulty IN ($placeholders2)
            AND q.status = 'approved'
            ORDER BY q.difficulty, RAND()
        ";

        $params = array_merge($categoryIds, $config['difficulties']);
        $stmt = $pdo->prepare($query);
        $stmt->execute($params);
        $availableQuestions = $stmt->fetchAll();

        echo "  - Found " . count($availableQuestions) . " available questions\n";

        // Select questions for this exam
        $selectedQuestions = array_slice($availableQuestions, 0, $config['target_questions']);
        $sortOrder = 1;
        $totalPoints = 0;

        foreach ($selectedQuestions as $question) {
            $stmt = $pdo->prepare("
                INSERT INTO exam_questions (exam_id, question_id, points, sort_order)
                VALUES (?, ?, ?, ?)
            ");
            $stmt->execute([$examId, $question['id'], $question['points'], $sortOrder]);

            echo "    - Added: {$question['title']} ({$question['points']} pts, {$question['difficulty']})\n";
            $totalPoints += $question['points'];
            $sortOrder++;
        }

        // Update exam total points
        $stmt = $pdo->prepare("UPDATE exams SET total_points = ? WHERE id = ?");
        $stmt->execute([$totalPoints, $examId]);

        echo "  - Total points updated to: $totalPoints\n";
        echo "  - Added " . count($selectedQuestions) . " questions to $examTitle\n\n";
    }

    echo "Sample exam questions linking completed successfully!\n";

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