<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *"); // For development, can be tightened later
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit(0);
}

require_once 'auth.php';

$request_uri = explode('?', $_SERVER['REQUEST_URI'], 2);
$path = trim($request_uri[0], '/');
$segments = explode('/', $path);

// Assuming URL structure is /api/v1/endpoint
$endpoint = $segments[2] ?? null; 
$method = $_SERVER['REQUEST_METHOD'];
$data = json_decode(file_get_contents('php://input'), true);

$response = ['success' => false, 'message' => 'Invalid endpoint.'];
http_response_code(404);

if ($endpoint) {
    switch ($endpoint) {
        case 'register':
            if ($method == 'POST') $response = register_user($data);
            break;
        case 'login':
            if ($method == 'POST') $response = login_user($data);
            break;
        case 'logout':
            // Logout now requires a token to identify the user
            if ($method == 'POST') $response = logout_user(get_bearer_token());
            break;
        // NEW ENDPOINT
        case 'validate_session':
            if ($method == 'POST') $response = validate_session($data);
            break;
        case 'test':
            $response = ['success' => true, 'message' => 'API is working!'];
            http_response_code(200);
            break;
    }
}

echo json_encode($response);
?>