<?php
require_once __DIR__ . '/../MPHX/common.php';
require_once __DIR__ . '/../MPHX/AuthManager.php';

if (!is_admin_login()) {
    header('Location: /admin/login.php');
    exit;
}

$admin = is_admin_login();

// 获取授权信息 - 强制从远程获取最新状态
$auth_info = null;
$auth_error = '';
$auth_status = 'unknown';

try {
    $authManager = new AuthManager($DB);
    
    // 获取token（强制验证模式，会到服务器验证token有效性）
    $token_result = $authManager->getToken(true);
    
    if ($token_result['code'] == 200) {
        $token = $token_result['data']['token'];
        
        // 查询授权信息获取实时状态
        $auth_info_result = $authManager->getAuthInfo($token);
        
        if ($auth_info_result['code'] == 200) {
            // 从授权信息响应中获取数据（注意：auth_info.php返回的数据在auth子数组中）
            $auth_data = $auth_info_result['data']['auth'] ?? [];
            $auth_info = [
                'expire_time' => $auth_data['expire_time'] ?? $token_result['data']['expire_time'],
                'is_trial' => $auth_data['is_trial'] ?? $token_result['data']['is_trial'] ?? true,
                'remain_seconds' => $auth_data['remain_seconds'] ?? 0,
                'device_id' => $auth_info_result['data']['device']['id'] ?? '',
                'software_id' => $auth_info_result['data']['software']['id'] ?? ''
            ];
            $auth_status = 'active';
        } else {
            // 查询失败，使用token中的基本信息
            $auth_info = [
                'expire_time' => $token_result['data']['expire_time'],
                'is_trial' => $token_result['data']['is_trial'],
                'remain_seconds' => 0,
                'device_id' => '',
                'software_id' => ''
            ];
            $auth_status = 'active';
        }
    } elseif ($token_result['code'] == 403 && isset($token_result['data']['need_auth'])) {
        $auth_status = 'need_auth';
        $auth_error = $token_result['message'];
    } else {
        $auth_status = 'error';
        $auth_error = $token_result['message'] ?? '获取授权信息失败';
    }
} catch (Exception $e) {
    $auth_status = 'error';
    $auth_error = $e->getMessage();
}

// 计算剩余时间
$remain_days = 0;
$remain_hours = 0;
$remain_minutes = 0;
$remain_seconds_total = 0;
if ($auth_info && isset($auth_info['expire_time'])) {
    $expire_timestamp = strtotime($auth_info['expire_time']);
    $now = time();
    $remain_seconds_total = max(0, $expire_timestamp - $now);
    // 优先使用服务器返回的remain_seconds
    if (isset($auth_info['remain_seconds']) && $auth_info['remain_seconds'] > 0) {
        $remain_seconds_total = $auth_info['remain_seconds'];
    }
    $remain_days = floor($remain_seconds_total / 86400);
    $remain_hours = floor(($remain_seconds_total % 86400) / 3600);
    $remain_minutes = floor(($remain_seconds_total % 3600) / 60);
}

$current_domain = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? '127.0.0.1';


?>
<!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>授权配置 - 宝塔主机管理系统</title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/css/all.min.css">
    <link rel="stylesheet" href="css/style.css?v=2026040501">
    <style>
        /* 倒计时移动端适配 */
        @media (max-width: 768px) {
            .countdown-box {
                width: 55px !important;
                height: 55px !important;
                font-size: 22px !important;
            }
            .countdown-separator {
                font-size: 18px !important;
            }
            .countdown-container {
                gap: 8px !important;
                padding: 15px 0 !important;
            }
            /* 激活授权区域移动端适配 */
            .auth-header {
                flex-direction: column !important;
                align-items: flex-start !important;
                gap: 10px !important;
            }
            .auth-header .btn {
                width: 100% !important;
            }
            .auth-input-row {
                flex-direction: column !important;
                gap: 10px !important;
            }
            .auth-input-row input {
                width: 100% !important;
            }
            .auth-input-row .btn {
                width: 100% !important;
            }
            .auth-button-row {
                flex-direction: column !important;
                gap: 10px !important;
            }
            .auth-button-row .btn {
                width: 100% !important;
            }
        }
    </style>
