<?php
$user_id = $_SESSION['user_id'];

// ========== 处理域名绑定请求（必须在任何输出之前） ==========
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'bind_domain') {
    header('Content-Type: application/json');
    
    $license_id = intval($_POST['license_id'] ?? 0);
    $domain = trim($_POST['domain'] ?? '');
    
    // 验证域名格式
    if (!preg_match('/^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$/', $domain)) {
        echo json_encode(['success' => false, 'message' => '域名格式不正确']);
        exit;
    }
    
    // 验证授权码属于当前用户，并检查是否已被使用
    $license = $db->fetchOne("SELECT id, used FROM licenses WHERE id = $license_id AND user_id = $user_id");
    if (!$license) {
        echo json_encode(['success' => false, 'message' => '授权码不存在']);
        exit;
    }
    
    // 检查授权码是否已被使用
    if ($license['used'] == 1) {
        echo json_encode(['success' => false, 'message' => '授权码已被使用，无法绑定']);
        exit;
    }
    
    $domain = $db->escape($domain);
    // 绑定域名并标记为已使用
    $db->query("UPDATE licenses SET domain = '$domain', used = 1, used_at = NOW(), used_domain = '$domain' WHERE id = $license_id");
    echo json_encode(['success' => true]);
    exit;
}

// ========== 以下是正常页面显示 ==========
$app_id = isset($_GET['app_id']) ? intval($_GET['app_id']) : 0;
$page = isset($_GET['p']) ? intval($_GET['p']) : 1;
$perpage = 15;

// 获取应用列表用于筛选
$apps = $db->fetchAll("SELECT id, name FROM apps WHERE id IN (SELECT DISTINCT app_id FROM licenses WHERE user_id = $user_id)");

// 构建查询条件
$where = "user_id = $user_id";
if ($app_id > 0) {
    $where .= " AND app_id = $app_id";
}

// 获取总数
$total_result = $db->query("SELECT COUNT(*) as cnt FROM licenses WHERE $where");
$total = $total_result->fetch_assoc()['cnt'];
$offset = ($page - 1) * $perpage;

// 获取授权码列表
$licenses = $db->fetchAll("
    SELECT l.*, a.name as app_name 
    FROM licenses l 
    JOIN apps a ON l.app_id = a.id 
    WHERE $where 
    ORDER BY l.id DESC 
    LIMIT $offset, $perpage
");
?>

<div class="licenses-container">
    <div class="page-header">
        <div class="page-title-section">
            <h2>授权码管理</h2>
            <p class="page-desc">管理您的授权码，支持复制和绑定域名</p>
        </div>
        <a href="?page=buy_app" class="btn btn-primary">
            <span class="btn-icon">+</span> 购买新授权
        </a>
    </div>
    
    <!-- 筛选栏 -->
    <div class="filter-bar">
        <div class="filter-left">
            <label>筛选应用：</label>
            <select id="appFilter" onchange="location.href='?page=licenses&app_id='+this.value">
                <option value="0">全部应用</option>
                <?php foreach ($apps as $app): ?>
                    <option value="<?php echo $app['id']; ?>" <?php echo $app_id == $app['id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($app['name']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="filter-right">
            <span class="total-count">共 <?php echo $total; ?> 个授权码</span>
        </div>
    </div>
    
    <div class="table-wrapper">
        <table class="data-table">
            <thead>
                <tr>
                    <th>授权码</th>
                    <th>应用名称</th>
                    <th>绑定域名</th>
                    <th>到期时间</th>
                    <th>状态</th>
                    <th>使用状态</th>
                </thead>
            <tbody>
                <?php if (empty($licenses)): ?>
                    <tr>
                        <td colspan="7" class="empty-row">暂无授权码</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($licenses as $lic): ?>
                        <tr>
                            <td class="license-code">
                                <code><?php echo htmlspecialchars($lic['license_code']); ?></code>
                                <button class="copy-btn" onclick="copyToClipboard('<?php echo $lic['license_code']; ?>')" title="复制授权码">
                                    📋
                                </button>
                            </td>
                            <td><?php echo htmlspecialchars($lic['app_name']); ?></td>
                            <td class="domain-cell">
                                <?php if ($lic['domain']): ?>
                                    <span class="domain-badge"><?php echo htmlspecialchars($lic['domain']); ?></span>
                                <?php else: ?>
                                    <span class="domain-empty">未绑定</span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo $lic['expire_date'] ?: '永久'; ?></td>
                            <td>
                                <span class="status-badge status-active">有效</span>
                            </td>
                            <td>
                                <?php if ($lic['used'] == 1): ?>
                                    <span class="status-badge status-used">已使用</span>
                                    <br><small style="color: var(--text-muted);"><?php echo htmlspecialchars($lic['used_domain']); ?></small>
                                <?php else: ?>
                                    <span class="status-badge status-unused">未使用</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <!-- 分页 -->
    <?php if ($total > $perpage): ?>
        <div class="pagination">
            <?php
            $total_pages = ceil($total / $perpage);
            for ($i = 1; $i <= $total_pages; $i++):
            ?>
                <a href="?page=licenses&app_id=<?php echo $app_id; ?>&p=<?php echo $i; ?>" class="page-link <?php echo $i == $page ? 'active' : ''; ?>">
                    <?php echo $i; ?>
                </a>
            <?php endfor; ?>
        </div>
    <?php endif; ?>
</div>

<!-- 绑定域名弹窗 -->
<div id="bindModal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3>绑定域名</h3>
            <span class="close">&times;</span>
        </div>
        <form id="bindForm">
            <input type="hidden" name="license_id" id="bind_license_id">
            <div class="modal-body">
                <div class="form-group">
                    <label>授权码</label>
                    <input type="text" id="bind_license_code" readonly class="readonly-input">
                </div>
                <div class="form-group">
                    <label>绑定域名</label>
                    <input type="text" name="domain" id="bind_domain" placeholder="例如：example.com" required>
                    <small>支持域名格式，如：example.com 或 sub.example.com<br>⚠️ 注意：绑定后授权码将变为已使用状态，不可更改</small>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary cancel-btn">取消</button>
                <button type="submit" class="btn btn-primary">保存绑定</button>
            </div>
        </form>
    </div>
</div>

<style>
.licenses-container {
    max-width: 100%;
}

/* 页面头部 */
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    flex-wrap: wrap;
    gap: 16px;
}
.page-title-section h2 {
    font-size: 24px;
    font-weight: 600;
    margin-bottom: 4px;
    color: var(--text-primary);
}
.page-desc {
    font-size: 14px;
    color: var(--text-secondary);
}
.btn-primary {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 10px 24px;
    background: var(--primary-color);
    color: white;
    border-radius: 10px;
    text-decoration: none;
    font-weight: 500;
    font-size: 14px;
    transition: all 0.2s;
}
.btn-primary:hover {
    background: var(--primary-hover);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(59,130,246,0.3);
}
.btn-icon {
    font-size: 16px;
}

/* 筛选栏 */
.filter-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    flex-wrap: wrap;
    gap: 12px;
}
.filter-left {
    display: flex;
    align-items: center;
    gap: 12px;
}
.filter-left label {
    font-size: 14px;
    color: var(--text-secondary);
}
.filter-left select {
    padding: 8px 16px;
    border: 1px solid var(--border-color);
    border-radius: 8px;
    background: var(--bg-primary);
    font-size: 14px;
    cursor: pointer;
}
.total-count {
    font-size: 13px;
    color: var(--text-muted);
    background: var(--bg-secondary);
    padding: 4px 12px;
    border-radius: 20px;
}

