<?php
// ============================================================
// 前台入口（唯一前端控制器，伪静态路由全部转发到这里）
// 站点根目录指向 public/
// ============================================================
declare(strict_types=1);

// 生产环境关闭错误回显，避免暴露路径 / SQL 等敏感信息
ini_set('display_errors', '0');
error_reporting(E_ALL);

use core\Auth;
use core\View;
use core\Db;
use core\Csrf;
use core\Security;

define('ROOT_PATH', dirname(__DIR__));

// 未安装或数据库配置丢失（如覆盖上传冲空配置）→ 跳转安装向导
$__cfg = require ROOT_PATH . '/config/database.php';
if (trim((string)($__cfg['dbname'] ?? '')) === '') {
    header('Location: /install/install.php');
    exit;
}

require ROOT_PATH . '/core/Db.php';
require ROOT_PATH . '/core/View.php';
require ROOT_PATH . '/core/Auth.php';
require ROOT_PATH . '/core/Upload.php';
require ROOT_PATH . '/core/autoload.php';

Auth::init();
Security::headers();

// CSRF 校验：所有 POST 提交必须携带有效令牌
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    if (!Csrf::check((string)($_POST['csrf_token'] ?? ''))) {
        http_response_code(403);
        exit('页面已过期，请返回上一页刷新后重试');
    }
}

// 动态页面不缓存，避免后台修改后前台仍显示旧内容
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');

// 解析伪静态路径，如 /info/12.html、/category/3.html、/publish.html
$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
$path = trim(rawurldecode((string)$path), '/');

// 去掉 .html 后缀
$path = preg_replace('/\.html$/', '', $path);
$segments = $path === '' ? [] : explode('/', $path);

// 路由分发
try {
    if ($segments === [] || $segments[0] === 'index') {
        (new app\controller\HomeController())->index();
    } elseif ($segments[0] === 'category' && isset($segments[1])) {
        (new app\controller\HomeController())->category((int)$segments[1]);
    } elseif ($segments[0] === 'info' && isset($segments[1])) {
        (new app\controller\HomeController())->detail((int)$segments[1]);
    } elseif ($segments[0] === 'publish') {
        (new app\controller\PublishController())->index();
    } elseif ($segments[0] === 'merchant' && !isset($segments[1])) {
        (new app\controller\MerchantController())->index();
    } elseif ($segments[0] === 'merchant' && isset($segments[1])) {
        (new app\controller\MerchantController())->detail((int)$segments[1]);
    } elseif ($segments[0] === 'search') {
        (new app\controller\HomeController())->search();
    } elseif ($segments[0] === 'cats') {
        (new app\controller\HomeController())->cats();
    } elseif ($segments[0] === 'captcha') {
        \core\Captcha::createImage();
    } elseif ($segments[0] === 'page' && isset($segments[1])) {
        (new app\controller\HomeController())->page((string)$segments[1]);
    } elseif ($segments[0] === 'news' && isset($segments[1])) {
        (new app\controller\HomeController())->newsDetail((int)$segments[1]);
    } elseif ($segments[0] === 'news') {
        (new app\controller\HomeController())->newsList();
    } elseif ($segments[0] === 'comment') {
        (new app\controller\HomeController())->comment();
    } elseif ($segments[0] === 'message') {
        (new app\controller\HomeController())->message();
    } elseif ($segments[0] === 'login') {
        (new app\controller\AuthController())->login();
    } elseif ($segments[0] === 'register') {
        (new app\controller\AuthController())->register();
    } elseif ($segments[0] === 'logout') {
        (new app\controller\AuthController())->logout();
    } elseif ($segments[0] === 'mine') {
        (new app\controller\MineController())->index();
    } elseif ($segments[0] === 'favorites') {
        (new app\controller\MineController())->favorites();
    } elseif ($segments[0] === 'likes') {
        (new app\controller\MineController())->likes();
    } elseif ($segments[0] === 'favorite') {
        (new app\controller\HomeController())->favorite();
    } elseif ($segments[0] === 'like') {
        (new app\controller\HomeController())->like();
    } else {
        http_response_code(404);
        View::render('404', ['title' => '页面不存在'], 'layout');
    }
} catch (Throwable $e) {
    error_log('[site] ' . $e->getMessage());
    http_response_code(500);
    echo '系统繁忙，请稍后再试';
}
