<?php
/**
 * Front-controller: single entry point for all /api/ requests.
 * Handles CORS, JSON content type, global error catching, and dispatch.
 */
require_once __DIR__ . '/../common.php';
require_once __DIR__ . '/../db_init.php';
require_once __DIR__ . '/../lib/response.php';
require_once __DIR__ . '/../lib/errors.php';
require_once __DIR__ . '/../lib/validate.php';
require_once __DIR__ . '/../lib/api_log.php';

// Parse route early (for access logs)
$requestUri = $_SERVER['REQUEST_URI'] ?? '';
$path = parse_url($requestUri, PHP_URL_PATH);
$base = dirname($_SERVER['SCRIPT_NAME']);
$route = trim(substr($path, strlen($base)), '/');
$route = preg_replace('/\.php$/', '', $route);
$route = strtolower($route);

$method = $_SERVER['REQUEST_METHOD'];

if (!defined('QDB_TESTING')) {
    qdb_api_log_begin($method, $route !== '' ? $route : '(root)');
    register_shutdown_function('qdb_api_log_finish');
}

// CORS
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-QDB-Client');

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

header('Content-Type: application/json; charset=UTF-8');

// Dispatch table: route -> handler file
$routes = [
    'questionnaires'     => __DIR__ . '/../handlers/questionnaires.php',
    'questions'          => __DIR__ . '/../handlers/questions.php',
    'answer_options'     => __DIR__ . '/../handlers/answer_options.php',
    'translations'       => __DIR__ . '/../handlers/translations.php',
    'users'              => __DIR__ . '/../handlers/users.php',
    'assignments'        => __DIR__ . '/../handlers/assignments.php',
    'clients'            => __DIR__ . '/../handlers/clients.php',
    'results'            => __DIR__ . '/../handlers/results.php',
    'export'             => __DIR__ . '/../handlers/export.php',
    'analytics'          => __DIR__ . '/../handlers/analytics.php',
    'scoring_profiles'   => __DIR__ . '/../handlers/scoring_profiles.php',
    'program_sessions'   => __DIR__ . '/../handlers/program_sessions.php',
    'coaches'            => __DIR__ . '/../handlers/coaches.php',
    'app_questionnaires' => __DIR__ . '/../handlers/app_questionnaires.php',
    'app_session_schedule' => __DIR__ . '/../handlers/app_session_schedule.php',
    'schedule'           => __DIR__ . '/../handlers/schedule.php',
    'logout'             => __DIR__ . '/../handlers/logout.php',
    'session'            => __DIR__ . '/../handlers/session.php',
    'auth/login'         => __DIR__ . '/../handlers/auth.php',
    'auth/change-password' => __DIR__ . '/../handlers/auth.php',
    'auth/keycloak-config' => __DIR__ . '/../handlers/auth.php',
    'auth/keycloak-login' => __DIR__ . '/../handlers/auth.php',
    'auth/keycloak-callback' => __DIR__ . '/../handlers/auth.php',
    'backup'             => __DIR__ . '/../handlers/backup.php',
    'dev'                => __DIR__ . '/../handlers/dev.php',
    'dev/import'         => __DIR__ . '/../handlers/dev.php',
    'activity-log'       => __DIR__ . '/../handlers/activity_log.php',
    'settings'           => __DIR__ . '/../handlers/settings.php',
];

try {
    if (!isset($routes[$route])) {
        json_error('NOT_FOUND', "Unknown endpoint: $route", 404);
    }

    $handlerFile = $routes[$route];
    if (!file_exists($handlerFile)) {
        json_error('NOT_FOUND', "Handler not found for: $route", 404);
    }

    require $handlerFile;

} catch (Throwable $e) {
    if (defined('QDB_TESTING') && (
        $e instanceof \Tests\Support\JsonSuccessResponse
        || $e instanceof \Tests\Support\JsonErrorResponse
        || $e instanceof \Tests\Support\RawHttpResponse
    )) {
        throw $e;
    }
    require_once __DIR__ . '/../lib/errors.php';
    qdb_emit_api_error($e, "API $method $route");
}
