<?php
/**
 * PartCross CMS - 入口文件 / 路由器
 * PHP + SQLite 轻量级内容管理系统
 */

require __DIR__ . '/config.php';
require APP_ROOT . '/core/Database.php';
require APP_ROOT . '/core/Auth.php';
require APP_ROOT . '/core/helpers.php';
require APP_ROOT . '/core/i18n.php';

// 确保数据结构就绪（须先于语言初始化：默认语种要读 settings.default_lang）
// 内部按「结构指纹」判断，已初始化过的请求只花 1 条 SELECT，不再重跑建表 SQL
Database::ensureSchema();

// 创建上传目录
if (!is_dir(UPLOAD_DIR)) {
    mkdir(UPLOAD_DIR, 0755, true);
}

// 初始化语言（前台生效，后台视图不使用 t() 因此不受影响）
i18n_init();

$requestPath = parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH);

// 优先使用 Web 服务器重写传入的后台路由，避免内部重写后的路径影响刷新。
$adminRoute = trim($_GET['__admin_route'] ?? '', '/');
if ($adminRoute !== '' && isAdminRoute($adminRoute)) {
    $_GET['r'] = $adminRoute;
} elseif ($requestPath === '/sx-admin' || $requestPath === '/sx-admin/') {
    $_GET['r'] = 'dashboard';
} elseif (preg_match('#^/sx-admin/(.+?)/?$#', $requestPath ?? '', $matches)) {
    $_GET['r'] = rawurldecode($matches[1]);
}

// 旧后台 GET 地址统一跳转到新路径。
$requestedRoute = trim($_GET['r'] ?? '', '/');
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET'
    && isAdminRoute($requestedRoute)
    && !str_starts_with($requestPath ?? '', '/sx-admin')) {
    $queryParams = $_GET;
    unset($queryParams['r'], $queryParams['__admin_route']);
    header('Location: ' . url($requestedRoute, $queryParams), true, 301);
    exit;
}

// 路由
$route = trim($_GET['r'] ?? 'home', '/');
$parts = explode('/', $route);
$controller = $parts[0] ?? 'home';
$action = $parts[1] ?? 'index';

// 页面（HTML）不缓存：后台改动（如站点配色）后，前台无需手动清缓存即可生效
if ($controller !== 'api' && !($controller === 'stats' && $action === 'record')) {
    header('Cache-Control: no-store, no-cache, must-revalidate');
    header('Pragma: no-cache');
    // 请求高熵 Client Hints 中的设备型号：Chrome 110+ 的 Android UA 已被降级（型号变常量 K），
    // 服务端只能通过 Sec-CH-UA-Model 拿到，再由前端 window.__CH_MODEL__ 使用。
    // Critical-CH 会让浏览器首访多带一次提示重试；如不想承担这一次开销，删掉该行即可（次访起仍能拿到）。
    header('Accept-CH: Sec-CH-UA-Model, Sec-CH-UA-Platform-Version');
    header('Critical-CH: Sec-CH-UA-Model');
}

// ─── 前台 API 路由（无需登录）────────────────────────────────
if ($controller === 'api') {
    require APP_ROOT . '/controllers/ApiController.php';
    $api = new ApiController();
    if (method_exists($api, $action)) {
        $api->$action();
    } else {
        header('Content-Type: application/json');
        echo json_encode(['error' => 'unknown endpoint']);
    }
    exit;
}

// ─── 前台页面路由（无需登录）────────────────────────────────
$frontRoutes = ['home', 'setting'];
if (in_array($controller, $frontRoutes, true)) {
    $action = $action === 'index' ? $controller : $action;
    require APP_ROOT . '/controllers/FrontController.php';
    $front = new FrontController();
    if (method_exists($front, $action)) {
        $front->$action();
    } else {
        $front->home();
    }
    exit;
}

// 认证路由（不需要登录）
if ($controller === 'auth') {
    if ($action === 'login') {
        // 尝试"记住我"自动登录
        if (Auth::tryRememberLogin()) {
            redirect('dashboard');
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!Auth::verifyCsrf()) {
                $error = 'CSRF验证失败，请刷新页面重试';
            } elseif (!Auth::captchaVerify($_POST['captcha'] ?? '')) {
                $error = '验证码错误';
            } else {
                $username = trim($_POST['username'] ?? '');
                $password = $_POST['password'] ?? '';
                $remember = !empty($_POST['remember']);
                $result = Auth::login($username, $password, $remember);
                if ($result === true) {
                    redirect('dashboard');
                } else {
                    $error = $result;
                }
            }
        }
        view('auth.login', [
            'error' => $error ?? null,
            'captcha_question' => Auth::captchaGenerate(),
        ]);
        exit;
    }
    if ($action === 'logout') {
        Auth::logout();
        redirect('auth/login');
    }
}

// 统计记录API（不需要登录）
if ($controller === 'stats' && $action === 'record') {
    require APP_ROOT . '/controllers/StatsController.php';
    (new StatsController())->record();
    exit;
}

// 以下路由需要登录
Auth::requireLogin();

// 加载控制器并执行
// dashboard 单独处理
if ($controller === 'dashboard') {
    view('dashboard');
    exit;
}

$controllerMap = [
    'banner'   => 'BannerController',
    'file'     => 'FileController',
    'mobile'   => 'MobileController',
    'product'  => 'ProductController',
    'stats'    => 'StatsController',
    'task'     => 'TaskController',
    'user'     => 'UserController',
    'settings' => 'SettingsController',
];

if (!array_key_exists($controller, $controllerMap)) {
    flash('danger', '页面不存在');
    redirect('dashboard');
}

$className = $controllerMap[$controller];
require APP_ROOT . "/controllers/{$className}.php";
$instance = new $className();

// 方法映射
if (method_exists($instance, $action)) {
    $instance->$action();
} else {
    flash('danger', '操作不存在');
    redirect('dashboard');
}