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

// Set JSON response header
header('Content-Type: application/json');

// Check authentication
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['error' => 'Authentication required']);
    exit;
}

// Check if user is instructor or admin
if (!hasAnyRole(['instructor', 'admin'])) {
    http_response_code(403);
    echo json_encode(['error' => 'Access denied']);
    exit;
}

$db = getDB();
$userId = $_SESSION['user_id'];
$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($method) {
        case 'GET':
            // Get questions with optional filters
            $search = $_GET['search'] ?? '';
            $type = $_GET['type'] ?? '';
            $difficulty = $_GET['difficulty'] ?? '';
            $category = $_GET['category'] ?? '';
            $status = $_GET['status'] ?? '';
            $course = $_GET['course'] ?? '';
            $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 50;
            $offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0;

            $query = "
                SELECT q.*, qc.name as category_name, c.title as course_title,
                       GROUP_CONCAT(DISTINCT qt.name) as tag_names
                FROM questions q
                LEFT JOIN question_categories qc ON q.category_id = qc.id
                LEFT JOIN courses c ON q.course_id = c.id
                LEFT JOIN question_tag_assignments qta ON q.id = qta.question_id
                LEFT JOIN question_tags qt ON qta.tag_id = qt.id
                WHERE (q.instructor_id = ? OR q.is_shared = TRUE)
            ";

            $params = [$userId];

            if (!empty($search)) {
                $query .= " AND (q.title LIKE ? OR q.content LIKE ?)";
                $params[] = "%$search%";
                $params[] = "%$search%";
            }

            if (!empty($type)) {
                $query .= " AND q.question_type = ?";
                $params[] = $type;
            }

            if (!empty($difficulty)) {
                $query .= " AND q.difficulty = ?";
                $params[] = $difficulty;
            }

            if (!empty($category)) {
                $query .= " AND q.category_id = ?";
                $params[] = $category;
            }

            if (!empty($status)) {
                $query .= " AND q.status = ?";
                $params[] = $status;
            }

            if (!empty($course)) {
                $query .= " AND q.course_id = ?";
                $params[] = $course;
            }

            $query .= " GROUP BY q.id ORDER BY q.created_at DESC LIMIT ? OFFSET ?";
            $params[] = $limit;
            $params[] = $offset;

            $stmt = $db->prepare($query);
            $stmt->execute($params);
            $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Process questions to include options and format data
            foreach ($questions as &$question) {
                // Decode JSON fields
                $question['tags'] = $question['tag_names'] ? explode(',', $question['tag_names']) : [];
                $question['hints'] = json_decode($question['hints'], true) ?: [];
                $question['metadata'] = json_decode($question['metadata'], true) ?: [];

                // Get options for applicable question types
                if (in_array($question['question_type'], ['mcq_single', 'mcq_multiple', 'true_false', 'matching'])) {
                    $stmt = $db->prepare("SELECT * FROM question_options WHERE question_id = ? ORDER BY sort_order");
                    $stmt->execute([$question['id']]);
                    $question['options'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
                }

                // Remove internal fields
                unset($question['tag_names']);
            }

            echo json_encode([
                'success' => true,
                'data' => $questions,
                'meta' => [
                    'total' => count($questions),
                    'limit' => $limit,
                    'offset' => $offset
                ]
            ]);
            break;

        case 'POST':
            // Create new question
            $data = json_decode(file_get_contents('php://input'), true);

            if (!$data) {
                throw new Exception('Invalid JSON data');
            }

            // Validate required fields
            if (empty($data['title']) || empty($data['content']) || empty($data['question_type'])) {
                throw new Exception('Title, content, and question_type are required');
            }

            $db->beginTransaction();

            // 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, created_at, updated_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
            ");

            $stmt->execute([
                $data['title'],
                $data['content'],
                $data['question_type'],
                $data['difficulty'] ?? 'medium',
                $data['points'] ?? 1,
                $data['time_limit'] ?? null,
                $data['category_id'] ?? null,
                $data['course_id'] ?? null,
                $userId,
                json_encode($data['tags'] ?? []),
                $data['explanation'] ?? '',
                json_encode($data['hints'] ?? []),
                json_encode($data['metadata'] ?? []),
                $data['status'] ?? 'draft'
            ]);

            $questionId = $db->lastInsertId();

            // Handle options if provided
            if (isset($data['options']) && is_array($data['options'])) {
                foreach ($data['options'] as $index => $option) {
                    $stmt = $db->prepare("
                        INSERT INTO question_options (question_id, option_text, is_correct, sort_order)
                        VALUES (?, ?, ?, ?)
                    ");
                    $stmt->execute([
                        $questionId,
                        $option['text'] ?? $option['option_text'],
                        $option['is_correct'] ?? false,
                        $index
                    ]);
                }
            }

            $db->commit();

            echo json_encode([
                'success' => true,
                'message' => 'Question created successfully',
                'data' => ['id' => $questionId]
            ]);
            break;

        default:
            http_response_code(405);
            echo json_encode(['error' => 'Method not allowed']);
    }

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
?>