<?php
ob_start();

requireAdmin();

// ========== 处理 AJAX 请求（必须在任何输出之前） ==========
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'toggle_status') {
    
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'delete') {
    
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'bind_domain') {
    
    
    $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";
}

// 修改这里：COUNT 查询也需要 JOIN
$total_result = $db->query("
    SELECT COUNT(*) as cnt 
    FROM licenses l 
    JOIN apps a ON l.app_id = a.id 
    JOIN users u ON l.user_id = u.id 
    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");

// 统计数据
$stats = [
    'total' => $db->fetchOne("SELECT COUNT(*) as cnt FROM licenses")['cnt'],
    'active' => $db->fetchOne("SELECT COUNT(*) as cnt FROM licenses WHERE status = 1")['cnt'],
    'inactive' => $db->fetchOne("SELECT COUNT(*) as cnt FROM licenses WHERE status = 0")['cnt'],
];
?>

<div class="licenses-manager">
    <!-- 页面头部 -->
    <div class="page-header">
        <h2>
            <img src="https://api.iconify.design/mdi:key.svg?color=%23667eea" width="26" height="26" style="vertical-align: middle; margin-right: 10px;" alt="">
            授权管理
        </h2>
        <p class="text-muted">管理所有用户的授权码</p>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-mini">
        <div class="stat-mini-item">
            <img src="https://api.iconify.design/mdi:key.svg?color=%23667eea" width="20" height="20" alt="">
            <span class="stat-label">总授权数</span>
            <span class="stat-value"><?php echo $stats['total']; ?></span>
        </div>
        <div class="stat-mini-item">
            <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="20" height="20" alt="">
            <span class="stat-label">有效授权</span>
            <span class="stat-value"><?php echo $stats['active']; ?></span>
        </div>
        <div class="stat-mini-item">
            <img src="https://api.iconify.design/mdi:close-circle.svg?color=%23ef4444" width="20" height="20" alt="">
            <span class="stat-label">已禁用</span>
            <span class="stat-value"><?php echo $stats['inactive']; ?></span>
        </div>
    </div>
    
    <!-- 筛选栏 -->
    <div class="filter-bar">
        <form method="GET" class="search-form" id="filterForm">
            <input type="hidden" name="page" value="licenses">
            <div class="search-row">
                <div class="search-input-wrapper">
                    <img src="https://api.iconify.design/mdi:magnify.svg?color=%239ca3af" width="18" height="18" class="search-icon" alt="">
                    <input type="text" name="search" placeholder="搜索授权码/用户名/应用名" value="<?php echo htmlspecialchars($search); ?>">
                </div>
                <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">
                    <img src="https://api.iconify.design/mdi:magnify.svg?color=white" width="16" height="16" style="margin-right: 4px;" alt="">
                    搜索
                </button>
                <?php if ($search || $app_id || $status != -1): ?>
                    <a href="?page=licenses" class="btn btn-secondary">
                        <img src="https://api.iconify.design/mdi:close.svg?color=currentColor" width="16" height="16" style="margin-right: 4px;" alt="">
                        清空
                    </a>
                <?php endif; ?>
            </div>
        </form>
    </div>
    
    <!-- 授权列表 -->
    <div class="table-wrapper">
        <table class="data-table" id="licensesTable">
            <thead>
                <tr>
                    <th>授权码</th>
                    <th>用户</th>
                    <th>应用名称</th>
                    <th>绑定域名</th>
                    <th>到期时间</th>
                    <th>状态</th>
                    <th>创建时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($licenses)): ?>
                    <tr>
                        <td colspan="8">
                            <div class="empty-state">
                                <img src="https://api.iconify.design/mdi:key-off.svg?color=%239ca3af" width="48" height="48" alt="">
                                <p>暂无授权码</p>
                            </div>
                        </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="复制">
                                    <img src="https://api.iconify.design/mdi:content-copy.svg?color=%239ca3af" width="14" height="14" alt="">
                                </button>
                            </td>
                            <td>
                                <div class="user-info">
                                    <img src="https://api.iconify.design/mdi:account.svg?color=%236b7280" width="14" height="14" alt="">
                                    <strong><?php echo htmlspecialchars($lic['username']); ?></strong>
                                </div>
                                <small class="user-email"><?php echo htmlspecialchars($lic['email']); ?></small>
                            </td>
                            <td>
                                <div class="app-info">
                                    <img src="https://api.iconify.design/mdi:application.svg?color=%23667eea" width="14" height="14" alt="">
                                    <?php echo htmlspecialchars($lic['app_name']); ?>
                                </div>
                            </td>
                            <td>
                                <?php if ($lic['domain']): ?>
                                    <span class="domain-badge">
                                        <img src="https://api.iconify.design/mdi:web.svg?color=%23667eea" width="12" height="12" alt="">
                                        <?php echo htmlspecialchars($lic['domain']); ?>
                                    </span>
                                <?php else: ?>
                                    <span class="domain-empty">
                                        <img src="https://api.iconify.design/mdi:minus-circle.svg?color=%239ca3af" width="12" height="12" alt="">
                                        未绑定
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($lic['expire_date']): ?>
                                    <span class="expire-date">
                                        <img src="https://api.iconify.design/mdi:calendar.svg?color=%236b7280" width="12" height="12" alt="">
                                        <?php echo $lic['expire_date']; ?>
                                    </span>
                                <?php else: ?>
                                    <span class="expire-forever">
                                        <img src="https://api.iconify.design/mdi:infinity.svg?color=%2310b981" width="14" height="14" alt="">
                                        永久
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="status-badge status-<?php echo $lic['status'] ? 'active' : 'inactive'; ?>" id="status-badge-<?php echo $lic['id']; ?>">
                                    <span class="status-dot"></span>
                                    <?php echo $lic['status'] ? '有效' : '已禁用'; ?>
                                </span>
                            </td>
                            <td><?php echo date('Y-m-d H:i', strtotime($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']; ?>" title="<?php echo $lic['status'] ? '禁用' : '启用'; ?>">
                                    <?php if ($lic['status']): ?>
                                        <img src="https://api.iconify.design/mdi:eye-off.svg?color=%23ef4444" width="16" height="16" alt="">
                                    <?php else: ?>
                                        <img src="https://api.iconify.design/mdi:eye.svg?color=%2310b981" width="16" height="16" alt="">
                                    <?php endif; ?>
                                </button>
                                <button class="action-btn" onclick="showBindModal(<?php echo $lic['id']; ?>, '<?php echo $lic['license_code']; ?>', '<?php echo htmlspecialchars($lic['domain'] ?: ''); ?>')" title="绑定域名">
                                    <img src="https://api.iconify.design/mdi:web.svg?color=%23667eea" width="16" height="16" alt="">
                                </button>
                                <button class="action-btn delete-btn" onclick="deleteLicense(<?php echo $lic['id']; ?>)" title="删除">
                                    <img src="https://api.iconify.design/mdi:delete.svg?color=%23ef4444" width="16" height="16" alt="">
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <!-- 分页 -->
    <?php if ($total > $perpage): ?>
        <div class="pagination">
            <?php if ($page > 1): ?>
                <a href="?page=licenses&p=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&app_id=<?php echo $app_id; ?>&status=<?php echo $status; ?>" class="page-link page-prev">
                    <img src="https://api.iconify.design/mdi:chevron-left.svg?color=currentColor" width="16" height="16" alt="">
                </a>
            <?php endif; ?>
            
            <?php
            $total_pages = ceil($total / $perpage);
            $start_page = max(1, $page - 2);
            $end_page = min($total_pages, $page + 2);
            
            if ($start_page > 1): ?>
                <a href="?page=licenses&p=1&search=<?php echo urlencode($search); ?>&app_id=<?php echo $app_id; ?>&status=<?php echo $status; ?>" class="page-link">1</a>
                <?php if ($start_page > 2): ?>
                    <span class="page-ellipsis">...</span>
                <?php endif; ?>
            <?php endif; ?>
            
            <?php for ($i = $start_page; $i <= $end_page; $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; ?>
            
            <?php if ($end_page < $total_pages): ?>
                <?php if ($end_page < $total_pages - 1): ?>
                    <span class="page-ellipsis">...</span>
                <?php endif; ?>
                <a href="?page=licenses&p=<?php echo $total_pages; ?>&search=<?php echo urlencode($search); ?>&app_id=<?php echo $app_id; ?>&status=<?php echo $status; ?>" class="page-link"><?php echo $total_pages; ?></a>
            <?php endif; ?>
            
            <?php if ($page < $total_pages): ?>
                <a href="?page=licenses&p=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&app_id=<?php echo $app_id; ?>&status=<?php echo $status; ?>" class="page-link page-next">
                    <img src="https://api.iconify.design/mdi:chevron-right.svg?color=currentColor" width="16" height="16" alt="">
                </a>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

<!-- 绑定域名弹窗 -->
<div id="bindModal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3>
                <img src="https://api.iconify.design/mdi:web.svg?color=%23667eea" width="20" height="20" style="margin-right: 8px;" alt="">
                绑定域名
            </h3>
            <button type="button" class="modal-close" onclick="closeModal()">
                <img src="https://api.iconify.design/mdi:close.svg?color=%239ca3af" width="20" height="20" alt="">
            </button>
        </div>
        <form id="bindForm">
            <input type="hidden" name="license_id" id="bind_license_id">
            <div class="modal-body">
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:key.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                        授权码
                    </label>
                    <input type="text" id="bind_license_code" readonly>
                </div>
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:web.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                        绑定域名
                    </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" onclick="closeModal()">
                    <img src="https://api.iconify.design/mdi:close.svg?color=currentColor" width="16" height="16" style="margin-right: 4px;" alt="">
                    取消
                </button>
                <button type="submit" class="btn btn-primary">
                    <img src="https://api.iconify.design/mdi:content-save.svg?color=white" width="16" height="16" style="margin-right: 4px;" alt="">
                    保存绑定
                </button>
            </div>
        </form>
    </div>
</div>

<style>
/* 基础变量 */
:root {
    --primary-color: #667eea;
    --primary-hover: #5a67d8;
    --danger-color: #ef4444;
    --success-color: #10b981;
    --warning-color: #f59e0b;
    --bg-primary: #ffffff;
    --bg-secondary: #f9fafb;
    --text-primary: #1f2937;
    --text-secondary: #6b7280;
    --text-muted: #9ca3af;
    --border-color: #e5e7eb;
    --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
    --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    --radius-sm: 8px;
    --radius-md: 12px;
    --radius-lg: 16px;
}

.licenses-manager {
    max-width: 100%;
    padding: 4px;
}

/* 页面头部 */
.page-header {
    margin-bottom: 20px;
}
.page-header h2 {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0 0 6px;
}
.text-muted {
    color: var(--text-muted);
    font-size: 13px;
}

/* 统计卡片 */
.stats-mini {
    display: flex;
    gap: 16px;
    margin-bottom: 24px;
    flex-wrap: wrap;
}
.stat-mini-item {
    display: flex;
    align-items: center;
    gap: 10px;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.08) 0%, rgba(102, 126, 234, 0.02) 100%);
    padding: 12px 20px;
    border-radius: var(--radius-md);
    border: 1px solid rgba(102, 126, 234, 0.15);
}
.stat-mini-item .stat-label {
    font-size: 14px;
    color: var(--text-secondary);
}
.stat-mini-item .stat-value {
    font-size: 20px;
    font-weight: 700;
    color: var(--primary-color);
    margin-left: 4px;
}

/* 筛选栏 */
.filter-bar {
    margin-bottom: 24px;
}
.search-form .search-row {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
    align-items: center;
}
.search-input-wrapper {
    position: relative;
    flex: 2;
    min-width: 200px;
}
.search-input-wrapper .search-icon {
    position: absolute;
    left: 14px;
    top: 50%;
    transform: translateY(-50%);
    pointer-events: none;
}
.search-input-wrapper input {
    width: 100%;
    padding: 11px 16px 11px 44px;
    border: 1.5px solid var(--border-color);
    border-radius: var(--radius-md);
    background: var(--bg-primary);
    font-size: 14px;
    transition: all 0.2s;
}
.search-input-wrapper input:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.search-form select {
    padding: 11px 16px;
    border: 1.5px solid var(--border-color);
    border-radius: var(--radius-md);
    background: var(--bg-primary);
    font-size: 14px;
    min-width: 130px;
}

/* 按钮 */
.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 11px 20px;
    border-radius: var(--radius-md);
    font-size: 14px;
    font-weight: 500;
    text-decoration: none;
    cursor: pointer;
    transition: all 0.2s;
    border: 1px solid transparent;
    gap: 6px;
}
.btn-primary {
    background: var(--primary-color);
    color: white;
    box-shadow: 0 2px 4px rgba(102, 126, 234, 0.2);
}
.btn-primary:hover {
    background: var(--primary-hover);
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(102, 126, 234, 0.3);
}
.btn-secondary {
    background: var(--bg-primary);
    color: var(--text-primary);
    border-color: var(--border-color);
}
.btn-secondary:hover {
    background: var(--bg-secondary);
    border-color: var(--text-muted);
}

