<?php
requireAdmin();

// ========== 处理 AJAX 请求（必须在任何输出之前） ==========
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'toggle_status') {
    header('Content-Type: application/json');
    $id = intval($_POST['id'] ?? 0);
    $status = intval($_POST['status'] ?? 0);
    $db->query("UPDATE licenses SET status = $status WHERE id = $id");
    echo json_encode(['success' => true]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'delete') {
    header('Content-Type: application/json');
    $id = intval($_POST['id'] ?? 0);
    $db->query("DELETE FROM licenses WHERE id = $id");
    echo json_encode(['success' => true]);
    exit;
}

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 used FROM licenses WHERE id = $license_id");
    if ($license && $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;
}

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

$where = "1=1";
if ($search) {
    $search = $db->escape($search);
    $where .= " AND (l.license_code LIKE '%$search%' OR u.username LIKE '%$search%' OR a.name LIKE '%$search%')";
}
if ($app_id > 0) {
    $where .= " AND l.app_id = $app_id";
}
if ($status >= 0) {
    $where .= " AND l.status = $status";
}

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

$licenses = $db->fetchAll("
    SELECT l.*, a.name as app_name, u.username, u.email
    FROM licenses l 
    JOIN apps a ON l.app_id = a.id 
    JOIN users u ON l.user_id = u.id
    WHERE $where 
    ORDER BY l.id DESC 
    LIMIT $offset, $perpage
");

$apps = $db->fetchAll("SELECT id, name FROM apps WHERE status = 1 ORDER BY id DESC");
?>

<div class="licenses-manager">
    <div class="page-header">
        <h2>授权管理</h2>
        <p class="text-muted">管理所有用户的授权码</p>
    </div>
    
    <div class="filter-bar">
        <form method="GET" class="search-form" id="filterForm">
            <input type="hidden" name="page" value="licenses">
            <div class="search-row">
                <input type="text" name="search" placeholder="搜索授权码/用户名/应用名" value="<?php echo htmlspecialchars($search); ?>">
                <select name="app_id">
                    <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>
                <select name="status">
                    <option value="-1">全部状态</option>
                    <option value="1" <?php echo $status == 1 ? 'selected' : ''; ?>>有效</option>
                    <option value="0" <?php echo $status == 0 ? 'selected' : ''; ?>>已禁用</option>
                </select>
                <button type="submit" class="btn btn-primary">搜索</button>
                <?php if ($search || $app_id || $status != -1): ?>
                    <a href="?page=licenses" class="btn btn-secondary">清空</a>
                <?php endif; ?>
            </div>
        </form>
    </div>
    
    <div class="table-container">
        <table class="data-table" id="licensesTable">
            <thead>
                <tr>
                    <th>授权码</th>
                    <th>用户</th>
                    <th>应用名称</th>
                    <th>绑定域名</th>
                    <th>到期时间</th>
                    <th>状态</th>
                    <th>创建时间</th>
                    <!--<th>使用状态</th>-->
                    <th>操作</th>
                </thead>
            <tbody>
                <?php if (empty($licenses)): ?>
                    <tr><td colspan="9" style="text-align: center; padding: 60px;">暂无授权码</td></tr>
                <?php else: ?>
                    <?php foreach ($licenses as $lic): ?>
                        <tr id="license-row-<?php echo $lic['id']; ?>">
                            <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 if ($lic['used'] == 1): ?>-->
<!--        <span class="status-badge status-used">已使用</span>-->
<!--        <br><small>使用域名：<?php echo htmlspecialchars($lic['used_domain']); ?></small>-->
<!--        <br><small>使用时间：<?php echo $lic['used_at']; ?></small>-->
<!--    <?php else: ?>-->
<!--        <span class="status-badge status-unused">未使用</span>-->
<!--    <?php endif; ?>-->
<!--</td>-->
                            <td>
                                <strong><?php echo htmlspecialchars($lic['username']); ?></strong><br>
                                <small style="color: var(--text-muted);"><?php echo htmlspecialchars($lic['email']); ?></small>
                            </td>
                            <td><?php echo htmlspecialchars($lic['app_name']); ?></td>
                            <td>
                                <?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-<?php echo $lic['status'] ? 'active' : 'inactive'; ?>">
                                    <?php echo $lic['status'] ? '有效' : '已禁用'; ?>
                                </span>
                            </td>
                            <td><?php echo $lic['created_at']; ?></td>
                            <td class="action-buttons">
                                <button class="action-btn toggle-status-btn" data-id="<?php echo $lic['id']; ?>" data-status="<?php echo $lic['status']; ?>">
                                    <?php echo $lic['status'] ? '🔴 禁用' : '🟢 启用'; ?>
                                </button>
                                <button class="action-btn" onclick="showBindModal(<?php echo $lic['id']; ?>, '<?php echo $lic['license_code']; ?>', '<?php echo htmlspecialchars($lic['domain'] ?: ''); ?>')">
                                    🌐 绑定
                                </button>
                                <button class="action-btn delete-btn" onclick="deleteLicense(<?php echo $lic['id']; ?>)">
                                    🗑️ 删除
                                </button>
                            </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&p=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&app_id=<?php echo $app_id; ?>&status=<?php echo $status; ?>" 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>
                </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</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-manager .page-header { margin-bottom: 20px; }
.licenses-manager .page-header h2 { margin-bottom: 4px; }
.text-muted { color: var(--text-muted); font-size: 13px; }
.filter-bar { margin-bottom: 20px; }
.search-form .search-row { display: flex; gap: 10px; flex-wrap: wrap; }
.search-form input, .search-form select { padding: 8px 16px; border: 1px solid var(--border-color); border-radius: var(--radius-sm); background: var(--bg-primary); }
.search-form input { flex: 2; min-width: 200px; }
.search-form select { min-width: 120px; }
.license-code { display: flex; align-items: center; gap: 8px; }
.license-code code { background: var(--bg-secondary); padding: 4px 8px; border-radius: 6px; font-size: 12px; }
.copy-btn { background: none; border: none; cursor: pointer; font-size: 14px; padding: 4px; border-radius: 4px; }
.copy-btn:hover { background: var(--bg-secondary); }
.domain-badge { background: var(--primary-light); color: var(--primary-color); padding: 2px 8px; border-radius: 20px; font-size: 12px; }
.domain-empty { color: var(--text-muted); font-size: 12px; }
.status-badge { display: inline-block; padding: 4px 10px; border-radius: 20px; font-size: 12px; font-weight: 500; }
.status-active { background: #d1fae5; color: #065f46; }
.status-inactive { background: #fee2e2; color: #991b1b; }
.action-buttons { display: flex; gap: 8px; flex-wrap: wrap; }
.action-btn { background: none; border: 1px solid var(--border-color); padding: 4px 10px; border-radius: 6px; cursor: pointer; font-size: 12px; transition: all 0.2s; display: inline-flex; align-items: center; gap: 4px; }
.action-btn:hover { border-color: var(--primary-color); background: var(--primary-light); }
.delete-btn:hover { border-color: var(--danger-color); color: var(--danger-color); background: #fee2e2; }
.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: var(--radius-md); width: 90%; max-width: 400px; }
.modal-header { padding: 15px 20px; border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; align-items: center; }
.modal-body { padding: 20px; }
.modal-footer { padding: 15px 20px; border-top: 1px solid var(--border-color); display: flex; gap: 10px; justify-content: flex-end; }
.close { cursor: pointer; font-size: 24px; }
.form-group { margin-bottom: 15px; }
.form-group label { display: block; margin-bottom: 6px; font-weight: 500; }
.form-group input { width: 100%; padding: 10px 12px; border: 1px solid var(--border-color); border-radius: var(--radius-sm); }
.pagination { display: flex; gap: 8px; justify-content: center; margin-top: 20px; }
.page-link { padding: 6px 12px; border: 1px solid var(--border-color); border-radius: var(--radius-sm); text-decoration: none; color: var(--text-primary); }
.page-link.active { background: var(--primary-color); color: white; border-color: var(--primary-color); }
.loading-spinner { display: inline-block; width: 14px; height: 14px; border: 2px solid #fff; border-radius: 50%; border-top-color: transparent; animation: spin 0.6s linear infinite; }
.status-used {
    background: #fef3c7;
    color: #92400e;
}
.status-unused {
    background: #d1fae5;
    color: #065f46;
}
@keyframes spin { to { transform: rotate(360deg); } }
</style>

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

function toggleStatus(element, licenseId, currentStatus) {
    const newStatus = currentStatus == 1 ? 0 : 1;
    const btn = element;
    const row = document.getElementById('license-row-' + licenseId);
    const statusSpan = row.querySelector('.status-badge');
    const originalText = btn.innerHTML;
    btn.innerHTML = '<span class="loading-spinner"></span> 处理中...';
    btn.disabled = true;
    
    fetch('?page=licenses&action=toggle_status', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `id=${licenseId}&status=${newStatus}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            if (newStatus == 1) {
                statusSpan.className = 'status-badge status-active';
                statusSpan.innerHTML = '有效';
                btn.innerHTML = '🔴 禁用';
                btn.setAttribute('data-status', '1');
            } else {
                statusSpan.className = 'status-badge status-inactive';
                statusSpan.innerHTML = '已禁用';
                btn.innerHTML = '🟢 启用';
                btn.setAttribute('data-status', '0');
            }
            btn.setAttribute('data-status', newStatus);
            window.showToast('状态已更新', 'success');
        } else {
            window.showToast(data.message || '操作失败', 'error');
        }
        btn.innerHTML = originalText;
        btn.disabled = false;
    })
    .catch(error => { window.showToast('网络错误', 'error'); btn.innerHTML = originalText; btn.disabled = false; });
}

function deleteLicense(licenseId) {
    if (confirm('确定要删除此授权码吗？此操作不可恢复。')) {
        const row = document.getElementById('license-row-' + licenseId);
        const deleteBtn = row.querySelector('.delete-btn');
        deleteBtn.innerHTML = '<span class="loading-spinner"></span> 删除中...';
        deleteBtn.disabled = true;
        
        fetch('?page=licenses&action=delete', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `id=${licenseId}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                row.remove();
                window.showToast('删除成功', 'success');
                if (document.querySelectorAll('#licensesTable tbody tr').length === 0) location.reload();
            } else {
                window.showToast(data.message || '删除失败', 'error');
                deleteBtn.innerHTML = '🗑️ 删除';
                deleteBtn.disabled = false;
            }
        })
        .catch(error => { window.showToast('网络错误', 'error'); deleteBtn.innerHTML = '🗑️ 删除'; deleteBtn.disabled = false; });
    }
}

function showBindModal(id, code, currentDomain) {
    const modal = document.getElementById('bindModal');
    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() { document.getElementById('bindModal').style.display = 'none'; }

document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.toggle-status-btn').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            toggleStatus(this, this.getAttribute('data-id'), parseInt(this.getAttribute('data-status')));
        });
    });
    
    document.querySelectorAll('.close, .cancel-btn').forEach(btn => btn.addEventListener('click', closeModal));
    
    const modal = document.getElementById('bindModal');
    if (modal) modal.addEventListener('click', function(e) { if (e.target === modal) closeModal(); });
    
    document.getElementById('bindForm')?.addEventListener('submit', function(e) {
        e.preventDefault();
        const licenseId = document.getElementById('bind_license_id').value;
        const domain = document.getElementById('bind_domain').value.trim();
        const submitBtn = this.querySelector('button[type="submit"]');
        
        if (!domain) { window.showToast('请输入域名', 'error'); return; }
        if (!/^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$/.test(domain)) {
            window.showToast('域名格式不正确', 'error'); return;
        }
        
        const originalText = submitBtn.innerHTML;
        submitBtn.innerHTML = '<span class="loading-spinner"></span> 保存中...';
        submitBtn.disabled = true;
        
        fetch('?page=licenses&action=bind_domain', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `license_id=${licenseId}&domain=${encodeURIComponent(domain)}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const row = document.getElementById('license-row-' + licenseId);
                const domainCell = row.querySelector('td:nth-child(5)');
                domainCell.innerHTML = '<span class="domain-badge">' + escapeHtml(domain) + '</span>';
                window.showToast('域名绑定成功', 'success');
                closeModal();
            } else {
                window.showToast(data.message || '绑定失败', 'error');
            }
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        })
        .catch(error => { window.showToast('网络错误', 'error'); submitBtn.innerHTML = originalText; submitBtn.disabled = false; });
    });
});

function escapeHtml(text) { if (!text) return ''; return text.replace(/[&<>]/g, function(m) { if (m === '&') return '&amp;'; if (m === '<') return '&lt;'; if (m === '>') return '&gt;'; return m; }); }
</script>