</head>
<body>
    <div class="content-area">
        
        <!-- 授权状态卡片 -->
        <?php if ($auth_status == 'active'): ?>
            <?php if ($auth_info['is_trial']): ?>
            <div class="card" style="border-left: 4px solid #188038;">
                <div style="display: flex; align-items: center; gap: 16px;">
                    <div style="width: 60px; height: 60px; background: #e6f4ea; border-radius: 6px; display: flex; align-items: center; justify-content: center;">
                        <i class="fas fa-clock" style="font-size: 28px; color: #188038;"></i>
                    </div>
                    <div style="flex: 1;">
                        <h3 style="margin: 0 0 4px 0; font-size: 18px; color: #202124;">试用授权</h3>
                        <p style="margin: 0; color: #5f6368; font-size: 13px;">当前正在使用试用授权，功能完整可用</p>
                    </div>
                    <span class="badge badge-success">试用中</span>
                </div>
            </div>
            <?php else: ?>
            <div class="card" style="border-left: 4px solid #188038;">
                <div style="display: flex; align-items: center; gap: 16px;">
                    <div style="width: 60px; height: 60px; background: #e6f4ea; border-radius: 6px; display: flex; align-items: center; justify-content: center;">
                        <i class="fas fa-check-circle" style="font-size: 28px; color: #188038;"></i>
                    </div>
                    <div style="flex: 1;">
                        <h3 style="margin: 0 0 4px 0; font-size: 18px; color: #202124;">正式授权</h3>
                        <p style="margin: 0; color: #5f6368; font-size: 13px;">授权已激活，享受完整服务</p>
                    </div>
                    <span class="badge badge-success">已激活</span>
                </div>
            </div>
            <?php endif; ?>
            
            <!-- 倒计时 -->
            <div class="card">
                <h3><i class="fas fa-hourglass-half"></i> 授权到期倒计时</h3>
                <div class="countdown-container" style="display: flex; justify-content: center; align-items: center; gap: 16px; padding: 20px 0;">
                    <div style="text-align: center;">
                        <div class="countdown-box" style="width: 80px; height: 80px; background: #f8f9fa; border-radius: 6px; display: flex; align-items: center; justify-content: center; font-size: 32px; font-weight: 600; color: #202124;" id="days"><?php echo $remain_days; ?></div>
                        <div style="margin-top: 8px; color: #5f6368; font-size: 12px;">天</div>
                    </div>
                    <div class="countdown-separator" style="font-size: 24px; color: #dadce0; font-weight: 300;">:</div>
                    <div style="text-align: center;">
                        <div class="countdown-box" style="width: 80px; height: 80px; background: #f8f9fa; border-radius: 6px; display: flex; align-items: center; justify-content: center; font-size: 32px; font-weight: 600; color: #202124;" id="hours"><?php echo sprintf('%02d', $remain_hours); ?></div>
                        <div style="margin-top: 8px; color: #5f6368; font-size: 12px;">时</div>
                    </div>
                    <div class="countdown-separator" style="font-size: 24px; color: #dadce0; font-weight: 300;">:</div>
                    <div style="text-align: center;">
                        <div class="countdown-box" style="width: 80px; height: 80px; background: #f8f9fa; border-radius: 6px; display: flex; align-items: center; justify-content: center; font-size: 32px; font-weight: 600; color: #202124;" id="minutes"><?php echo sprintf('%02d', $remain_minutes); ?></div>
                        <div style="margin-top: 8px; color: #5f6368; font-size: 12px;">分</div>
                    </div>
                    <div class="countdown-separator" style="font-size: 24px; color: #dadce0; font-weight: 300;">:</div>
                    <div style="text-align: center;">
                        <div class="countdown-box" style="width: 80px; height: 80px; background: #f8f9fa; border-radius: 6px; display: flex; align-items: center; justify-content: center; font-size: 32px; font-weight: 600; color: #202124;" id="seconds">00</div>
                        <div style="margin-top: 8px; color: #5f6368; font-size: 12px;">秒</div>
                    </div>
                </div>
                <div style="text-align: center; color: #5f6368; font-size: 13px;">
                    到期时间：<strong style="color: #202124;"><?php echo $auth_info['expire_time']; ?></strong>
                </div>
            </div>
            
            <!-- 授权信息 -->
            <div class="card">
                <h3><i class="fas fa-info-circle"></i> 授权信息</h3>
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 16px;">
                    <div style="padding: 12px; background: #f8f9fa; border-radius: 4px;">
                        <div style="color: #5f6368; font-size: 12px; margin-bottom: 4px;"><i class="fas fa-globe" style="margin-right: 6px;"></i>当前域名</div>
                        <div style="color: #202124; font-weight: 500;"><?php echo htmlspecialchars($current_domain); ?></div>
                    </div>
                    <div style="padding: 12px; background: #f8f9fa; border-radius: 4px;">
                        <div style="color: #5f6368; font-size: 12px; margin-bottom: 4px;"><i class="fas fa-tag" style="margin-right: 6px;"></i>授权类型</div>
                        <div>
                            <?php if ($auth_info['is_trial']): ?>
                                <span class="badge badge-success">试用授权</span>
                            <?php else: ?>
                                <span class="badge badge-success">正式授权</span>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php if (isset($auth_info['device_id']) && $auth_info['device_id']): ?>
                    <div style="padding: 12px; background: #f8f9fa; border-radius: 4px; grid-column: span 2;">
                        <div style="color: #5f6368; font-size: 12px; margin-bottom: 4px;"><i class="fas fa-server" style="margin-right: 6px;"></i>设备ID</div>
                        <div style="color: #202124; font-family: monospace; font-size: 12px;"><?php echo $auth_info['device_id']; ?></div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            
        <?php elseif ($auth_status == 'need_auth'): ?>
            <div class="card" style="border-left: 4px solid #1a73e8;">
                <div style="display: flex; align-items: center; gap: 16px;">
                    <div style="width: 60px; height: 60px; background: #e8f0fe; border-radius: 6px; display: flex; align-items: center; justify-content: center;">
                        <i class="fas fa-exclamation-circle" style="font-size: 28px; color: #1a73e8;"></i>
                    </div>
                    <div style="flex: 1;">
                        <h3 style="margin: 0 0 4px 0; font-size: 18px; color: #202124;">需要授权</h3>
                        <p style="margin: 0; color: #5f6368; font-size: 13px;"><?php echo htmlspecialchars($auth_error); ?></p>
                    </div>
                </div>
            </div>
        <?php else: ?>
            <div class="card" style="border-left: 4px solid #d93025;">
                <div style="display: flex; align-items: center; gap: 16px;">
                    <div style="width: 60px; height: 60px; background: #fce8e6; border-radius: 6px; display: flex; align-items: center; justify-content: center;">
                        <i class="fas fa-times-circle" style="font-size: 28px; color: #d93025;"></i>
                    </div>
                    <div style="flex: 1;">
                        <h3 style="margin: 0 0 4px 0; font-size: 18px; color: #202124;">授权异常</h3>
                        <p style="margin: 0; color: #5f6368; font-size: 13px;"><?php echo htmlspecialchars($auth_error); ?></p>
                    </div>
                </div>
            </div>
        <?php endif; ?>
        
        <!-- 激活授权 -->
        <div class="card">
            <div class="auth-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
                <h3 style="margin: 0;"><i class="fas fa-key"></i> 激活授权</h3>
                <a href="https://plus.a116.vip/shop/" target="_blank" class="btn btn-success">
                    <i class="fas fa-shopping-cart"></i> 购买授权
                </a>
            </div>
            <p style="color: #5f6368; font-size: 13px; margin-bottom: 16px;">如果您购买了正式授权，请在下方输入授权码进行激活</p>
            <div class="auth-input-row" style="display: flex; gap: 10px; margin-bottom: 10px;">
                <input type="text" id="auth_code" class="form-control" placeholder="请输入授权码，例如：AUTH_xxxxxxxx" style="flex: 1;">
                <button type="button" class="btn btn-primary" onclick="activateAuth(this)" style="white-space: nowrap;">
                    <i class="fas fa-check"></i> 激活
                </button>
            </div>
            <div class="auth-button-row" style="display: flex; gap: 10px;">
                <button type="button" class="btn btn-primary" onclick="reapplyAuth(this)" style="flex: 1;">
                    <i class="fas fa-redo"></i> 激活试用
                </button>
                <button type="button" class="btn btn-info" onclick="queryDomainAuth(this)" style="flex: 1;">
                    <i class="fas fa-search"></i> 查询域名授权状态
                </button>
            </div>
        </div>
        
        <!-- 刷新授权 -->
        <div class="card">
            <h3><i class="fas fa-sync-alt"></i> 刷新授权</h3>
            <p style="color: #5f6368; font-size: 13px; margin-bottom: 16px;">如果授权信息显示不正确，可以点击下方按钮刷新授权状态（不会重新申请授权）</p>
            <button type="button" class="btn btn-secondary" onclick="refreshAuth(this)">
                <i class="fas fa-sync"></i> 刷新授权状态
            </button>
        </div>
        
    </div>
    
    <script src="/static/js/jquery.min.js"></script>
    <script>
    var remainSeconds = <?php echo $remain_seconds_total; ?>;
    
    function updateCountdown() {
        if (remainSeconds <= 0) {
            document.getElementById('days').textContent = '0';
            document.getElementById('hours').textContent = '00';
            document.getElementById('minutes').textContent = '00';
            document.getElementById('seconds').textContent = '00';
            return;
        }
        
        var days = Math.floor(remainSeconds / 86400);
        var hours = Math.floor((remainSeconds % 86400) / 3600);
        var minutes = Math.floor((remainSeconds % 3600) / 60);
        var seconds = remainSeconds % 60;
        
        document.getElementById('days').textContent = days;
        document.getElementById('hours').textContent = hours < 10 ? '0' + hours : hours;
        document.getElementById('minutes').textContent = minutes < 10 ? '0' + minutes : minutes;
        document.getElementById('seconds').textContent = seconds < 10 ? '0' + seconds : seconds;
        
        remainSeconds--;
    }
    
    if (remainSeconds > 0) {
        updateCountdown();
        setInterval(updateCountdown, 1000);
    }
    
    function activateAuth(btn) {
        var authCode = document.getElementById('auth_code').value.trim();
        
        if (!authCode) {
            alert('请输入授权码');
            return;
        }
        
        var $btn = $(btn);
        var originalText = $btn.html();
        $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 激活中...');
        
        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: { egn: 'activate_auth', auth_code: authCode },
            dataType: 'json',
            success: function(data) {
                $btn.prop('disabled', false).html(originalText);
                if (data.code == 200) {
                    alert('授权激活成功！');
                    location.reload();
                } else {
                    alert('激活失败：' + (data.message || '未知错误'));
                }
            },
            error: function() {
                $btn.prop('disabled', false).html(originalText);
                alert('请求失败，请重试');
            }
        });
    }
    
    function refreshAuth(btn) {
        var $btn = $(btn);
        var originalText = $btn.html();
        $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 刷新中...');
        
        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: { egn: 'refresh_auth' },
            dataType: 'json',
            success: function(data) {
                $btn.prop('disabled', false).html(originalText);
                if (data.code == 200) {
                    alert('授权刷新成功！');
                    location.reload();
                } else {
                    alert('刷新失败：' + (data.message || '未知错误'));
                }
            },
            error: function() {
                $btn.prop('disabled', false).html(originalText);
                alert('请求失败，请重试');
            }
        });
    }
    
    function reapplyAuth(btn) {
        if (!confirm('确定要重新申请试用授权吗？这会清除本地授权记录并尝试重新申请。')) {
            return;
        }
        
        var $btn = $(btn);
        var originalText = $btn.html();
        $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 申请中...');
        
        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: { egn: 'reapply_auth' },
            dataType: 'json',
            success: function(data) {
                $btn.prop('disabled', false).html(originalText);
                if (data.code == 200) {
                    alert('试用授权申请成功！');
                    location.reload();
                } else {
                    alert('申请失败：' + (data.message || '未知错误'));
                }
            },
            error: function() {
                $btn.prop('disabled', false).html(originalText);
                alert('请求失败，请重试');
            }
        });
    }
    
    function queryDomainAuth(btn) {
        var $btn = $(btn);
        var originalText = $btn.html();
        $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 查询中...');
        
        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: { egn: 'query_domain_auth' },
            dataType: 'json',
            success: function(data) {
                $btn.prop('disabled', false).html(originalText);
                if (data.code == 200) {
                    var msg = '域名授权状态：\n';
                    msg += '域名：' + (data.domain || '未知') + '\n';
                    msg += '授权类型：' + (data.is_trial ? '试用授权' : '正式授权') + '\n';
                    msg += '过期时间：' + (data.expire_time || '未知') + '\n';
                    msg += '剩余天数：' + Math.floor(data.remain_seconds / 86400) + '天';
                    alert(msg);
                } else {
                    alert('查询结果：' + (data.message || '该域名暂无授权记录'));
                }
            },
            error: function() {
                $btn.prop('disabled', false).html(originalText);
                alert('请求失败，请重试');
            }
        });
    }
    </script>
</body>
</html>