/* 表格 */
.table-wrapper {
    overflow-x: auto;
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    border: 1px solid var(--border-color);
    box-shadow: var(--shadow-sm);
}
.data-table {
    width: 100%;
    border-collapse: collapse;
    min-width: 1100px;
}
.data-table th {
    padding: 16px 16px;
    text-align: left;
    font-weight: 600;
    font-size: 13px;
    color: var(--text-secondary);
    background: var(--bg-secondary);
    border-bottom: 1px solid var(--border-color);
    white-space: nowrap;
    text-transform: uppercase;
    letter-spacing: 0.3px;
}
.data-table td {
    padding: 16px;
    border-bottom: 1px solid var(--border-color);
    font-size: 14px;
    vertical-align: middle;
}
.data-table tbody tr {
    transition: background 0.2s;
}
.data-table tbody tr:hover {
    background: var(--bg-secondary);
}
.data-table tbody tr:last-child td {
    border-bottom: none;
}

/* 单元格样式 */
.license-code {
    display: flex;
    align-items: center;
    gap: 8px;
}
.license-code code {
    font-family: 'Monaco', 'Menlo', 'Courier New', monospace;
    font-size: 13px;
    background: var(--bg-secondary);
    padding: 6px 12px;
    border-radius: var(--radius-sm);
    color: var(--primary-color);
    border: 1px solid var(--border-color);
}
.copy-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 28px;
    height: 28px;
    background: var(--bg-secondary);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    cursor: pointer;
    transition: all 0.2s;
}
.copy-btn:hover {
    background: var(--bg-primary);
    border-color: var(--primary-color);
}
.user-info {
    display: flex;
    align-items: center;
    gap: 6px;
    margin-bottom: 4px;
}
.user-email {
    color: var(--text-muted);
    font-size: 12px;
}
.app-info {
    display: flex;
    align-items: center;
    gap: 6px;
}
.domain-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: #e0e7ff;
    color: #4338ca;
    padding: 4px 12px;
    border-radius: 30px;
    font-size: 12px;
    font-weight: 500;
}
.domain-empty {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    color: var(--text-muted);
    font-size: 12px;
}
.expire-date {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    color: var(--text-secondary);
}
.expire-forever {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    color: var(--success-color);
}

