<?php
// 设置会话保存路径
$session_path = __DIR__ . '/data/sessions';
if (!is_dir($session_path)) {
    mkdir($session_path, 0777, true);
}
session_save_path($session_path);

// 设置会话参数
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'domain' => '',
    'secure' => false,
    'httponly' => true,
    'samesite' => 'Lax'
]);

// 启动会话
session_start();

require_once 'config/config.php';
require_once 'includes/functions.php';

// 获取路由信息
$request_uri = $_SERVER['REQUEST_URI'];
$path = parse_url($request_uri, PHP_URL_PATH);
$path = trim($path, '/');

// 路由处理
if (empty($path)) {
    // 首页 - 显示所有文章
    include 'pages/home.php';
} elseif (preg_match('/^(\d{4})\/(\d{2})\/(\d{2})\/(.+)\.html$/', $path, $matches)) {
    // 文章页面
    $year = $matches[1];
    $month = $matches[2];
    $day = $matches[3];
    $slug = $matches[4];
    include 'pages/post.php';
} elseif ($path === 'admin') {
    // 管理后台首页
    include 'admin/index.php';
} elseif (strpos($path, 'admin/') === 0) {
    // 管理后台子页面
    $admin_path = substr($path, 6);
    
    // 调试：检查会话数据
    error_log("Admin path access - Session ID: " . session_id());
    error_log("Admin path access - Session data: " . print_r($_SESSION, true));
    error_log("Admin path access - isAdmin result: " . (isAdmin() ? 'true' : 'false'));
    error_log("Admin path access - Requested path: " . $admin_path);
    error_log("Admin path access - Cookie header: " . (isset($_SERVER['HTTP_COOKIE']) ? $_SERVER['HTTP_COOKIE'] : 'No cookies'));
    
    // 特殊处理：如果是admin/且没有具体页面，显示后台首页
    if (empty($admin_path)) {
        include 'admin/index.php';
        return;
    }
    
    // 路径映射
    $path_mapping = [
        'posts' => 'posts',
        'comments' => 'comment-management',
        'users' => 'user-management',
        'edit-post' => 'edit-post',
        'create-post' => 'create-post',
        'settings' => 'settings',
        'admin-settings' => 'admin-settings'
    ];
    
    if (isset($path_mapping[$admin_path])) {
        $admin_path = $path_mapping[$admin_path];
    }
    
    // 检查文件是否存在
    $file_path = 'admin/' . $admin_path . '.php';
    if (file_exists($file_path)) {
        include $file_path;
    } else {
        // 404页面
        http_response_code(404);
        include 'pages/404.php';
    }
} elseif ($path === 'api/comment') {
    // 评论API
    include 'api/comment.php';
} elseif ($path === 'api/login') {
    // 登录API
    include 'api/login.php';
} elseif ($path === 'api/logout') {
    // 登出API
    include 'api/logout.php';
} else {
    // 404页面
    http_response_code(404);
    include 'pages/404.php';
}
?>