<?php
/**
 * 万能授权验证代码 + 原程序内容
 */

// ========== 处理授权码保存请求（必须在任何输出之前） ==========
if (isset($_GET['save_license']) && isset($_POST['license_code'])) {
    $license_file = dirname(__FILE__) . '/.license_cache';
    $code = trim($_POST['license_code']);
    $result = file_put_contents($license_file, $code);
    header('Content-Type: application/json');
    if ($result !== false) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'error' => '无法写入授权文件，请检查目录权限']);
    }
    exit;
}

// ========== 配置区域 ==========
$api_url = 'https://auth.lhwks.top/api/verify.php';  // 您的授权服务端地址
$app_name = '麟泓授权系统所授权的应用';                          // 您的应用名称
$app_key = 'your_app_key_here';  // ⭐ 重要：修改为您的应用标识（与后台设置一致）
// =============================

// 获取存储的授权码
$license_file = dirname(__FILE__) . '/.license_cache';
$license_code = '';

if (file_exists($license_file)) {
    $license_code = trim(file_get_contents($license_file));
}

// 验证授权函数（带应用标识）
function verifyLicense($api_url, $license_code, $domain, $app_key) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'license_code' => $license_code,
        'domain' => $domain,
        'app_key' => $app_key   // ⭐ 传递应用标识
    ]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    if ($response) {
        return json_decode($response, true);
    }
    return null;
}

$domain = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? 'localhost';

// 验证授权
$need_auth = true;

if (!empty($license_code)) {
    $auth_result = verifyLicense($api_url, $license_code, $domain, $app_key);
    if ($auth_result && isset($auth_result['code']) && $auth_result['code'] == 200) {
        $need_auth = false;
    }
}