/* 状态徽章 */
.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 5px 12px;
    border-radius: 30px;
    font-size: 12px;
    font-weight: 500;
    white-space: nowrap;
}
.status-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
}
.status-active {
    background: #d1fae5;
    color: #065f46;
}
.status-active .status-dot {
    background: #10b981;
    box-shadow: 0 0 0 2px rgba(16, 185, 129, 0.2);
}
.status-inactive {
    background: #fee2e2;
    color: #991b1b;
}
.status-inactive .status-dot {
    background: #ef4444;
    box-shadow: 0 0 0 2px rgba(239, 68, 68, 0.2);
}

/* 操作按钮 */
.action-buttons {
    display: flex;
    gap: 8px;
}
.action-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 34px;
    height: 34px;
    background: var(--bg-secondary);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    cursor: pointer;
    transition: all 0.2s;
}
.action-btn:hover {
    background: var(--bg-primary);
    border-color: var(--primary-color);
    transform: translateY(-1px);
    box-shadow: var(--shadow-sm);
}
.delete-btn:hover {
    border-color: var(--danger-color);
    background: #fef2f2;
}

/* 空状态 */
.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    text-align: center;
}
.empty-state img {
    opacity: 0.4;
    margin-bottom: 16px;
}
.empty-state p {
    color: var(--text-muted);
    font-size: 15px;
    margin: 0;
}

