<?php
ob_start();
require_once __DIR__ . '/../../config.php';

if (!isAdmin()) {
    header('Location: /m/');
    exit;
}

$user = currentUser();
$message = '';
$error = '';

// 批量删除卡密
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'batch_delete') {
    $ids = $_POST['ids'] ?? [];
    if (!empty($ids)) {
        $id_list = implode(',', array_map('intval', $ids));
        $count_result = $db->fetchOne("SELECT COUNT(*) as cnt FROM card_codes WHERE id IN ($id_list) AND status = 0");
        $deleted = $count_result['cnt'] ?? 0;
        $db->query("DELETE FROM card_codes WHERE id IN ($id_list) AND status = 0");
        $message = "成功删除 {$deleted} 张卡密";
    }
}

// 生成卡密
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'generate') {
    $amount = floatval($_POST['amount']);
    $quantity = intval($_POST['quantity']);
    $expire_days = intval($_POST['expire_days']);
    
    if ($amount <= 0) {
        $error = '面额必须大于0';
    } elseif ($quantity <= 0 || $quantity > 500) {
        $error = '数量必须在1-500之间';
    } else {
        $expire_at = $expire_days > 0 ? date('Y-m-d H:i:s', strtotime("+{$expire_days} days")) : null;
        $success_count = 0;
        
        for ($i = 0; $i < $quantity; $i++) {
            $card_code = strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 16));
            $card_code = substr($card_code, 0, 4) . '-' . substr($card_code, 4, 4) . '-' . substr($card_code, 8, 4) . '-' . substr($card_code, 12, 4);
            
            $sql = "INSERT INTO card_codes (card_code, amount, created_by, expire_at) 
                    VALUES ('$card_code', $amount, {$user['id']}, " . ($expire_at ? "'$expire_at'" : "NULL") . ")";
            if ($db->query($sql)) {
                $success_count++;
            }
        }
        $message = "成功生成 {$success_count} 张卡密，面额 ¥{$amount}";
    }
}

// 删除单张卡密
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $db->query("DELETE FROM card_codes WHERE id = $id AND status = 0");
    $message = '删除成功';
}

// 获取卡密列表
$page_num = isset($_GET['p']) ? intval($_GET['p']) : 1;
$perpage = 15;
$status = isset($_GET['status']) ? intval($_GET['status']) : -1;
$offset = ($page_num - 1) * $perpage;

$where = "1=1";
if ($status >= 0) $where .= " AND status = $status";

$total = $db->fetchOne("SELECT COUNT(*) as cnt FROM card_codes WHERE $where")['cnt'];
$cards = $db->fetchAll("SELECT * FROM card_codes WHERE $where ORDER BY id DESC LIMIT $offset, $perpage");

$stats = [
    'total' => $db->fetchOne("SELECT COUNT(*) as cnt FROM card_codes")['cnt'],
    'unused' => $db->fetchOne("SELECT COUNT(*) as cnt FROM card_codes WHERE status = 0")['cnt'],
    'used' => $db->fetchOne("SELECT COUNT(*) as cnt FROM card_codes WHERE status = 1")['cnt'],
];
?>

<?php if ($message): ?>
<div class="card" style="background: #d1fae5; color: #065f46; padding: 12px;">
    <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="18" height="18" alt=""> <?php echo $message; ?>
</div>
<?php endif; ?>

<?php if ($error): ?>
<div class="card" style="background: #fef2f2; color: #991b1b; padding: 12px;">
    <img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23ef4444" width="18" height="18" alt=""> <?php echo $error; ?>
</div>
<?php endif; ?>

<!-- 生成卡密 -->
<div class="card">
    <h3 style="margin-bottom: 12px; font-size: 15px; display: flex; gap: 8px;">
        <img src="https://api.iconify.design/mdi:plus-circle.svg?color=%23667eea" width="20" height="20" alt="">
        生成卡密
    </h3>
    <form method="POST">
        <input type="hidden" name="action" value="generate">
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 12px;">
            <input type="number" name="amount" placeholder="面额" step="0.01" required style="padding: 10px; border:1px solid #e5e7eb; border-radius:8px;">
            <input type="number" name="quantity" placeholder="数量" value="10" required style="padding: 10px; border:1px solid #e5e7eb; border-radius:8px;">
        </div>
        <select name="expire_days" style="width:100%; padding: 10px; border:1px solid #e5e7eb; border-radius:8px; margin-bottom:12px;">
            <option value="0">永久有效</option>
            <option value="30">30天</option>
            <option value="90">90天</option>
            <option value="365">365天</option>
        </select>
        <button type="submit" class="btn btn-primary btn-block">
            <img src="https://api.iconify.design/mdi:ticket.svg?color=white" width="18" height="18" alt="">
            生成卡密
        </button>
    </form>
</div>

<!-- 统计 -->
<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px;">
    <div class="card" style="text-align: center; padding: 12px;">
        <div style="font-size: 20px; font-weight: 700;"><?php echo $stats['total']; ?></div>
        <div style="font-size: 12px; color: #999;">总数</div>
    </div>
    <div class="card" style="text-align: center; padding: 12px;">
        <div style="font-size: 20px; font-weight: 700; color: #f59e0b;"><?php echo $stats['unused']; ?></div>
        <div style="font-size: 12px; color: #999;">未使用</div>
    </div>
    <div class="card" style="text-align: center; padding: 12px;">
        <div style="font-size: 20px; font-weight: 700; color: #10b981;"><?php echo $stats['used']; ?></div>
        <div style="font-size: 12px; color: #999;">已使用</div>
    </div>
</div>