// 如果需要授权，显示弹窗
if ($need_auth) {
    ?>
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>授权验证 - 麟泓网科室</title>
            <link rel="icon" href="//auth.lhwks.top/assets/uploads/favicon.ico"> 
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            
            body {
                font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
                background: radial-gradient(circle at 20% 50%, rgba(102, 126, 234, 0.15), rgba(118, 75, 162, 0.15)),
                            linear-gradient(135deg, #0f172a 0%, #1e1b4b 50%, #2d1b69 100%);
                min-height: 100vh;
                display: flex;
                align-items: center;
                justify-content: center;
                padding: 20px;
                position: relative;
                overflow: hidden;
            }
            
            /* 动态背景粒子效果 */
            body::before {
                content: '';
                position: absolute;
                width: 200%;
                height: 200%;
                background: radial-gradient(circle, rgba(255,255,255,0.03) 1px, transparent 1px);
                background-size: 40px 40px;
                animation: moveParticles 60s linear infinite;
                pointer-events: none;
            }
            
            @keyframes moveParticles {
                0% { transform: translate(0, 0); }
                100% { transform: translate(-20%, -20%); }
            }
            
            /* 光晕效果 */
            body::after {
                content: '';
                position: absolute;
                width: 80%;
                height: 80%;
                background: radial-gradient(circle, rgba(99, 102, 241, 0.2), transparent 70%);
                top: 10%;
                left: 10%;
                pointer-events: none;
            }
            
            .auth-modal {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0, 0, 0, 0.6);
                backdrop-filter: blur(12px);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 99999;
                animation: fadeIn 0.4s ease-out;
            }
            
            @keyframes fadeIn {
                from {
                    opacity: 0;
                    backdrop-filter: blur(0px);
                }
                to {
                    opacity: 1;
                    backdrop-filter: blur(12px);
                }
            }
            
            .auth-container {
                background: rgba(255, 255, 255, 0.98);
                border-radius: 48px;
                box-shadow: 0 40px 80px -20px rgba(0, 0, 0, 0.4), 0 0 0 1px rgba(255, 255, 255, 0.1);
                width: 100%;
                max-width: 480px;
                overflow: hidden;
                animation: slideUp 0.5s cubic-bezier(0.2, 0.9, 0.4, 1.1);
                transform-origin: center;
            }
            
            @keyframes slideUp {
                from {
                    opacity: 0;
                    transform: translateY(40px) scale(0.96);
                }
                to {
                    opacity: 1;
                    transform: translateY(0) scale(1);
                }
            }
            
            .auth-header {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
                padding: 40px 32px;
                text-align: center;
                position: relative;
                overflow: hidden;
            }
            
            .auth-header::before {
                content: '';
                position: absolute;
                top: -50%;
                right: -50%;
                width: 200%;
                height: 200%;
                background: radial-gradient(circle, rgba(255,255,255,0.2), transparent 70%);
                animation: rotateGlow 12s linear infinite;
            }
            
            @keyframes rotateGlow {
                from { transform: rotate(0deg); }
                to { transform: rotate(360deg); }
            }
            
            .auth-header h2 {
                color: white;
                font-size: 32px;
                margin-bottom: 12px;
                font-weight: 700;
                letter-spacing: -0.5px;
                position: relative;
                z-index: 1;
            }
            
            .auth-header p {
                color: rgba(255, 255, 255, 0.9);
                font-size: 15px;
                position: relative;
                z-index: 1;
                font-weight: 400;
            }
            
            .auth-header .icon-lock {
                font-size: 48px;
                margin-bottom: 16px;
                display: inline-block;
                filter: drop-shadow(0 4px 8px rgba(0,0,0,0.2));
                position: relative;
                z-index: 1;
            }
            
            .auth-body {
                padding: 40px 32px 32px;
            }
            
            .form-group {
                margin-bottom: 28px;
            }
            
            .form-group label {
                display: block;
                margin-bottom: 10px;
                font-weight: 600;
                font-size: 14px;
                color: #1f2937;
                letter-spacing: 0.3px;
            }
            
            .form-group input {
                width: 100%;
                padding: 14px 18px;
                border: 2px solid #e5e7eb;
                border-radius: 24px;
                font-size: 15px;
                transition: all 0.25s ease;
                outline: none;
                background: #fafbfc;
                font-family: 'SF Mono', 'Fira Code', monospace;
                letter-spacing: 0.5px;
            }
            
            .form-group input:focus {
                border-color: #667eea;
                box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.15);
                background: white;
            }
            
            .form-group input::placeholder {
                color: #9ca3af;
                font-family: monospace;
                font-size: 13px;
            }
            
            .btn-auth {
                width: 100%;
                padding: 14px;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                border: none;
                border-radius: 40px;
                font-size: 16px;
                font-weight: 600;
                cursor: pointer;
                transition: all 0.3s ease;
                position: relative;
                overflow: hidden;
                box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
            }
            
            .btn-auth::before {
                content: '';
                position: absolute;
                top: 0;
                left: -100%;
                width: 100%;
                height: 100%;
                background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);
                transition: left 0.5s ease;
            }
            
            .btn-auth:hover {
                transform: translateY(-2px);
                box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
            }
            
            .btn-auth:hover::before {
                left: 100%;
            }
            
            .btn-auth:active {
                transform: translateY(1px);
            }
            
            .error-message {
                background: linear-gradient(135deg, #fee2e2 0%, #ffd6d6 100%);
                color: #dc2626;
                padding: 14px 18px;
                border-radius: 20px;
                margin-bottom: 24px;
                font-size: 14px;
                text-align: center;
                border-left: 4px solid #ef4444;
                font-weight: 500;
                animation: shake 0.4s ease;
            }
            
            @keyframes shake {
                0%, 100% { transform: translateX(0); }
                25% { transform: translateX(-5px); }
                75% { transform: translateX(5px); }
            }
            
            .success-message {
                background: linear-gradient(135deg, #d1fae5 0%, #bef5e0 100%);
                color: #059669;
                padding: 14px 18px;
                border-radius: 20px;
                margin-bottom: 24px;
                font-size: 14px;
                text-align: center;
                border-left: 4px solid #10b981;
                font-weight: 500;
                animation: pulse 0.5s ease;
            }
            
            @keyframes pulse {
                0%, 100% { transform: scale(1); }
                50% { transform: scale(1.02); }
            }
            
            .info-text {
                text-align: center;
                margin-top: 28px;
                padding-top: 24px;
                border-top: 1px solid #eef2f6;
            }
            
            .info-text p {
                font-size: 12px;
                color: #9ca3af;
                margin: 6px 0;
            }
            
            .loading {
                display: inline-block;
                width: 18px;
                height: 18px;
                border: 2px solid rgba(255,255,255,0.3);
                border-radius: 50%;
                border-top-color: white;
                animation: spin 0.6s linear infinite;
                margin-right: 8px;
                vertical-align: middle;
            }
            
            @keyframes spin {
                to { transform: rotate(360deg); }
            }
            
            /* 装饰元素 */
            .auth-footer-note {
                background: #f9fafb;
                margin: 20px -32px -32px;
                padding: 20px 32px;
                text-align: center;
                border-top: 1px solid #eef2f6;
            }
            
            .auth-footer-note p {
                font-size: 12px;
                color: #6b7280;
            }
            
            @media (max-width: 480px) {
                .auth-container {
                    border-radius: 32px;
                }
                .auth-header {
                    padding: 32px 24px;
                }
                .auth-header h2 {
                    font-size: 26px;
                }
                .auth-body {
                    padding: 32px 24px;
                }
                .form-group input {
                    padding: 12px 16px;
                }
            }
        </style>
    </head>
    <body>
        <div class="auth-modal">
            <div class="auth-container">
                <div class="auth-header">
                    <div class="icon-lock">🔐</div>
                    <h2>授权验证</h2>
                    <p>请输入授权码以继续使用</p>
                </div>
                <div class="auth-body">
                    <div id="messageArea"></div>
                    <form id="authForm">
                        <div class="form-group">
                            <label>授权码</label>
                            <input type="text" id="licenseCode" placeholder="例如：7FD18BE974F2698A" required autocomplete="off">
                        </div>
                        <button type="submit" class="btn-auth" id="submitBtn">
                            <span>验证授权</span>
                        </button>
                    </form>
                    <div class="info-text">
                        <p>💡 购买授权码后在此输入，即可永久使用</p>
                        <p>📞 如有问题请联系客服</p>
                        <div class="auth-footer-note">
                    <p>© <?php echo date('Y'); ?> 麟泓授权系统 · 安全 · 稳定 · 高效</p>
                </div>
                    </div>
                </div>
                <!--<div class="auth-footer-note">-->
                <!--    <p>© <?php echo date('Y'); ?> 麟泓授权系统 · 安全 · 稳定 · 高效</p>-->
                <!--</div>-->
            </div>
        </div>
        <script>
            const apiUrl = '<?php echo $api_url; ?>';
            const domain = '<?php echo $domain; ?>';
            const appKey = '<?php echo $app_key; ?>';  // ⭐ 添加应用标识
            
            document.getElementById('authForm').addEventListener('submit', async function(e) {
                e.preventDefault();
                const licenseCode = document.getElementById('licenseCode').value.trim().toUpperCase();
                if (!licenseCode) {
                    showMessage('请输入授权码', 'error');
                    return;
                }
                
                // 简单格式验证
                if (!/^[A-F0-9]{16}$/.test(licenseCode)) {
                    showMessage('授权码格式不正确，应为16位大写字母和数字组合', 'error');
                    return;
                }
                
                const submitBtn = document.getElementById('submitBtn');
                const originalText = submitBtn.innerHTML;
                submitBtn.innerHTML = '<span class="loading"></span> 验证中...';
                submitBtn.disabled = true;
                
                try {
                    // ⭐ 验证请求中增加 app_key 参数
                    const response = await fetch(apiUrl, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        body: 'license_code=' + encodeURIComponent(licenseCode) + 
                               '&domain=' + encodeURIComponent(domain) + 
                               '&app_key=' + encodeURIComponent(appKey)
                    });
                    const result = await response.json();
                    
                    if (result.code === 200) {
                        const saveResponse = await fetch('?save_license=1', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                            body: 'license_code=' + encodeURIComponent(licenseCode)
                        });
                        const saveResult = await saveResponse.json();
                        
                        if (saveResult.success) {
                            showMessage('✓ 授权成功！正在加载程序...', 'success');
                            setTimeout(() => window.location.reload(), 1500);
                        } else {
                            showMessage('保存失败：' + (saveResult.error || '请检查目录权限'), 'error');
                            submitBtn.innerHTML = originalText;
                            submitBtn.disabled = false;
                        }
                    } else {
                        let errorMsg = result.message || '授权验证失败';
                        if (result.code === 403) errorMsg = '❌ ' + errorMsg;
                        if (result.code === 404) errorMsg = '❌ 授权码不存在';
                        showMessage(errorMsg, 'error');
                        submitBtn.innerHTML = originalText;
                        submitBtn.disabled = false;
                    }
                } catch (error) {
                    console.error('错误:', error);
                    showMessage('网络错误，请检查网络连接后重试', 'error');
                    submitBtn.innerHTML = originalText;
                    submitBtn.disabled = false;
                }
            });
            
            function showMessage(msg, type) {
                const area = document.getElementById('messageArea');
                area.innerHTML = '<div class="' + (type === 'error' ? 'error-message' : 'success-message') + '">' + msg + '</div>';
                setTimeout(() => {
                    const el = area.firstChild;
                    if (el) {
                        el.style.opacity = '0';
                        el.style.transform = 'translateY(-10px)';
                        setTimeout(() => {
                            if (area.firstChild) area.removeChild(area.firstChild);
                        }, 300);
                    }
                }, 3000);
            }
            
            // 自动大写输入
            document.getElementById('licenseCode').addEventListener('input', function(e) {
                this.value = this.value.toUpperCase();
            });
        </script>
    </body>
    </html>
    <?php
    exit;
}

// 验证通过，定义授权常量
define('LICENSE_CODE', $license_code);
define('LICENSE_VALID', true);