<?php
/**
 * 2026企业CMS - 认证函数库
 */

// 启动SESSION
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

// 管理员登录
function admin_login($username, $password) {
    $admin = db_query_one("SELECT * FROM `admins` WHERE `username` = ? AND `status` = 1", [$username]);
    
    if ($admin && password_verify($password, $admin['password'])) {
        $_SESSION['admin_id'] = $admin['id'];
        $_SESSION['admin_username'] = $admin['username'];
        $_SESSION['admin_role'] = $admin['role'];
        $_SESSION['admin_realname'] = $admin['realname'];
        
        // 更新最后登录信息
        db_exec(
            "UPDATE `admins` SET `last_login` = NOW(), `last_ip` = ? WHERE `id` = ?",
            [$_SERVER['REMOTE_ADDR'] ?? '', $admin['id']]
        );
        
        add_log('login', 'auth', '管理员登录: ' . $username);
        return true;
    }
    return false;
}

// 检查管理员是否登录
function admin_check_login() {
    if (!isset($_SESSION['admin_id'])) {
        header('Location: /admin/login.php');
        exit;
    }
}

// 管理员退出
function admin_logout() {
    add_log('logout', 'auth', '管理员退出: ' . ($_SESSION['admin_username'] ?? ''));
    session_destroy();
    header('Location: /admin/login.php');
    exit;
}

// 获取当前管理员信息
function current_admin() {
    if (!isset($_SESSION['admin_id'])) return null;
    return db_query_one("SELECT * FROM `admins` WHERE `id` = ?", [$_SESSION['admin_id']]);
}

// 检查权限
function check_permission($requiredRole = 'editor') {
    $roleLevel = ['editor' => 1, 'admin' => 2, 'superadmin' => 3];
    $currentLevel = $roleLevel[$_SESSION['admin_role'] ?? 'editor'] ?? 1;
    $requiredLevel = $roleLevel[$requiredRole] ?? 1;
    
    if ($currentLevel < $requiredLevel) {
        echo '<div class="alert alert-danger">权限不足！</div>';
        exit;
    }
}

// 生成CSRF Token
function csrf_token() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

// 验证CSRF Token
function csrf_verify($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}
