<?php
/**
 * 授权检测文件
 * 用于检测系统授权状态
 */

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

/**
 * 检测授权状态
 * 返回: true=已授权, false=未授权
 */
function check_system_auth() {
    // 调用授权验证
    if (function_exists('verify_auth_status')) {
        $result = verify_auth_status();
        return isset($result['code']) && $result['code'] === 1;
    }
    
    // 如果函数不存在，尝试直接调用API
    $auth_config = include(ROOT . 'includes/Auth.php');
    $authcode = $auth_config['authcode'] ?? '';
    $domain = $_SERVER['HTTP_HOST'] ?? '';
    
    if (empty($authcode)) {
        return false;
    }
    
    $params = [
        'card_key' => $authcode,
        'domain' => $domain
    ];
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => 'https://sqz.dadxb.cn/api/verify.php',
        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);
    curl_close($ch);
    
    // 如果服务器错误（500），暂时放行
    if ($httpCode >= 500) {
        return true; // 服务器错误时暂时认为已授权
    }
    
    if ($httpCode != 200) {
        return false;
    }
    
    $data = json_decode($response, true);
    
    return isset($data['success']) && $data['success'] && isset($data['data']['is_valid']) && $data['data']['is_valid'];
}

/**
 * 获取授权信息
 */
function get_auth_info() {
    if (function_exists('verify_auth_status')) {
        return verify_auth_status();
    }
    
    $auth_config = include(ROOT . 'includes/Auth.php');
    $authcode = $auth_config['authcode'] ?? '';
    $domain = $_SERVER['HTTP_HOST'] ?? '';
    
    if (empty($authcode)) {
        return ['code' => -1, 'msg' => '未配置授权码'];
    }
    
    $params = [
        'card_key' => $authcode,
        'domain' => $domain
    ];
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => 'https://sqz.dadxb.cn/api/verify.php',
        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);
    
    if ($error) {
        return ['code' => -1, 'msg' => '授权服务器连接失败: ' . $error];
    }
    
    if ($httpCode >= 500) {
        return ['code' => -2, 'msg' => '授权服务器暂时不可用，请稍后重试'];
    }
    
    if ($httpCode != 200) {
        return ['code' => -1, 'msg' => 'HTTP错误: ' . $httpCode];
    }
    
    $data = json_decode($response, true);
    
    if (isset($data['success']) && $data['success'] && isset($data['data']['is_valid']) && $data['data']['is_valid']) {
        return [
            'code' => 1,
            'msg' => $data['message'] ?? '授权有效',
            'data' => $data['data']
        ];
    }
    
    return [
        'code' => -1,
        'msg' => $data['message'] ?? '授权无效',
        'data' => $data['data'] ?? []
    ];
}

/**
 * 显示授权失败页面
 */
function show_auth_failed_page($error_msg = '授权验证失败') {
    $domain = $_SERVER['HTTP_HOST'] ?? '';
    
    // 退出登录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>
    <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);
            }
        }
    </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">
                <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>
            
            <!-- 信息展示 -->
            <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>
            
            <!-- 授权说明 -->
            <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>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
</body>
</html>
    <?php
    exit;
}