/* 分页 */
.pagination {
    display: flex;
    gap: 6px;
    justify-content: center;
    margin-top: 28px;
}
.page-link {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 38px;
    height: 38px;
    padding: 0 8px;
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    text-decoration: none;
    color: var(--text-primary);
    font-size: 14px;
    font-weight: 500;
    background: var(--bg-primary);
    transition: all 0.2s;
}
.page-link:hover {
    border-color: var(--primary-color);
    color: var(--primary-color);
    background: rgba(102, 126, 234, 0.05);
}
.page-link.active {
    background: var(--primary-color);
    color: white;
    border-color: var(--primary-color);
}
.page-ellipsis {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 38px;
    height: 38px;
    color: var(--text-muted);
}

/* 弹窗 */
.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(4px);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
    animation: fadeIn 0.2s ease;
}
@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}
.modal-content {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    width: 90%;
    max-width: 450px;
    box-shadow: var(--shadow-lg);
    animation: slideUp 0.3s ease;
}
@keyframes slideUp {
    from { opacity: 0; transform: translateY(20px); }
    to { opacity: 1; transform: translateY(0); }
}
.modal-header {
    padding: 20px 24px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.modal-header h3 {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: 600;
    margin: 0;
}
.modal-close {
    background: none;
    border: none;
    cursor: pointer;
    padding: 4px;
    border-radius: var(--radius-sm);
    transition: background 0.2s;
    display: flex;
}
.modal-close:hover {
    background: var(--bg-secondary);
}
.modal-body {
    padding: 24px;
}
.modal-footer {
    padding: 16px 24px 24px;
    display: flex;
    gap: 12px;
    justify-content: flex-end;
}
.form-group {
    margin-bottom: 20px;
}
.form-group label {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    font-weight: 500;
    font-size: 14px;
    color: var(--text-primary);
}
.form-group input {
    width: 100%;
    padding: 12px 16px;
    border: 1.5px solid var(--border-color);
    border-radius: var(--radius-md);
    font-size: 14px;
    background: var(--bg-primary);
    transition: all 0.2s;
}
.form-group input:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.form-group input[readonly] {
    background: var(--bg-secondary);
    cursor: not-allowed;
}
.form-group small {
    display: block;
    margin-top: 6px;
    font-size: 12px;
    color: var(--text-muted);
}

/* 加载动画 */
.loading-spinner {
    display: inline-block;
    width: 16px;
    height: 16px;
    border: 2px solid rgba(102, 126, 234, 0.3);
    border-radius: 50%;
    border-top-color: var(--primary-color);
    animation: spin 0.6s linear infinite;
}
@keyframes spin {
    to { transform: rotate(360deg); }
}

/* 响应式 */
@media (max-width: 768px) {
    .search-form .search-row {
        flex-direction: column;
        align-items: stretch;
    }
    .search-input-wrapper {
        min-width: 100%;
    }
}
</style>

<script>
// 更新统计卡片
function updateStatsDisplay(activeChange, inactiveChange, totalChange = 0) {
    const statValues = document.querySelectorAll('.stat-mini-item .stat-value');
    const totalStat = statValues[0];  // 总授权数
    const activeStat = statValues[1]; // 有效授权
    const inactiveStat = statValues[2]; // 已禁用
    
    if (totalStat) {
        let totalCount = parseInt(totalStat.innerText) || 0;
        totalStat.innerText = Math.max(0, totalCount + totalChange);
    }
    if (activeStat) {
        let activeCount = parseInt(activeStat.innerText) || 0;
        activeStat.innerText = Math.max(0, activeCount + activeChange);
    }
    if (inactiveStat) {
        let inactiveCount = parseInt(inactiveStat.innerText) || 0;
        inactiveStat.innerText = Math.max(0, inactiveCount + inactiveChange);
    }
}

function copyToClipboard(text) {
    navigator.clipboard?.writeText(text).then(() => {
        window.showToast && 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 && window.showToast('授权码已复制', 'success');
    });
}

function toggleStatus(btn, licenseId, currentStatus) {
    const newStatus = currentStatus == 1 ? 0 : 1;
    const statusBadge = document.getElementById('status-badge-' + licenseId);
    const originalHtml = btn.innerHTML;
    
    btn.innerHTML = '<span class="loading-spinner"></span>';
    btn.disabled = true;
    
    fetch('/api/admin_toggle_license_status.php', {
        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) {
                statusBadge.className = 'status-badge status-active';
                statusBadge.innerHTML = '<span class="status-dot"></span>有效';
                btn.innerHTML = '<img src="https://api.iconify.design/mdi:eye-off.svg?color=%23ef4444" width="16" height="16" alt="">';
                btn.setAttribute('data-status', '1');
                btn.setAttribute('title', '禁用');
                // 启用授权：有效+1，禁用-1
                updateStatsDisplay(1, -1);
            } else {
                statusBadge.className = 'status-badge status-inactive';
                statusBadge.innerHTML = '<span class="status-dot"></span>已禁用';
                btn.innerHTML = '<img src="https://api.iconify.design/mdi:eye.svg?color=%2310b981" width="16" height="16" alt="">';
                btn.setAttribute('data-status', '0');
                btn.setAttribute('title', '启用');
                // 禁用授权：有效-1，禁用+1
                updateStatsDisplay(-1, 1);
            }
            window.showToast && window.showToast('状态已更新', 'success');
        } else {
            window.showToast && window.showToast(data.message || '操作失败', 'error');
        }
        btn.disabled = false;
    })
    .catch(error => {
        console.error('错误:', error);
        window.showToast && window.showToast('网络错误', 'error');
        btn.innerHTML = originalHtml;
        btn.disabled = false;
    });
}

