<?php
require __DIR__ . '/app/bootstrap.php';

if (!app_is_installed()) {
    redirect('install.php');
}

require_login(false);

// 授权激活页仅超管可访问
if (!is_super_admin()) {
    redirect('/admin/dashboard/index.php');
}

$lic = license_config();
$alreadyActive = license_is_activated();
$isExpired = license_is_expired();
$error = '';
$success = '';
$activationCode = '';

$errorParam = isset($_GET['error']) ? trim((string)$_GET['error']) : '';
if ($errorParam === 'expired') {
    $error = '授权已过期或已被禁用，请重新激活或联系管理员。';
} elseif ($errorParam === 'unreachable') {
    $error = '授权服务器无法连接且已超过宽限期，请检查网络后重试。';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) {
        $error = '页面已过期，请刷新后重试。';
    } else {
        $action = isset($_POST['action']) ? trim((string)$_POST['action']) : '';
        $activationCode = isset($_POST['activation_code']) ? strtoupper(trim((string)$_POST['activation_code'])) : '';

        if ($action === 'activate') {
            if ($activationCode === '') {
                $error = '请输入激活码。';
            } elseif (!preg_match('/^[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/', $activationCode)) {
                $error = '激活码格式不正确，应为 XXXX-XXXX-XXXX-XXXX。';
            } else {
                $oldLic = license_config();
                if (!empty($oldLic['activation_code']) && $oldLic['activation_code'] !== $activationCode) {
                    app_update_runtime_config(array(license_config_key() => array()));
                }
                $result = license_activate_remote($activationCode);
                if ($result['success']) {
                    $success = $result['msg'];
                    $lic = license_config();
                    $alreadyActive = license_is_activated();
                    $isExpired = license_is_expired();
                } else {
                    $error = $result['msg'];
                }
            }
        } elseif ($action === 'verify') {
            $result = license_verify_remote();
            if ($result['valid'] === true) {
                $success = '授权验证通过。';
                $lic = license_config();
            } elseif ($result['valid'] === false) {
                $error = $result['msg'];
                $lic = license_config();
            } else {
                $error = '无法连接授权服务器，请稍后重试。';
            }
            $alreadyActive = license_is_activated();
            $isExpired = license_is_expired();
        } elseif ($action === 'deactivate') {
            app_update_runtime_config(array(license_config_key() => array()));
            $lic = array();
            $alreadyActive = false;
            $isExpired = false;
            $success = '本地授权信息已清除。';
        }
    }
}

