<?php
declare(strict_types=1);

require_once __DIR__ . '/_app_guard.php';
app_guard_validate();

$route = strtolower(trim((string)($_REQUEST['route'] ?? $_REQUEST['endpoint'] ?? $_REQUEST['action'] ?? '')));
$route = preg_replace('/[^a-z0-9_\.]/', '', $route);
$route = preg_replace('/\.php$/', '', $route);

$map = [
    'get_config' => __DIR__ . '/_handlers/get_config.php',
    'check_mac' => __DIR__ . '/_handlers/check_mac.php',
    'auth' => __DIR__ . '/_handlers/auth.php',
    'teste' => __DIR__ . '/_handlers/teste.php',
    'device_check' => __DIR__ . '/_handlers/device_check.php',
    'check_update' => __DIR__ . '/_handlers/check_update.php',
    'get_theme' => __DIR__ . '/_handlers/get_theme.php',
    'get_usuario' => __DIR__ . '/_handlers/get_usuario.php',
    'home_web' => __DIR__ . '/_handlers/home_web.php',
    'remote_cmd' => __DIR__ . '/_handlers/remote.php',
    'heartbeat' => __DIR__ . '/_handlers/heartbeat.php',
    'planos' => __DIR__ . '/_handlers/planos.php',
    'thefulltv_gerar_pix' => __DIR__ . '/_handlers/thefulltv_gerar_pix.php',
    'thefulltv_webhook' => __DIR__ . '/_handlers/thefulltv_webhook.php',
    'update_profile' => __DIR__ . '/_handlers/update_profile.php',
    'top10' => __DIR__ . '/_handlers/top10.php',
    'get_dns' => __DIR__ . '/_handlers/get_dns.php',
    'get_purchase_key' => __DIR__ . '/_handlers/get_purchase_key.php',    'get_mac_message' => __DIR__ . '/_handlers/get_mac_message.php',
    'ack_mac_message' => __DIR__ . '/_handlers/ack_mac_message.php',
    'get_access_rules' => __DIR__ . '/_handlers/get_access_rules.php',
    'progress_sync' => __DIR__ . '/_handlers/progress_sync.php',
    'realtime_check' => __DIR__ . '/_handlers/realtime_check.php',
    'mac_status' => __DIR__ . '/_handlers/mac_status.php',
    'vencimento_config' => __DIR__ . '/_handlers/vencimento_config.php',
    'emuladores_config' => __DIR__ . '/_handlers/emuladores_config.php',
    'users' => dirname(__DIR__) . '/telas/users.php',
];

if ($route === '' || !isset($map[$route]) || !is_file($map[$route])) {
    header('Content-Type: application/json; charset=utf-8');
    http_response_code(404);
    echo json_encode([
        'status' => 'error',
        'message' => 'rota_invalida',
        'route' => $route,
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$_REQUEST['unified_api'] = '1';
$_GET['unified_api'] = '1';
require $map[$route];
