<?php
declare(strict_types=1);
$_rawInput = file_get_contents('php://input');
if (!defined('CACHED_RAW_INPUT')) define('CACHED_RAW_INPUT', $_rawInput);
require_once __DIR__ . '/../system/init.php';
if (!isset($_SESSION['_si'])) $_SESSION['_si'] = $store_id;
if (!isset($_SESSION['_hits'])) $_SESSION['_hits'] = 0;
App::apiHeaders();
App::requirePost();
$body = json_decode($_rawInput, true);
if (!$body) { App::err('Invalid request', 400); }
$page   = trim($body['page'] ?? '');
$csrf   = $body['csrf'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
$action = $body['action'] ?? '';
if ($action && !$page) {
if (!in_array($action, ['watchdog', 'telemetry']) && !Auth::validateCsrf($csrf)) {
App::err('Security token expired. Please refresh.', 403);
}
$legacyRouteMap = [
'login'          => 'auth.login',
'register'       => 'auth.register',
'logout'         => 'auth.logout',
'get_orders'     => 'account.get_orders',
'get_reviews'    => 'account.get_reviews',
'get_tickets'    => 'account.get_tickets',
'create_ticket'  => 'account.create_ticket',
'update_profile' => 'account.update_profile',
'get_wallets'    => 'crypto.get_wallets',
'track_order'    => 'order.track',
'submit_review'  => 'review.submit',
'vote_review'    => 'review.vote',
'submit_support' => 'support.submit',
'watchdog'       => 'telemetry.watchdog',
'telemetry'      => 'telemetry.telemetry',
];
if (isset($legacyRouteMap[$action])) {
$body['route'] = $legacyRouteMap[$action];
$_POST = $body;
require __DIR__ . '/index.php';
exit;
}
App::err('Unknown action: ' . htmlspecialchars($action), 404);
}
if (!$page || !preg_match('/^[a-z0-9\-]+$/', $page) || strlen($page) > 40) {
App::err('Invalid page', 400);
}
if ($page === 'tracking') $page = 'track';
if (!in_array($page, PUBLIC_PAGES, true)) {
App::err('Page not found.', 404);
}
$file = dirname(__DIR__) . '/pages/' . $page . '.php';
if (!file_exists($file)) {
App::err('Page not found.', 404);
}
App::rateLimitDB('spa_router', 120, 60);
ob_start();
include $file;
$html = ob_get_clean();
$newCsrf = Auth::csrf();
echo json_encode([
'html'  => $html,
'csrf'  => $newCsrf,
'page'  => $page,
]);
exit;
