<?php
// 页面头部文件
require_once __DIR__ . '/../config.php';

// 全局数据库连接
$db = getDB();

// 检查站点是否处于维护状态（管理员页面除外）
$isAdminPage = strpos($_SERVER['REQUEST_URI'] ?? '', '/admin/') !== false;
if (!$isAdminPage) {
    $stmt = $db->query("SELECT value FROM settings WHERE group_name = 'site' AND key_name = 'site_closed'");
    $closedRow = $stmt->fetch();
    if ($closedRow && $closedRow['value'] === '1') {
        // 站点维护中，重定向到维护页面
        header('Location: ' . SITE_URL . '/maintenance.php');
        exit;
    }
}

// 获取公众号配置（用于前端遮罩检测）
$wechatConfig = [];
$stmt = $db->query("SELECT key_name, value FROM settings WHERE group_name = 'wechat'");
foreach ($stmt->fetchAll() as $row) {
    $wechatConfig[$row['key_name']] = $row['value'];
}
$wechatEnabled = ($wechatConfig['wechat_enabled'] ?? '0') === '1';
$wechatForceFollow = ($wechatConfig['wechat_force_follow'] ?? '0') === '1';
$wechatQrcode = $wechatConfig['wechat_qrcode_url'] ?? '';
$wechatAppid = $wechatConfig['wechat_appid'] ?? '';

// 自动登录：确保始终有 user_id（如果公众号登录未启用则使用默认用户）
// 排除登录相关页面，避免重定向循环
$currentPage = basename($_SERVER['SCRIPT_NAME'] ?? '');
$loginPages = ['login.php', 'wechat-callback.php', 'maintenance.php'];

if (!isset($_SESSION['user_id'])) {
    if (!$wechatEnabled) {
        // 公众号登录未启用，使用默认自动登录
        $stmt = $db->query("SELECT id FROM users WHERE id = 1");
        $defaultUser = $stmt->fetch();
        if (!$defaultUser) {
            $db->exec("INSERT INTO users (id, username, password, real_name) VALUES (1, 'default', '', '默认用户')");
        }
        $_SESSION['user_id'] = 1;
    } else {
        // 公众号登录已启用，未登录用户必须先登录
        if (!in_array($currentPage, $loginPages)) {
            header('Location: ' . SITE_URL . '/pages/login.php');
            exit;
        }
        // 登录页自身不做重定向，仅标记为未登录状态
        $_SESSION['user_id'] = 0;
    }
} elseif ($_SESSION['user_id'] === 0 && $wechatEnabled) {
    // 已标记为未登录(user_id=0)，非登录页则跳转
    if (!in_array($currentPage, $loginPages)) {
        header('Location: ' . SITE_URL . '/pages/login.php');
        exit;
    }
}

// 检查用户封禁状态（兼容字段不存在的情况）
$hasBanColumns = false;
try {
    $colCheck = $db->query("SHOW COLUMNS FROM users LIKE 'is_banned'")->fetch();
    $hasBanColumns = !empty($colCheck);
} catch (Exception $e) {}

