<?php
/**
 * Simple Judge API Test
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

try {
    session_start();
    
    // Simple auth simulation
    if (!isset($_SESSION['user_id'])) {
        $_SESSION['user_id'] = 1;
        $_SESSION['user_type'] = 'admin';
        $_SESSION['username'] = 'admin';
    }
    
    $action = $_GET['action'] ?? $_POST['action'] ?? '';
    $response = ['success' => false, 'data' => null, 'message' => ''];

    // Get current user context
    $user_type = $_SESSION['user_type'];
    $user_id = $_SESSION['user_id'];
    $judge_id = $user_id;

    switch ($action) {
        case 'test':
            $response = [
                'success' => true,
                'data' => [
                    'message' => 'API is working!',
                    'timestamp' => date('Y-m-d H:i:s'),
                    'judge_id' => $judge_id,
                    'user_type' => $user_type
                ]
            ];
            break;
            
        case 'get_judge_context':
            $response = [
                'success' => true,
                'data' => [
                    'judge_id' => $judge_id,
                    'judge_name' => $_SESSION['username'],
                    'user_type' => $user_type,
                    'assigned_events' => [
                        ['id' => 3, 'name' => 'Test Event', 'date' => '2025-08-23']
                    ],
                    'default_event_id' => 3
                ]
            ];
            break;
            
        default:
            $response = [
                'success' => false,
                'message' => 'Invalid action: ' . $action
            ];
    }

    echo json_encode($response);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Server error: ' . $e->getMessage(),
        'error_code' => 'INTERNAL_ERROR'
    ]);
}
?>
