<?php

require_once 'config.php';

// Authenticate the request
authenticateRequest($API_KEY);

$method = $_SERVER['REQUEST_METHOD'];
$table = 'celpip_questions';

switch ($method) {
    // =========================
    // GET QUESTIONS
    // =========================
    case 'GET':
        if (isset($_GET['id'])) {
            $stmt = $pdo->prepare("SELECT * FROM $table WHERE id = :id");
            $stmt->execute([':id' => $_GET['id']]);
            $question = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($question) {
                $question['options'] = json_decode($question['options']);
                // Add full URLs for media if they are not already absolute
                if ($question['image_url'] && strpos($question['image_url'], 'http') !== 0) {
                    $question['image_url'] = $IMAGE_BASE_URL . $question['image_url'];
                }
                if ($question['audio_url'] && strpos($question['audio_url'], 'http') !== 0) {
                    $question['audio_url'] = $AUDIO_BASE_URL . $question['audio_url'];
                }
                response(true, 'Question retrieved successfully', $question);
            } else {
                response(false, 'Question not found');
            }
        } else {
            $stmt = $pdo->query("SELECT * FROM $table");
            $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            foreach ($questions as &$q) {
                $q['options'] = json_decode($q['options']);
                // Add full URLs for media if they are not already absolute
                if ($q['image_url'] && strpos($q['image_url'], 'http') !== 0) {
                    $q['image_url'] = $IMAGE_BASE_URL . $q['image_url'];
                }
                if ($q['audio_url'] && strpos($q['audio_url'], 'http') !== 0) {
                    $q['audio_url'] = $AUDIO_BASE_URL . $q['audio_url'];
                }
            }
            
            response(true, 'Questions retrieved successfully', $questions);
        }
        break;

    // =========================
    // CREATE QUESTION
    // =========================
    case 'POST':
        // For multipart/form-data, data is in $_POST
        $data = $_POST;
        // If data is sent as JSON (not multipart), check php://input
        if (empty($data)) {
            $data = json_decode(file_get_contents('php://input'), true);
        }

        if (!isset($data['question'], $data['options'], $data['answer'])) {
            response(false, 'Missing required fields');
        }

        // Handle File Uploads
        $imageFilename = handleFileUpload($_FILES['image'] ?? null, '../questionbank/images/');
        $audioFilename = handleFileUpload($_FILES['audio'] ?? null, '../questionbank/audio/');

        $stmt = $pdo->prepare("INSERT INTO $table (set_name, section_name, part_name, question, options, answer, image_url, audio_url, question_type) 
                                VALUES (:set_name, :section_name, :part_name, :question, :options, :answer, :image_url, :audio_url, :question_type)");

        $stmt->execute([
            ':set_name' => $data['set_name'] ?? null,
            ':section_name' => $data['section_name'] ?? null,
            ':part_name' => $data['part_name'] ?? null,
            ':question' => $data['question'],
            ':options' => is_string($data['options']) ? $data['options'] : json_encode($data['options']),
            ':answer' => $data['answer'],
            ':image_url' => $imageFilename,
            ':audio_url' => $audioFilename,
            ':question_type' => $data['question_type'] ?? null
        ]);

        response(true, 'Question created successfully', [
            'insert_id' => $pdo->lastInsertId()
        ]);
        break;

    // =========================
    // UPDATE QUESTION
    // =========================
    case 'PUT':
        // PHP doesn't populate $_FILES for PUT requests easily if sent as multipart.
        // Usually, for simplicity in admin panels, we use POST with an _method=PUT or just stick to POST for updates with files.
        // However, let's handle JSON-based PUT (without files) and suggest using POST for media updates if needed.
        
        $input = json_decode(file_get_contents('php://input'), true);

        if (!isset($input['id'])) {
            response(false, 'Question ID is required');
        }

        $stmt = $pdo->prepare("UPDATE $table SET
            set_name = :set_name,
            section_name = :section_name,
            part_name = :part_name,
            question = :question,
            options = :options,
            answer = :answer,
            question_type = :question_type,
            image_url = :image_url,
            audio_url = :audio_url
            WHERE id = :id
        ");

        $stmt->execute([
            ':id' => $input['id'],
            ':set_name' => $input['set_name'] ?? null,
            ':section_name' => $input['section_name'] ?? null,
            ':part_name' => $input['part_name'] ?? null,
            ':question' => $input['question'],
            ':options' => json_encode($input['options']),
            ':answer' => $input['answer'],
            ':question_type' => $input['question_type'] ?? null,
            ':image_url' => $input['image_url'] ?? null,
            ':audio_url' => $input['audio_url'] ?? null
        ]);

        response(true, 'Question updated successfully');
        break;

    // =========================
    // DELETE QUESTION
    // =========================
    case 'DELETE':
        parse_str($_SERVER['QUERY_STRING'], $query);

        if (!isset($query['id'])) {
            response(false, 'Question ID is required');
        }

        $stmt = $pdo->prepare("DELETE FROM $table WHERE id = :id");
        $stmt->execute([':id' => $query['id']]);

        response(true, 'Question deleted successfully');
        break;

    default:
        response(false, 'Unsupported request method');
        break;
}

?>