<?php
/**
 * 授权检测拦截器
 * 用于在管理后台实时检测授权状态
 */

// 防止直接访问
if (!defined('ROOT')) {
    die('Access denied');
}

/**
 * 实时检测授权状态
 * 如果授权无效，显示失败页面并退出
 */
function check_auth_and_block() {
    // 获取当前域名
    $domain = $_SERVER['HTTP_HOST'] ?? '';
    
    if (empty($domain)) {
        show_auth_failed_page('无法获取当前域名');
    }
    
    // 调用授权验证API
    $api_url = 'https://sqz.dadxb.cn/api/verify.php';
    
    $params = [
        'domain' => $domain
    ];
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $api_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($params),
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_TIMEOUT => 10,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    // 如果服务器错误（500），暂时放行
    if ($httpCode >= 500) {
        // 服务器错误时不拦截，避免影响正常使用
        return true;
    }
    
    // 如果HTTP状态码不是200，显示错误
    if ($httpCode != 200) {
        show_auth_failed_page('HTTP错误: ' . $httpCode, $domain);
    }
    
    // 解析响应
    $data = json_decode($response, true);
    
    if (!$data) {
        show_auth_failed_page('授权服务器响应异常', $domain);
    }
    
    // 检查授权状态
    if (!isset($data['data']['is_valid']) || !$data['data']['is_valid']) {
        $reason = $data['data']['reason'] ?? 'unknown';
        $message = $data['message'] ?? '授权无效';
        
        // 根据原因显示不同的错误信息
        switch ($reason) {
            case 'not_found':
                $message = '当前域名未授权';
                break;
            case 'disabled':
                $message = '授权已被禁用';
                break;
            case 'not_activated':
                $message = '授权未激活';
                break;
            case 'expired':
                $message = '授权已过期';
                break;
        }
        
        show_auth_failed_page($message, $domain, $reason);
    }
    
    // 授权有效，继续执行
    return true;
}

/**
 * 显示授权失败页面
 */
function show_auth_failed_page($error_msg = '授权验证失败', $domain = '', $reason = 'unknown') {
    // 退出登录session
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    session_destroy();
    
    // 清除cookie
    setcookie('admin_sid', '', time() - 3600, '/');
    setcookie('admin_uid', '', time() - 3600, '/');
    
    ?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>授权验证失败</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
            min-height: 100vh;
        }
        .auth-card {
            animation: fadeInUp 0.5s ease-out;
        }
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        .warning-icon {
            animation: shake 0.5s ease-in-out;
        }
        @keyframes shake {
            0%, 100% { transform: rotate(0deg); }
            25% { transform: rotate(-10deg); }
            75% { transform: rotate(10deg); }
        }
    </style>
</head>
<body class="min-h-screen flex items-center justify-center p-4">
    <div class="w-full max-w-md auth-card">
        <div class="bg-white rounded-2xl shadow-2xl p-8 text-center">
            <!-- 警告图标 -->
            <div class="inline-flex items-center justify-center w-16 h-16 bg-red-100 rounded-full mb-4 warning-icon">
                <i class="fas fa-exclamation-triangle text-red-500 text-3xl"></i>
            </div>
            
            <!-- 标题 -->
            <h1 class="text-2xl font-bold text-gray-800 mb-2">授权验证失败</h1>
            <p class="text-gray-500 text-sm mb-6"><?php echo htmlspecialchars($error_msg); ?></p>
            
            <!-- 信息展示 -->
            <?php if ($domain): ?>
            <div class="bg-gray-50 rounded-lg p-4 mb-6 text-left">
                <div class="flex justify-between items-center py-2 border-b border-gray-200">
                    <span class="text-gray-500">当前域名</span>
                    <span class="text-gray-800 font-medium"><?php echo htmlspecialchars($domain); ?></span>
                </div>
                <div class="flex justify-between items-center py-2">
                    <span class="text-gray-500">授权状态</span>
                    <span class="bg-red-500 text-white text-xs px-3 py-1 rounded-full">未授权</span>
                </div>
            </div>
            <?php endif; ?>
            
            <!-- 授权说明 -->
            <div class="bg-blue-50 rounded-lg p-4 mb-6 text-left">
                <p class="text-blue-600 font-medium mb-2">授权说明:</p>
                <p class="text-blue-500 text-sm">请联系管理员获取授权密钥，或访问授权平台进行授权。授权后即可正常使用后台功能。</p>
            </div>
            
            <!-- 按钮 -->
            <div class="flex flex-col gap-3">
                <a href="https://51mpz.shop" target="_blank" class="w-full inline-flex items-center justify-center gap-2 px-6 py-3 bg-gradient-to-r from-blue-500 to-purple-500 text-white rounded-lg font-medium hover:from-blue-600 hover:to-purple-600 transition-all shadow-lg">
                    <i class="fas fa-shopping-cart"></i>
                    前往购买授权
                </a>
                <a href="./login.php" class="w-full inline-flex items-center justify-center gap-2 px-6 py-3 bg-gray-100 text-gray-700 rounded-lg font-medium hover:bg-gray-200 transition-all">
                    <i class="fas fa-sign-out-alt"></i>
                    退出登录
                </a>
            </div>
        </div>
    </div>
</body>
</html>
    <?php
    exit;
}
