<?php
session_start();
header('Content-Type: text/html; charset=utf-8');

// 检查用户是否登录
function checkLogin() {
    return isset($_SESSION['user_id']);
}

// 重定向函数
function redirect($url) {
    header('Location: ' . $url);
    exit;
}

// 处理请求
if (isset($_GET['page'])) {
    $page = $_GET['page'];
    
    // 检查是否需要登录
    $requiresLogin = true;
    if ($page === 'login' || $page === 'register') {
        $requiresLogin = false;
    }
    
    // 如果需要登录但未登录，重定向到登录页面
    if ($requiresLogin && !checkLogin()) {
        redirect('pages/login.php');
    }
    
    // 加载相应的页面
    $pageFile = 'pages/' . $page . '.php';
    if (file_exists($pageFile)) {
        require_once $pageFile;
    } else {
        // 页面不存在，显示404
        echo '<h1>404 Not Found</h1>';
    }
} else {
    // 默认重定向到仪表盘或登录页面
    if (checkLogin()) {
        redirect('pages/dashboard.php');
    } else {
        redirect('pages/login.php');
    }
}
?>