<?php
// require_once '../../config.php';
requireAdmin();

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

// 生成卡密
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 === 'NULL' ? 'NULL' : "'$expire_at'") . ")";
            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 = isset($_GET['p']) ? intval($_GET['p']) : 1;
$perpage = 20;
$offset = ($page - 1) * $perpage;

$status_filter = isset($_GET['status']) ? intval($_GET['status']) : -1;
$status_sql = $status_filter >= 0 ? "AND status = $status_filter" : "";

$total = $db->fetchOne("SELECT COUNT(*) as cnt FROM card_codes WHERE 1=1 $status_sql")['cnt'];
$cards = $db->fetchAll("SELECT * FROM card_codes WHERE 1=1 $status_sql ORDER BY id DESC LIMIT $offset, $perpage");
?>
<!--<?php include '../../includes/admin_header.php'; ?>-->
<div class="admin-container">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h2>🎫 卡密充值管理</h2>
    </div>
    
    <?php if ($message): ?>
        <div class="alert alert-success">✅ <?php echo $message; ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="alert alert-error">❌ <?php echo $error; ?></div>
    <?php endif; ?>
    
    <!-- 生成卡密 -->
    <div class="card" style="margin-bottom: 30px;">
        <h3>生成卡密</h3>
        <form method="POST" class="form-inline" style="display: flex; gap: 15px; flex-wrap: wrap; margin-top: 15px;">
            <input type="hidden" name="action" value="generate">
            <div>
                <label>面额 (元)</label>
                <input type="number" name="amount" step="0.01" min="0.01" required style="width: 120px; padding: 8px;">
            </div>
            <div>
                <label>数量</label>
                <input type="number" name="quantity" min="1" max="500" value="10" required style="width: 100px; padding: 8px;">
            </div>
            <div>
                <label>有效期 (天)</label>
                <select name="expire_days" style="padding: 8px;">
                    <option value="0">永久</option>
                    <option value="30">30天</option>
                    <option value="90">90天</option>
                    <option value="180">180天</option>
                    <option value="365">365天</option>
                </select>
            </div>
            <div style="display: flex; align-items: flex-end;">
                <button type="submit" class="btn btn-primary">生成卡密</button>
            </div>
        </form>
    </div>
    
    <!-- 筛选 -->
    <div style="margin-bottom: 20px;">
        <a href="?status=-1" class="btn <?php echo $status_filter == -1 ? 'btn-primary' : 'btn-secondary'; ?>">全部</a>
        <a href="?status=0" class="btn <?php echo $status_filter == 0 ? 'btn-primary' : 'btn-secondary'; ?>">未使用</a>
        <a href="?status=1" class="btn <?php echo $status_filter == 1 ? 'btn-primary' : 'btn-secondary'; ?>">已使用</a>
    </div>
    
    <!-- 卡密列表 -->
    <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>卡密</th>
                    <th>面额</th>
                    <th>状态</th>
                    <th>使用者</th>
                    <th>使用时间</th>
                    <th>过期时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($cards as $card): ?>
                <tr>
                    <td><?php echo $card['id']; ?></td>
                    <td><code><?php echo $card['card_code']; ?></code></td>
                    <td>¥<?php echo number_format($card['amount'], 2); ?></td>
                    <td>
                        <?php if ($card['status'] == 1): ?>
                            <span class="badge badge-success">已使用</span>
                        <?php else: ?>
                            <span class="badge badge-warning">未使用</span>
                        <?php endif; ?>
                    </td>
                    <td><?php echo $card['used_by'] ? $card['used_by'] : '-'; ?></td>
                    <td><?php echo $card['used_at'] ?: '-'; ?></td>
                    <td><?php echo $card['expire_at'] ?: '永久'; ?></td>
                    <td>
                        <?php if ($card['status'] == 0): ?>
                            <a href="?delete=<?php echo $card['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('确定删除？')">删除</a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($cards)): ?>
                    <tr><td colspan="8" style="text-align: center;">暂无数据</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <!-- 分页 -->
    <?php if ($total > $perpage): ?>
    <div class="pagination" style="margin-top: 20px;">
        <?php for ($i = 1; $i <= ceil($total / $perpage); $i++): ?>
            <a href="?p=<?php echo $i; ?>&status=<?php echo $status_filter; ?>" class="btn btn-sm <?php echo $i == $page ? 'btn-primary' : 'btn-secondary'; ?>"><?php echo $i; ?></a>
        <?php endfor; ?>
    </div>
    <?php endif; ?>
</div>

<style>
.form-inline div {
    display: flex;
    flex-direction: column;
    gap: 5px;
}
.badge {
    padding: 2px 8px;
    border-radius: 20px;
    font-size: 11px;
}
.badge-success { background: #10b981; color: white; }
.badge-warning { background: #f59e0b; color: white; }
</style>
<!--<?php include '../../includes/admin_footer.php'; ?>-->