if ($hasBanColumns && isset($_SESSION['user_id']) && $_SESSION['user_id'] > 0) {
    $stmt = $db->prepare("SELECT is_banned, ban_reason, ban_expire_at FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $banRow = $stmt->fetch();
    if ($banRow && $banRow['is_banned']) {
        $now = date('Y-m-d H:i:s');
        $isExpired = false;
        if ($banRow['ban_expire_at'] && $banRow['ban_expire_at'] !== '9999-12-31 23:59:59' && $banRow['ban_expire_at'] < $now) {
            $isExpired = true;
            $stmt2 = $db->prepare("UPDATE users SET is_banned = 0, ban_reason = '', ban_expire_at = NULL WHERE id = ?");
            $stmt2->execute([$_SESSION['user_id']]);
        }
        if (!$isExpired) {
            $banReason = $banRow['ban_reason'] ?: '违反平台规定';
            $banExpire = $banRow['ban_expire_at'];
            if ($banExpire === '9999-12-31 23:59:59') $banExpire = '永久';
            ?>
            <!DOCTYPE html>
            <html lang="zh-CN">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
                <title>账号封禁 - <?php echo SITE_NAME; ?></title>
                <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css">
                <style>
                * { margin: 0; padding: 0; box-sizing: border-box; }
                body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #f9fafb; display: flex; align-items: center; justify-content: center; min-height: 100vh; }
                .ban-container { text-align: center; padding: 48px 32px; max-width: 400px; width: 90%; }
                .ban-icon { font-size: 72px; color: #ef4444; margin-bottom: 24px; }
                .ban-title { font-size: 22px; font-weight: 700; color: #1f2937; margin-bottom: 12px; }
                .ban-reason { font-size: 16px; color: #6b7280; line-height: 1.8; margin-bottom: 20px; background: white; border-radius: 12px; padding: 20px; border: 1px solid #e5e7eb; }
                .ban-expire { font-size: 14px; color: #9ca3af; margin-bottom: 32px; }
                .ban-contact { font-size: 13px; color: #9ca3af; }
                </style>
            </head>
            <body>
                <div class="ban-container">
                    <div class="ban-icon"><i class="fas fa-ban"></i></div>
                    <div class="ban-title">账号已被封禁</div>
                    <div class="ban-reason"><i class="fas fa-exclamation-circle" style="color:#ef4444;margin-right:6px;"></i>封禁原因：<?php echo htmlspecialchars($banReason); ?></div>
                    <div class="ban-expire">封禁到期时间：<?php echo htmlspecialchars($banExpire); ?></div>
                    <div class="ban-contact">如有疑问请联系管理员</div>
                </div>
            </body>
            </html>
            <?php
            exit;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title><?php echo isset($pageTitle) ? $pageTitle . ' - ' . SITE_NAME : SITE_NAME; ?></title>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/css/common.css?v=8">
    <?php if (isset($pageCss)): ?>
    <link rel="stylesheet" href="<?php echo SITE_URL . $pageCss; ?>?v=8">
    <?php endif; ?>
</head>
<body>
<?php
// 公众号强关遮罩：如果启用了强关模式，且用户未关注公众号，则显示遮罩
$hasFollowColumn = false;
try {
    $colCheck2 = $db->query("SHOW COLUMNS FROM users LIKE 'is_follow_wechat'")->fetch();
    $hasFollowColumn = !empty($colCheck2);
} catch (Exception $e) {}

if ($wechatEnabled && $wechatForceFollow && $hasFollowColumn && isset($_SESSION['user_id']) && $_SESSION['user_id'] > 0) {
    // 检查用户是否已关注
    $stmt = $db->prepare("SELECT is_follow_wechat FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $followRow = $stmt->fetch();
    if ($followRow && !$followRow['is_follow_wechat']) {
        // 未关注，显示遮罩
        ?>
        <div id="wechatFollowMask" style="position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.6);z-index:9999;display:flex;align-items:center;justify-content:center;">
            <div style="background:white;border-radius:16px;padding:32px 24px;text-align:center;max-width:320px;width:90%;">
                <div style="font-size:18px;font-weight:600;color:#1f2937;margin-bottom:12px;">请关注公众号</div>
                <div style="font-size:14px;color:#6b7280;margin-bottom:24px;">为了更好的服务体验，请先关注我们的公众号</div>
                <?php if ($wechatQrcode): ?>
                <div style="width:200px;height:200px;margin:0 auto 16px;background:#f3f4f6;border-radius:8px;overflow:hidden;">
                    <img src="<?php echo htmlspecialchars($wechatQrcode); ?>" style="width:100%;height:100%;object-fit:contain;">
                </div>
                <?php endif; ?>
                <div style="font-size:12px;color:#9ca3af;">长按识别二维码关注公众号</div>
            </div>
        </div>
        <?php
    }
}
?>
