<?php
session_start();

function check_admin_login() {
    if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
        header('Location: index.php');
        exit;
    }
}

function check_user_login() {
    global $pdo; // 引用全局数据库变量
    
    // 1. 基础检查：Session 是否存在
    if (!isset($_SESSION['user_logged_in']) || $_SESSION['user_logged_in'] !== true) {
        header('Location: user/index.php');
        exit;
    }

    // 2. Token 一致性检查 (实现强制下线的关键)
    // 必须数据库连接正常且 Session 中有 user_id
    if (isset($pdo) && isset($_SESSION['user_id'])) {
        try {
            $stmt = $pdo->prepare("SELECT token FROM users WHERE id = ?");
            $stmt->execute([$_SESSION['user_id']]);
            $user = $stmt->fetch();

            // 逻辑：
            // 如果数据库里有 Token，且 Session 里也有 Token
            // 但两者不一致 -> 说明密码被改了，或者 Token 被刷新了 -> 强制下线
            if ($user && !empty($user['token'])) {
                if (!isset($_SESSION['user_token']) || $_SESSION['user_token'] !== $user['token']) {
                    // 销毁 Session
                    session_unset();
                    session_destroy();
                    // 跳转到登录页
                    header('Location: user/index.php?msg=forced_logout');
                    exit;
                }
            }
        } catch (PDOException $e) {
            // 数据库错误处理
            error_log("Token check failed: " . $e->getMessage());
        }
    }
}

function get_all_settings($pdo) {
    $stmt = $pdo->query("SELECT setting_key, setting_value FROM settings");
    $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    return $settings;
}

function anti_bot_check() {
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $bots = ['bot', 'spider', 'crawl', 'slurp', 'mediapartners-google'];
    foreach ($bots as $bot) {
        if (stripos($user_agent, $bot) !== false) {
            header('HTTP/1.1 403 Forbidden');
            die('Access Denied.');
        }
    }
}
?>