/* 表格 */
.table-wrapper {
    overflow-x: auto;
    background: var(--bg-primary);
    border-radius: 16px;
    border: 1px solid var(--border-color);
}
.data-table {
    width: 100%;
    border-collapse: collapse;
}
.data-table th {
    padding: 16px 20px;
    text-align: left;
    font-weight: 600;
    font-size: 14px;
    color: var(--text-secondary);
    background: var(--bg-secondary);
    border-bottom: 1px solid var(--border-color);
}
.data-table td {
    padding: 16px 20px;
    border-bottom: 1px solid var(--border-color);
    font-size: 14px;
}
.data-table tr:hover {
    background: var(--bg-secondary);
}
.empty-row {
    text-align: center;
    padding: 60px;
    color: var(--text-muted);
}

/* 授权码单元格 */
.license-code {
    display: flex;
    align-items: center;
    gap: 8px;
    font-family: monospace;
}
.license-code code {
    background: var(--bg-secondary);
    padding: 4px 8px;
    border-radius: 6px;
    font-size: 13px;
}
.copy-btn {
    background: none;
    border: none;
    cursor: pointer;
    font-size: 16px;
    padding: 4px;
    border-radius: 4px;
    transition: background 0.2s;
}
.copy-btn:hover {
    background: var(--bg-secondary);
}

/* 域名标签 */
.domain-badge {
    background: var(--primary-light);
    color: var(--primary-color);
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
}
.domain-empty {
    color: var(--text-muted);
    font-size: 13px;
}

/* 状态标签 */
.status-badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
}
.status-active {
    background: #d1fae5;
    color: #065f46;
}
.status-used {
    background: #fef3c7;
    color: #92400e;
}
.status-unused {
    background: #d1fae5;
    color: #065f46;
}
.disabled-action {
    color: var(--text-muted);
    font-size: 13px;
}

/* 操作按钮 */
.action-buttons {
    white-space: nowrap;
}
.action-btn {
    background: none;
    border: 1px solid var(--border-color);
    padding: 6px 14px;
    border-radius: 8px;
    cursor: pointer;
    font-size: 13px;
    transition: all 0.2s;
    background: var(--bg-primary);
    color: var(--text-primary);
}
.action-btn:hover {
    border-color: var(--primary-color);
    color: var(--primary-color);
    background: var(--primary-light);
}