function deleteLicense(licenseId) {
    if (!confirm('确定要删除此授权码吗？此操作不可恢复。')) return;
    
    const row = document.getElementById('license-row-' + licenseId);
    const deleteBtn = row.querySelector('.delete-btn');
    const originalHtml = deleteBtn.innerHTML;
    
    // 获取当前授权状态
    const statusBadge = document.getElementById('status-badge-' + licenseId);
    const isActive = statusBadge.classList.contains('status-active');
    
    deleteBtn.innerHTML = '<span class="loading-spinner"></span>';
    deleteBtn.disabled = true;
    
    fetch('/api/admin_delete_license.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `id=${licenseId}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 更新统计：总数-1，根据状态减少对应计数
            if (isActive) {
                updateStatsDisplay(-1, 0, -1);
            } else {
                updateStatsDisplay(0, -1, -1);
            }
            
            row.style.transition = 'opacity 0.3s';
            row.style.opacity = '0';
            setTimeout(() => {
                row.remove();
                window.showToast && window.showToast('删除成功', 'success');
                if (document.querySelectorAll('#licensesTable tbody tr').length === 0) {
                    location.reload();
                }
            }, 300);
        } else {
            window.showToast && window.showToast(data.message || '删除失败', 'error');
            deleteBtn.innerHTML = originalHtml;
            deleteBtn.disabled = false;
        }
    })
    .catch(error => {
        console.error('错误:', error);
        window.showToast && window.showToast('网络错误', 'error');
        deleteBtn.innerHTML = originalHtml;
        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.getElementById('bindForm')?.reset();
}

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;
    });
}

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('.modal-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();
        });
    }
    
    // ESC 关闭弹窗
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') 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 && 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 && window.showToast('域名格式不正确', 'error');
            return;
        }
        
        const originalHtml = submitBtn.innerHTML;
        submitBtn.innerHTML = '<span class="loading-spinner"></span> 保存中...';
        submitBtn.disabled = true;
        
        fetch('/api/admin_bind_license_domain.php', {
            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(4)');
                domainCell.innerHTML = `<span class="domain-badge"><img src="https://api.iconify.design/mdi:web.svg?color=%23667eea" width="12" height="12" alt=""> ${escapeHtml(domain)}</span>`;
                window.showToast && window.showToast('域名绑定成功', 'success');
                closeModal();
            } else {
                window.showToast && window.showToast(data.message || '绑定失败', 'error');
            }
            submitBtn.innerHTML = originalHtml;
            submitBtn.disabled = false;
        })
        .catch(error => {
            console.error('错误:', error);
            window.showToast && window.showToast('网络错误', 'error');
            submitBtn.innerHTML = originalHtml;
            submitBtn.disabled = false;
        });
    });
});
</script>