<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../config/rbac.php';
require_once '../../includes/functions.php';
require_once '../../includes/middleware.php';

// Check if user is instructor or admin
anyRoleMiddleware(['instructor', 'admin']);

$user = getUserContext();
$db = getDB();
$userId = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit;
}

try {
    $db->beginTransaction();

    // Get form data
    $questionType = $_POST['question_type'] ?? '';
    $title = trim($_POST['title'] ?? '');
    $content = trim($_POST['content'] ?? '');
    $difficulty = $_POST['difficulty'] ?? 'medium';
    $points = floatval($_POST['points'] ?? 1);
    $timeLimit = !empty($_POST['time_limit']) ? intval($_POST['time_limit']) : null;
    $categoryId = !empty($_POST['category_id']) ? intval($_POST['category_id']) : null;
    $courseId = !empty($_POST['course_id']) ? intval($_POST['course_id']) : null;
    $tags = $_POST['tags'] ?? [];
    $isShared = isset($_POST['is_shared']) ? 1 : 0;
    $explanation = trim($_POST['explanation'] ?? '');
    $hints = array_filter(array_map('trim', $_POST['hints'] ?? []));
    $action = $_POST['action'] ?? 'save_draft';

    // Validate required fields
    if (empty($questionType) || empty($title) || empty($content)) {
        throw new Exception('Required fields are missing');
    }

    // Determine status based on action and user role
    $status = 'draft';
    $reviewStatus = 'not_submitted';
    if ($action === 'submit_review') {
        $status = 'pending_review';
        $reviewStatus = 'pending';
    } elseif ($action === 'save_approved' && hasRole('admin')) {
        $status = 'approved';
        $reviewStatus = 'approved';
    } elseif (hasRole('admin')) {
        // Admins can create approved questions directly
        $status = 'approved';
        $reviewStatus = 'approved';
    }

    // Prepare metadata based on question type
    $metadata = [];

    // Handle different question types
    switch ($questionType) {
        case 'mcq_single':
        case 'mcq_multiple':
            $options = array_filter(array_map('trim', $_POST['options'] ?? []));
            if (empty($options)) {
                throw new Exception('At least one option is required');
            }

            $correctOptions = [];
            if ($questionType === 'mcq_single') {
                $correctOption = $_POST['correct_option'] ?? null;
                if ($correctOption === null) {
                    throw new Exception('Please select the correct answer');
                }
                $correctOptions = [$correctOption];
            } else {
                $correctOptions = $_POST['correct_options'] ?? [];
                if (empty($correctOptions)) {
                    throw new Exception('Please select at least one correct answer');
                }
            }

            $metadata['options'] = $options;
            $metadata['correct_options'] = $correctOptions;
            break;

        case 'true_false':
            $correctOption = $_POST['correct_option'] ?? null;
            if ($correctOption === null) {
                throw new Exception('Please select the correct answer');
            }
            $metadata['correct_option'] = $correctOption;
            break;

        case 'matching':
            $leftSides = array_filter(array_map('trim', $_POST['matching_left'] ?? []));
            $rightSides = array_filter(array_map('trim', $_POST['matching_right'] ?? []));

            if (count($leftSides) !== count($rightSides) || empty($leftSides)) {
                throw new Exception('Matching pairs are incomplete');
            }

            $metadata['matching_pairs'] = array_combine($leftSides, $rightSides);
            break;

        case 'fill_blanks':
            $blanksTemplate = trim($_POST['blanks_template'] ?? '');
            if (empty($blanksTemplate)) {
                throw new Exception('Fill in the blanks template is required');
            }

            // Extract blanks from template
            preg_match_all('/\[blank\]/', $blanksTemplate, $matches);
            $blankCount = count($matches[0]);

            if ($blankCount === 0) {
                throw new Exception('Template must contain at least one [blank] placeholder');
            }

            $metadata['blanks_template'] = $blanksTemplate;
            $metadata['blank_count'] = $blankCount;
            break;

        case 'code':
            $codeTemplate = trim($_POST['code_template'] ?? '');
            $metadata['code_template'] = $codeTemplate;
            break;

        case 'essay':
        case 'short_answer':
            // No additional metadata needed
            break;

        default:
            throw new Exception('Invalid question type');
    }

    $correctAnswer = buildCorrectAnswer($questionType, $metadata);

    // Insert question
    $stmt = $db->prepare("
        INSERT INTO questions (
            title, content, question_type, difficulty, points, time_limit,
            category_id, course_id, instructor_id, tags, explanation,
            hints, metadata, status, review_status, is_shared,
            correct_answer, created_at, updated_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
    ");

    $tagsJson = json_encode($tags);
    $hintsJson = json_encode($hints);
    $metadataJson = json_encode($metadata);

    $stmt->execute([
        $title, $content, $questionType, $difficulty, $points, $timeLimit,
        $categoryId, $courseId, $userId, $tagsJson, $explanation,
        $hintsJson, $metadataJson, $status, $reviewStatus, $isShared,
        $correctAnswer
    ]);

    $questionId = $db->lastInsertId();

    // Handle options for MCQ questions
    if (in_array($questionType, ['mcq_single', 'mcq_multiple', 'true_false'])) {
        if ($questionType === 'true_false') {
            // Insert True/False options
            $options = ['True', 'False'];
            $correctIndex = intval($correctOption);
        } else {
            $options = $metadata['options'];
            $correctOptions = $metadata['correct_options'];
        }

        foreach ($options as $index => $optionText) {
            $isCorrect = 0;
            if ($questionType === 'mcq_single') {
                $isCorrect = ($index == $correctOptions[0]) ? 1 : 0;
            } elseif ($questionType === 'mcq_multiple') {
                $isCorrect = in_array($index, $correctOptions) ? 1 : 0;
            } elseif ($questionType === 'true_false') {
                $isCorrect = ($index === $correctIndex) ? 1 : 0;
            }

            $stmt = $db->prepare("
                INSERT INTO question_options (question_id, option_text, is_correct, sort_order)
                VALUES (?, ?, ?, ?)
            ");
            $stmt->execute([$questionId, $optionText, $isCorrect, $index]);
        }
    }

    // Handle matching pairs
    if ($questionType === 'matching') {
        $pairIndex = 0;
        foreach ($metadata['matching_pairs'] as $left => $right) {
            // Insert left side
            $stmt = $db->prepare("
                INSERT INTO question_options (question_id, option_text, option_value, sort_order)
                VALUES (?, ?, ?, ?)
            ");
            $stmt->execute([$questionId, $left, $right, $pairIndex]);

            $pairIndex++;
        }
    }

    // Handle tags
    if (!empty($tags)) {
        foreach ($tags as $tagId) {
            $stmt = $db->prepare("
                INSERT INTO question_tag_assignments (question_id, tag_id)
                VALUES (?, ?)
            ");
            $stmt->execute([$questionId, $tagId]);
        }
    }

    $db->commit();

    // Set success message
    $_SESSION['success_message'] = 'Question saved successfully!';

    // Redirect based on action
    if ($action === 'submit_review') {
        header('Location: index.php?status=pending_review');
    } else {
        header('Location: edit.php?id=' . $questionId);
    }
    exit;

} catch (Exception $e) {
    $db->rollBack();
    $_SESSION['error_message'] = 'Error saving question: ' . $e->getMessage();
    header('Location: new.php');
    exit;
}
function buildCorrectAnswer(string $questionType, array $metadata): ?string
{
    if ($questionType === 'mcq_single') {
        return isset($metadata['correct_options'][0]) ? (string) $metadata['correct_options'][0] : null;
    }

    if ($questionType === 'mcq_multiple') {
        return json_encode(array_map('strval', $metadata['correct_options'] ?? []), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }

    if ($questionType === 'true_false') {
        return isset($metadata['correct_option']) ? (string) $metadata['correct_option'] : null;
    }

    if ($questionType === 'matching') {
        return json_encode($metadata['matching_pairs'] ?? [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }

    return null;
}
?>