<?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
    $questionId = $_POST['question_id'] ?? null;
    $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'] ?? []));

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

    // Check if user owns the question or has access
    $stmt = $db->prepare("SELECT id FROM questions WHERE id = ? AND (instructor_id = ? OR is_shared = TRUE)");
    $stmt->execute([$questionId, $userId]);
    if (!$stmt->fetch()) {
        throw new Exception('Question not found or access denied');
    }

    // 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');
    }

    // Update question
    $stmt = $db->prepare("
        UPDATE questions SET
            title = ?, content = ?, question_type = ?, difficulty = ?, points = ?, time_limit = ?,
            category_id = ?, course_id = ?, explanation = ?,
            hints = ?, metadata = ?, is_shared = ?, updated_at = NOW()
        WHERE id = ?
    ");

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

    $stmt->execute([
        $title, $content, $questionType, $difficulty, $points, $timeLimit,
        $categoryId, $courseId, $explanation,
        $hintsJson, $metadataJson, $isShared, $questionId
    ]);

    // Delete existing options
    $stmt = $db->prepare("DELETE FROM question_options WHERE question_id = ?");
    $stmt->execute([$questionId]);

    // 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++;
        }
    }

    // Delete existing tag assignments
    $stmt = $db->prepare("DELETE FROM question_tag_assignments WHERE question_id = ?");
    $stmt->execute([$questionId]);

    // 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 updated successfully!';

    // Redirect back to edit page
    header('Location: edit.php?id=' . $questionId);
    exit;

} catch (Exception $e) {
    $db->rollBack();
    $_SESSION['error_message'] = 'Error updating question: ' . $e->getMessage();
    header('Location: edit.php?id=' . ($questionId ?? ''));
    exit;
}
?>