$adminName = isset($_SESSION['admin_name']) ? (string)$_SESSION['admin_name'] : 'Admin';
?><!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo e(APP_NAME); ?> - 授权激活</title>
    <link rel="stylesheet" href="assets/css/admin-ui.css">
    <style>
        .activate-wrap { max-width: 560px; margin: 60px auto; padding: 0 20px; }
        .activate-card { background: #fff; border-radius: 16px; box-shadow: 0 2px 24px rgba(0,0,0,0.07); padding: 40px 36px; }
        .activate-header { text-align: center; margin-bottom: 32px; }
        .activate-header .brand-icon { width: 56px; height: 56px; border-radius: 14px; background: linear-gradient(135deg, #f59e0b 0%, #f97316 100%); color: #fff; font-size: 28px; display: flex; align-items: center; justify-content: center; margin: 0 auto 16px; }
        .activate-header h1 { font-size: 22px; font-weight: 700; color: #111827; margin: 0 0 6px; }
        .activate-header p { font-size: 14px; color: #6b7280; margin: 0; }
        .activate-form .field { margin-bottom: 20px; }
        .activate-form label { display: block; font-size: 13px; font-weight: 600; color: #374151; margin-bottom: 6px; }
        .activate-form .code-input { width: 100%; padding: 12px 16px; font-size: 18px; font-family: 'Consolas','Courier New',monospace; letter-spacing: 2px; text-align: center; text-transform: uppercase; border: 2px solid #e5e7eb; border-radius: 10px; outline: none; transition: border-color 0.2s; }
        .activate-form .code-input:focus { border-color: #f59e0b; }
        .activate-form .btn-activate { width: 100%; padding: 13px; font-size: 16px; font-weight: 600; color: #fff; background: linear-gradient(135deg, #f59e0b 0%, #f97316 100%); border: none; border-radius: 10px; cursor: pointer; transition: opacity 0.2s; }
        .activate-form .btn-activate:hover { opacity: 0.9; }
        .msg-box { padding: 12px 16px; border-radius: 8px; margin-bottom: 20px; font-size: 14px; line-height: 1.5; }
        .msg-error { background: #fef2f2; color: #991b1b; border: 1px solid #fecaca; }
        .msg-success { background: #f0fdf4; color: #166534; border: 1px solid #bbf7d0; }
        .license-info { background: #f9fafb; border-radius: 10px; padding: 20px; margin-top: 24px; }
        .license-info h3 { font-size: 14px; font-weight: 600; color: #374151; margin: 0 0 12px; }
        .license-info dl { margin: 0; display: grid; grid-template-columns: 100px 1fr; gap: 8px 12px; font-size: 13px; }
        .license-info dt { color: #6b7280; font-weight: 500; }
        .license-info dd { color: #111827; margin: 0; font-weight: 600; }
        .license-info .badge-active { color: #15803d; }
        .license-info .badge-expired { color: #dc2626; }
        .license-info .badge-permanent { color: #0369a1; }
        .action-row { display: flex; gap: 10px; margin-top: 20px; }
        .action-row button, .action-row a { flex: 1; padding: 10px; font-size: 14px; font-weight: 500; border-radius: 8px; text-align: center; text-decoration: none; cursor: pointer; border: none; }
        .btn-enter { background: #f59e0b; color: #fff; }
        .btn-enter:hover { opacity: 0.9; }
        .btn-verify { background: #e5e7eb; color: #374151; }
        .btn-verify:hover { background: #d1d5db; }
        .btn-deactivate { background: #fee2e2; color: #991b1b; font-size: 12px; }
        .btn-deactivate:hover { background: #fecaca; }
        .footer-note { text-align: center; margin-top: 24px; font-size: 12px; color: #9ca3af; }
    </style>
</head>
<body style="background: #f3f4f6; min-height: 100vh;">
<div class="activate-wrap">
    <div class="activate-card">
        <div class="activate-header">
            <div class="brand-icon">蜂</div>
            <h1><?php echo e(APP_NAME); ?></h1>
            <p><?php echo $isExpired ? '授权已过期，请重新激活' : ($alreadyActive ? '授权信息' : '请输入激活码以启用系统功能'); ?></p>
        </div>

        <?php if ($error !== ''): ?>
            <div class="msg-box msg-error"><?php echo e($error); ?></div>
        <?php endif; ?>
        <?php if ($success !== ''): ?>
            <div class="msg-box msg-success"><?php echo e($success); ?></div>
        <?php endif; ?>

        <?php if ($isExpired): ?>
            <div class="msg-box msg-error" style="text-align:center;font-size:16px;font-weight:700;padding:18px 20px;">
                ⚠ 您的授权已过期或已失效，系统功能已锁定。
            </div>
            <div class="license-info" style="opacity:0.7;">
                <h3>过期授权信息</h3>
                <dl>
                    <dt>激活码</dt>
                    <dd><?php echo e(isset($lic['activation_code']) && $lic['activation_code'] !== '' ? $lic['activation_code'] : '-'); ?></dd>
                    <dt>授权状态</dt>
                    <dd class="badge-expired"><?php echo e(license_status_label()); ?></dd>
                    <dt>截止日期</dt>
                    <dd style="color:#dc2626;font-weight:700;"><?php echo e(license_end_date_display_text($lic)); ?></dd>
                    <dt>上次验证</dt>
                    <dd><?php echo !empty($lic['last_verify_at']) ? date('Y-m-d H:i', (int)$lic['last_verify_at']) : '-'; ?></dd>
                </dl>
            </div>
            <form class="activate-form" method="post" style="margin-top:24px;">
                <?php echo csrf_field(); ?>
                <input type="hidden" name="action" value="activate">
                <div class="field">
                    <label>输入新激活码</label>
                    <input class="code-input" type="text" name="activation_code" value="<?php echo e($activationCode); ?>" placeholder="XXXX-XXXX-XXXX-XXXX" maxlength="19" autocomplete="off" autofocus>
                </div>
                <button class="btn-activate" type="submit">激活系统</button>
            </form>
            <div class="action-row" style="margin-top:16px;">
                <form method="post" style="flex:1; display:flex;">
                    <?php echo csrf_field(); ?>
                    <input type="hidden" name="action" value="verify">
                    <button class="btn-verify" type="submit" style="width:100%;">重新验证</button>
                </form>
            </div>
            <div style="text-align:center; margin-top:10px;">
                <form method="post" onsubmit="return confirm('确定要清除本地授权信息吗？');">
                    <?php echo csrf_field(); ?>
                    <input type="hidden" name="action" value="deactivate">
                    <button class="btn-deactivate" type="submit">清除本地授权</button>
                </form>
            </div>
        <?php elseif ($alreadyActive): ?>
            <div class="license-info">
                <h3>当前授权</h3>
                <dl>
                    <dt>激活码</dt>
                    <dd><?php echo e(isset($lic['activation_code']) && $lic['activation_code'] !== '' ? $lic['activation_code'] : '-'); ?></dd>
                    <dt>授权状态</dt>
                    <dd class="<?php echo (isset($lic['status']) && $lic['status'] === 'active') ? 'badge-active' : 'badge-expired'; ?>"><?php echo e(license_status_label()); ?></dd>
                    <dt>被授权方</dt>
                    <dd><?php echo e(!empty($lic['licensee']) ? $lic['licensee'] : (!empty($lic['username']) ? $lic['username'] : '-')); ?></dd>
                    <dt>授权域名</dt>
                    <dd><?php echo e(!empty($lic['domain']) ? $lic['domain'] : request_host()); ?></dd>
                    <dt>起始日期</dt>
                    <dd><?php echo e(!empty($lic['start_date']) ? $lic['start_date'] : '-'); ?></dd>
                    <dt>截止日期</dt>
                    <dd class="<?php echo empty($lic['end_date']) ? 'badge-permanent' : ''; ?>"><?php echo e(license_end_date_display_text($lic)); ?></dd>
                    <?php if (!empty($lic['end_date'])): ?>
                        <dt>剩余天数</dt>
                        <dd><?php $d = license_days_remaining(); echo $d >= 0 ? $d . ' 天' : '-'; ?></dd>
                    <?php endif; ?>
                    <dt>上次验证</dt>
                    <dd><?php echo !empty($lic['last_verify_at']) ? date('Y-m-d H:i', (int)$lic['last_verify_at']) : '-'; ?></dd>
                </dl>
            </div>
            <div class="action-row">
                <a class="btn-enter" href="/admin/dashboard/index.php">进入后台</a>
                <form method="post" style="flex:1; display:flex;">
                    <?php echo csrf_field(); ?>
                    <input type="hidden" name="action" value="verify">
                    <button class="btn-verify" type="submit" style="width:100%;">重新验证</button>
                </form>
            </div>
            <div style="text-align:center; margin-top:14px;">
                <form method="post" onsubmit="return confirm('确定要清除本地授权信息吗？清除后需重新激活。');">
                    <?php echo csrf_field(); ?>
                    <input type="hidden" name="action" value="deactivate">
                    <button class="btn-deactivate" type="submit">清除授权并重新激活</button>
                </form>
            </div>
        <?php else: ?>
            <form class="activate-form" method="post">
                <?php echo csrf_field(); ?>
                <input type="hidden" name="action" value="activate">
                <div class="field">
                    <label>激活码</label>
                    <input class="code-input" type="text" name="activation_code" value="<?php echo e($activationCode); ?>" placeholder="XXXX-XXXX-XXXX-XXXX" maxlength="19" autocomplete="off" autofocus>
                </div>
                <button class="btn-activate" type="submit">激活系统</button>
            </form>
            <div class="footer-note">
                激活码由系统管理员发放，如需获取请联系 <?php echo e(APP_DEVELOPER); ?>。<br>
                当前域名：<?php echo e(request_host()); ?>
            </div>
        <?php endif; ?>
    </div>
    <div class="footer-note" style="margin-top:16px;">
        <?php echo e(APP_NAME); ?> v<?php echo e(APP_VERSION); ?> &middot; 已登录为 <?php echo e($adminName); ?>
        &middot; <a href="logout.php" style="color:#6b7280;">退出登录</a>
    </div>
</div>
<script>
var input = document.querySelector('.code-input');
if (input) {
    input.addEventListener('input', function() {
        var v = this.value.replace(/[^A-Za-z0-9]/g, '').toUpperCase().substring(0, 16);
        var parts = [];
        for (var i = 0; i < v.length; i += 4) {
            parts.push(v.substring(i, i + 4));
        }
        this.value = parts.join('-');
    });
}
</script>
</body>
</html>
