<?php
// ─── API Router v2.0 ─────────────────────────────────────────────────────
// Block direct access
if (realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME']) && empty($_GET['route'])) {
    header('HTTP/1.0 403 Forbidden', true, 403);
    exit;
}

header('Content-Type: application/json; charset=utf-8');
header('X-Frame-Options: DENY');
header("Content-Security-Policy: frame-ancestors 'none';");
// Never let the browser cache API responses — profile/dashboard/etc. must always
// reflect the current session, not whatever was cached before/after login.
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . '/../core/helpers.php';
require_once __DIR__ . '/../config/app.php';
require_once __DIR__ . '/../config/db.php';

// Rate Limiting
if (isset($_SESSION['last_api_request']) && $_SESSION['last_api_request'] > time() - RATE_WINDOW) {
    $_SESSION['api_requests'] = ($_SESSION['api_requests'] ?? 0) + 1;
    if ($_SESSION['api_requests'] > RATE_LIMIT) {
        http_response_code(429);
        echo json_encode(['success' => false, 'message' => 'Too many requests']);
        exit;
    }
} else {
    $_SESSION['api_requests'] = 0;
}
$_SESSION['last_api_request'] = time();

$route = $_GET['route'] ?? '';
$method = $_SERVER['REQUEST_METHOD'];

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

if ($method === 'OPTIONS') { http_response_code(204); exit; }

$routes = [
    'auth/login'           => 'auth.php@login',
    'auth/register'        => 'auth.php@register',
    'auth/check-lock'      => 'auth.php@checkLock',
    'auth/forgot'          => 'auth.php@forgot',
    'auth/reset'           => 'auth.php@passwordReset',
    'auth/email-link'      => 'auth.php@emailLink',
    'auth/verify'          => 'auth.php@verify',
    'auth/logout'          => 'auth.php@logout',
    'profile'              => 'profile.php@get',
    'profile/update'       => 'profile.php@update',
    'profile/password'     => 'profile.php@password',
    'dashboard/stats'      => 'dashboard.php@stats',
    'services'             => 'services.php@serviceList',
    'services/featured'    => 'services.php@featured',
    'services/detail'      => 'services.php@detail',
    'services/upgrade'     => 'services.php@upgrade',
    'services/renew'       => 'services.php@renew',
    'services/delete'      => 'services.php@delete',
    'services/domain'      => 'services.php@updateDomain',
    'services/packages'    => 'services.php@packages',
    'hosting/sso'          => 'hosting.php@sso',
    'hosting/password'     => 'hosting.php@password',
    'hosting/suspend'      => 'hosting.php@suspend',
    'hosting/unsuspend'    => 'hosting.php@unsuspend',
    'hosting/info'         => 'hosting.php@info',
    'hosting/provision'    => 'hosting.php@provision',
    'hosting/send-details' => 'hosting.php@sendDetails',
    'invoices'             => 'invoices.php@invoiceList',
    'invoices/detail'      => 'invoices.php@detail',
    'invoices/revenue'     => 'invoices.php@revenue',
    'support/tickets'      => 'support.php@ticketList',
    'support/ticket'       => 'support.php@detail',
    'support/create'       => 'support.php@create',
    'support/reply'        => 'support.php@reply',
    'support/close'        => 'support.php@close',
    'domains'              => 'domains.php@domainList',
    'domains/info'         => 'domains.php@info',
    'domains/nameservers'  => 'domains.php@nameservers',
    'domains/tlds'         => 'domains.php@tldList',
    'domains/check'        => 'domains.php@checkAvailability',
    'products'             => 'products.php@productList',
    'products/detail'      => 'products.php@detail',
    'orders/cart'          => 'orders.php@cart',
    'orders/coupon'        => 'orders.php@coupon',
    'orders/checkout'      => 'orders.php@checkout',
    'news'                 => 'news.php@newsList',
    'uptime'               => 'uptime.php@uptimeGet',
    'contact'              => 'contact.php@send',
    'payments/config'         => 'payments.php@config',
    'payments/create-order'   => 'payments.php@createOrder',
    'payments/capture-order'  => 'payments.php@captureOrder',
    'payments/btc-claim'      => 'payments.php@btcClaim',
    'admin/services'       => 'admin.php@adminServices',
    'admin/orders'         => 'admin.php@adminOrders',
    'admin/order-status'   => 'admin.php@adminOrderStatus',
    'admin/invoices'       => 'admin.php@adminInvoices',
    'admin/invoice-action' => 'admin.php@adminInvoiceAction',
    'admin/revenue'        => 'admin.php@adminRevenue',
    'admin/users'          => 'admin.php@adminUsers',
    'admin/products'       => 'admin.php@adminProducts',
    'admin/product-toggle' => 'admin.php@adminProductToggle',
    'admin/servers'        => 'admin.php@adminServers',
    'admin/tlds'           => 'admin.php@adminTlds',
    'admin/tld-save'       => 'admin.php@adminTldSave',
    'admin/tld-delete'     => 'admin.php@adminTldDelete',
    'admin/tld-move'       => 'admin.php@adminTldMove',
    'admin/settings'       => 'admin.php@adminSettingsGet',
    'admin/settings-save'  => 'admin.php@adminSettingsSave',
    'admin/registrars'          => 'admin.php@adminRegistrars',
    'admin/registrar-save'      => 'admin.php@adminRegistrarSave',
    'admin/registrar-delete'    => 'admin.php@adminRegistrarDelete',
    'admin/registrar-tlds'      => 'admin.php@adminRegistrarTlds',
    'admin/registrar-tld-save'  => 'admin.php@adminRegistrarTldSave',
    'admin/registrar-tld-delete'=> 'admin.php@adminRegistrarTldDelete',
    'admin/coupons'        => 'admin.php@adminCoupons',
    'admin/coupon-save'    => 'admin.php@adminCouponSave',
    'admin/coupon-delete'  => 'admin.php@adminCouponDelete',
    'admin/news'           => 'admin.php@adminNews',
    'admin/news-create'    => 'admin.php@adminNewsCreate',
    'admin/news-delete'    => 'admin.php@adminNewsDelete',
    'admin/tickets'        => 'admin.php@adminTickets',
    'admin/bulk-close'     => 'admin.php@adminBulkClose',
    'admin/bulk-reminders' => 'admin.php@adminBulkReminders',
    'admin/bulk-invoices'  => 'admin.php@adminBulkInvoices',
];

if (!isset($routes[$route])) {
    http_response_code(404);
    echo json_encode(['success' => false, 'message' => 'Route not found: ' . $route]);
    exit;
}

$handler = $routes[$route];
[$file, $function] = explode('@', $handler);
$filePath = __DIR__ . '/' . $file;

if (!file_exists($filePath)) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Handler not found: ' . $file]);
    exit;
}

require_once $filePath;

if (!function_exists($function)) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Handler function not found: ' . $function]);
    exit;
}

try { $function(); } catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}