<!-- 筛选和批量操作 -->
<div style="display: flex; gap: 8px; margin: 12px 0;">
    <a href="?page=card_codes&status=-1" class="btn" style="background:<?php echo $status==-1?'#667eea':'#f5f5f5'; ?>; color:<?php echo $status==-1?'white':'#666'; ?>; flex:1;">全部</a>
    <a href="?page=card_codes&status=0" class="btn" style="background:<?php echo $status==0?'#667eea':'#f5f5f5'; ?>; color:<?php echo $status==0?'white':'#666'; ?>; flex:1;">未使用</a>
    <a href="?page=card_codes&status=1" class="btn" style="background:<?php echo $status==1?'#667eea':'#f5f5f5'; ?>; color:<?php echo $status==1?'white':'#666'; ?>; flex:1;">已使用</a>
</div>

<!-- 批量操作栏 -->
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
    <label style="display: flex; align-items: center; gap: 6px;">
        <input type="checkbox" id="selectAll" onchange="toggleSelectAll(this)">
        <span style="font-size: 13px;">全选</span>
    </label>
    <button class="btn" style="background:#fef2f2; color:#ef4444;" onclick="batchDelete()">
        <img src="https://api.iconify.design/mdi:delete.svg?color=%23ef4444" width="16" height="16" alt="">
        批量删除
    </button>
</div>

<!-- 卡密列表 -->
<form id="batchForm" method="POST">
    <input type="hidden" name="action" value="batch_delete">
    <div id="selectedIds"></div>
</form>

<?php foreach ($cards as $card): ?>
<div class="card">
    <div style="display: flex; align-items: center; gap: 10px;">
        <input type="checkbox" class="card-checkbox" value="<?php echo $card['id']; ?>" <?php echo $card['status'] ? 'disabled' : ''; ?>>
        <div style="flex:1;">
            <code style="font-size: 14px; background: #f5f5f5; padding: 4px 8px; border-radius: 6px; display: block; margin-bottom: 8px;"><?php echo $card['card_code']; ?></code>
            <div style="display: flex; gap: 16px; font-size: 13px; color: #666;">
                <span><img src="https://api.iconify.design/mdi:cash.svg?color=%2310b981" width="14" height="14" alt=""> ¥<?php echo number_format($card['amount'], 2); ?></span>
                <span><img src="https://api.iconify.design/mdi:calendar.svg?color=%23666" width="14" height="14" alt=""> <?php echo $card['expire_at'] ? date('Y-m-d', strtotime($card['expire_at'])) : '永久'; ?></span>
            </div>
        </div>
        <span style="padding: 4px 10px; border-radius: 20px; font-size: 12px;
                     <?php echo $card['status'] ? 'background:#d1fae5;color:#065f46;' : 'background:#fef3c7;color:#92400e;'; ?>">
            <?php echo $card['status'] ? '已使用' : '未使用'; ?>
        </span>
    </div>
    <?php if ($card['status'] == 0): ?>
    <div style="margin-top: 10px; display: flex; gap: 8px;">
        <button onclick="copyToClipboard('<?php echo $card['card_code']; ?>')" style="flex:1; padding: 8px; background: #f5f5f5; border: none; border-radius: 6px; font-size: 13px;">
            <img src="https://api.iconify.design/mdi:content-copy.svg?color=%23666" width="14" height="14" alt=""> 复制
        </button>
        <a href="?page=card_codes&delete=<?php echo $card['id']; ?>" onclick="return confirm('确定删除？')" style="flex:1; padding: 8px; background: #fef2f2; border-radius: 6px; text-decoration: none; color: #ef4444; font-size: 13px; text-align: center;">
            <img src="https://api.iconify.design/mdi:delete.svg?color=%23ef4444" width="14" height="14" alt=""> 删除
        </a>
    </div>
    <?php endif; ?>
</div>
<?php endforeach; ?>

<?php if (empty($cards)): ?>
<div class="card" style="text-align: center; padding: 40px;">
    <img src="https://api.iconify.design/mdi:ticket-outline.svg?color=%23999" width="48" height="48" alt="">
    <p style="color: #999;">暂无卡密</p>
</div>
<?php endif; ?>

<!-- 分页 -->
<?php if ($total > $perpage): ?>
<div style="display: flex; justify-content: center; gap: 8px; margin-top: 16px;">
    <?php if ($page_num > 1): ?>
        <a href="?page=card_codes&status=<?php echo $status; ?>&p=<?php echo $page_num-1; ?>" class="btn" style="background:#f5f5f5;">上一页</a>
    <?php endif; ?>
    <span style="padding: 10px 16px;"><?php echo $page_num; ?>/<?php echo ceil($total/$perpage); ?></span>
    <?php if ($page_num < ceil($total/$perpage)): ?>
        <a href="?page=card_codes&status=<?php echo $status; ?>&p=<?php echo $page_num+1; ?>" class="btn" style="background:#f5f5f5;">下一页</a>
    <?php endif; ?>
</div>
<?php endif; ?>

<script>
function copyToClipboard(text) {
    navigator.clipboard?.writeText(text).then(() => showToast('已复制'));
}

function toggleSelectAll(checkbox) {
    document.querySelectorAll('.card-checkbox:not(:disabled)').forEach(cb => cb.checked = checkbox.checked);
}

function batchDelete() {
    const checked = document.querySelectorAll('.card-checkbox:checked');
    if (checked.length === 0) {
        showToast('请选择要删除的卡密', 'error');
        return;
    }
    if (!confirm('确定删除选中的 ' + checked.length + ' 张卡密吗？')) return;
    
    const form = document.getElementById('batchForm');
    const container = document.getElementById('selectedIds');
    container.innerHTML = '';
    checked.forEach(cb => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'ids[]';
        input.value = cb.value;
        container.appendChild(input);
    });
    form.submit();
}
</script>