/* 分页 */
.pagination {
    display: flex;
    gap: 8px;
    justify-content: center;
    margin-top: 24px;
}
.page-link {
    padding: 8px 14px;
    border: 1px solid var(--border-color);
    border-radius: 8px;
    text-decoration: none;
    color: var(--text-primary);
    transition: all 0.2s;
}
.page-link:hover {
    border-color: var(--primary-color);
    background: var(--primary-light);
}
.page-link.active {
    background: var(--primary-color);
    color: white;
    border-color: var(--primary-color);
}

/* 弹窗 */
.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
}
.modal-content {
    background: var(--bg-primary);
    border-radius: 20px;
    width: 90%;
    max-width: 450px;
    box-shadow: var(--shadow-lg);
}
.modal-header {
    padding: 20px 24px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.modal-header h3 {
    font-size: 18px;
    font-weight: 600;
}
.close {
    cursor: pointer;
    font-size: 24px;
    color: var(--text-muted);
}
.modal-body {
    padding: 24px;
}
.modal-footer {
    padding: 16px 24px;
    border-top: 1px solid var(--border-color);
    display: flex;
    gap: 12px;
    justify-content: flex-end;
}
.form-group {
    margin-bottom: 20px;
}
.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    font-size: 14px;
}
.form-group input {
    width: 100%;
    padding: 12px 16px;
    border: 1px solid var(--border-color);
    border-radius: 10px;
    font-size: 14px;
    background: var(--bg-primary);
}
.readonly-input {
    background: var(--bg-secondary) !important;
    cursor: not-allowed;
}
.form-group small {
    display: block;
    margin-top: 6px;
    font-size: 12px;
    color: var(--text-muted);
}
.btn-secondary {
    padding: 10px 20px;
    background: var(--bg-secondary);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    cursor: pointer;
    font-size: 14px;
}
.btn-secondary:hover {
    background: var(--bg-tertiary);
}

/* 响应式 */
@media (max-width: 768px) {
    .page-header {
        flex-direction: column;
        align-items: flex-start;
    }
    .filter-bar {
        flex-direction: column;
        align-items: flex-start;
    }
    .data-table th, .data-table td {
        padding: 12px;
    }
    .license-code {
        flex-wrap: wrap;
    }
    .action-btn {
        padding: 4px 10px;
        font-size: 12px;
    }
}
</style>

<script>
// 复制到剪贴板
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        if (window.showToast) window.showToast('授权码已复制', 'success');
        else alert('复制成功');
    }).catch(() => {
        const ta = document.createElement('textarea');
        ta.value = text;
        document.body.appendChild(ta);
        ta.select();
        document.execCommand('copy');
        document.body.removeChild(ta);
        if (window.showToast) window.showToast('授权码已复制', 'success');
        else alert('复制成功');
    });
}

// 显示绑定弹窗
function showBindModal(id, code, currentDomain) {
    const modal = document.getElementById('bindModal');
    if (!modal) return;
    document.getElementById('bind_license_id').value = id;
    document.getElementById('bind_license_code').value = code;
    document.getElementById('bind_domain').value = currentDomain !== '未绑定' ? currentDomain : '';
    modal.style.display = 'flex';
}

// 关闭弹窗
function closeModal() {
    const modal = document.getElementById('bindModal');
    if (modal) modal.style.display = 'none';
}

// 绑定表单提交
document.addEventListener('DOMContentLoaded', function() {
    const modal = document.getElementById('bindModal');
    const bindForm = document.getElementById('bindForm');
    
    // 关闭按钮
    document.querySelectorAll('.close, .cancel-btn').forEach(btn => {
        btn.addEventListener('click', closeModal);
    });
    
    // 点击背景关闭
    if (modal) {
        modal.addEventListener('click', function(e) {
            if (e.target === modal) closeModal();
        });
    }
    
    // 表单提交
    if (bindForm) {
        bindForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const licenseId = document.getElementById('bind_license_id').value;
            const domain = document.getElementById('bind_domain').value.trim();
            
            if (!domain) {
                if (window.showToast) window.showToast('请输入域名', 'error');
                else alert('请输入域名');
                return;
            }
            
            const domainPattern = /^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$/;
            if (!domainPattern.test(domain)) {
                if (window.showToast) window.showToast('域名格式不正确', 'error');
                else alert('域名格式不正确');
                return;
            }
            
            fetch('/api/bind_domain.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'license_id=' + encodeURIComponent(licenseId) + '&domain=' + encodeURIComponent(domain)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    if (window.showToast) window.showToast('域名绑定成功', 'success');
                    else alert('域名绑定成功');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    if (window.showToast) window.showToast(data.message || '绑定失败', 'error');
                    else alert(data.message || '绑定失败');
                }
                closeModal();
            })
            .catch(error => {
                console.error('绑定错误:', error);
                if (window.showToast) window.showToast('网络错误', 'error');
                else alert('网络错误');
                closeModal();
            });
        });
    }
});
</script>