<?php
session_start();

// ================= 引入现有配置 =================
require_once dirname(__FILE__) . '/../config.php';
// =================================================

// 配置管理密码
$ADMIN_PASSWORD = '090813';

// 登录处理
$is_logged_in = isset($_SESSION['card_admin']) && $_SESSION['card_admin'] === true;
$msg = '';
$msg_type = 'error';

// --- 1. 撤销逻辑 (扣除金币，卡密变回未使用) ---
if ($is_logged_in && isset($_GET['action']) && $_GET['action'] === 'revoke' && isset($_GET['id'])) {
    $card_id = intval($_GET['id']);
    
    $stmt = mysqli_prepare($conn, "SELECT * FROM cards WHERE id = ?");
    mysqli_stmt_bind_param($stmt, "i", $card_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $card = mysqli_fetch_assoc($result);
    
    // 只有已使用的卡密才能撤销
    if ($card && $card['status'] == 1 && !empty($card['used_by'])) {
        mysqli_begin_transaction($conn);
        try {
            // 扣除用户小马币
            $stmt_user = mysqli_prepare($conn, "UPDATE users SET coins = coins - ? WHERE id = ?");
            mysqli_stmt_bind_param($stmt_user, "ii", $card['value'], $card['used_by']);
            mysqli_stmt_execute($stmt_user);
            
            // 重置卡密状态为未使用，但保留 used_by 记录以便后悔时恢复
            // 注意：这里我们将 status 改为 0，但不清空 used_by
            $stmt_card = mysqli_prepare($conn, "UPDATE cards SET status = 0 WHERE id = ?");
            mysqli_stmt_bind_param($stmt_card, "i", $card_id);
            mysqli_stmt_execute($stmt_card);
            
            mysqli_commit($conn);
            $msg = "撤销成功！已扣除用户 ID: {$card['used_by']} 的 {$card['value']} 个币。如误操作请点击恢复。";
            $msg_type = 'success';
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $msg = "撤销失败：系统错误。";
        }
    } else {
        $msg = "撤销失败：卡密不存在或未处于已使用状态。";
    }
}

// --- 2. 恢复逻辑 (补回金币，卡密变回已使用) ---
if ($is_logged_in && isset($_GET['action']) && $_GET['action'] === 'restore' && isset($_GET['id'])) {
    $card_id = intval($_GET['id']);
    
    $stmt = mysqli_prepare($conn, "SELECT * FROM cards WHERE id = ?");
    mysqli_stmt_bind_param($stmt, "i", $card_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $card = mysqli_fetch_assoc($result);
    
    // 只有未使用的卡密，且有记录使用者ID的才能恢复
    if ($card && $card['status'] == 0 && !empty($card['used_by'])) {
        mysqli_begin_transaction($conn);
        try {
            // 补回用户小马币
            $stmt_user = mysqli_prepare($conn, "UPDATE users SET coins = coins + ? WHERE id = ?");
            mysqli_stmt_bind_param($stmt_user, "ii", $card['value'], $card['used_by']);
            mysqli_stmt_execute($stmt_user);
            
            // 恢复卡密状态为已使用
            $stmt_card = mysqli_prepare($conn, "UPDATE cards SET status = 1 WHERE id = ?");
            mysqli_stmt_bind_param($stmt_card, "i", $card_id);
            mysqli_stmt_execute($stmt_card);
            
            mysqli_commit($conn);
            $msg = "恢复成功！已补发用户 ID: {$card['used_by']} 的 {$card['value']} 个币。";
            $msg_type = 'success';
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $msg = "恢复失败：系统错误。";
        }
    } else {
        $msg = "恢复失败：找不到该卡密的使用记录，无法恢复。";
    }
}

// 登录验证
if (!$is_logged_in && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login_password'])) {
    if ($_POST['login_password'] === $ADMIN_PASSWORD) {
        $_SESSION['card_admin'] = true;
        $is_logged_in = true;
    } else {
        $msg = '密码错误';
    }
}

// 生成卡密函数
function generateCardCode($length = 16) {
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $code = '';
    for ($i = 0; $i < $length; $i++) {
        $code .= $chars[rand(0, strlen($chars) - 1)];
    }
    return $code;
}

// 生成卡密处理
$new_cards = [];
if ($is_logged_in && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate'])) {
    $count = intval($_POST['count'] ?? 1);
    $value = intval($_POST['value'] ?? 10);
    $expire_days = intval($_POST['expire_days'] ?? 30);
    
    $count = min($count, 100); 
    $expire_time = date('Y-m-d H:i:s', strtotime("+{$expire_days} days"));
    
    for ($i = 0; $i < $count; $i++) {
        $code = generateCardCode();
        $stmt = mysqli_prepare($conn, "INSERT INTO cards (card_code, value, expire_time) VALUES (?, ?, ?)");
        mysqli_stmt_bind_param($stmt, "sis", $code, $value, $expire_time);
        mysqli_stmt_execute($stmt);
        $new_cards[] = ['code' => $code, 'value' => $value, 'expire' => $expire_time];
    }
    $msg = "成功生成 {$count} 张卡密！";
    $msg_type = 'success';
}

// 查询最近卡密
$recent_cards = [];
if ($is_logged_in) {
    $res = mysqli_query($conn, "SELECT * FROM cards ORDER BY id DESC LIMIT 50");
    while ($row = mysqli_fetch_assoc($res)) {
        $recent_cards[] = $row;
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>卡密生成系统</title>
    <style>
        * { box-sizing: border-box; }
        body { background: #1a1a2e; color: #eee; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; margin: 0; padding: 20px; min-height: 100vh; }
        .container { max-width: 1000px; margin: 0 auto; }
        
        .login-box { background: #16213e; padding: 40px; border-radius: 10px; max-width: 400px; margin: 100px auto; text-align: center; }
        .login-box h2 { margin-bottom: 20px; color: #e94560; }
        .login-box input { width: 100%; padding: 12px; border: none; border-radius: 5px; margin-bottom: 15px; font-size: 16px; }
        .login-box button { width: 100%; padding: 12px; background: #e94560; color: white; border: none; border-radius: 5px; font-size: 16px; cursor: pointer; }
        
        .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; }
        .header h1 { margin: 0; color: #e94560; }
        .btn-logout { background: #0f3460; color: #eee; padding: 8px 15px; border-radius: 5px; text-decoration: none; }
        
        .card-grid { display: grid; grid-template-columns: 350px 1fr; gap: 20px; }
        @media (max-width: 800px) { .card-grid { grid-template-columns: 1fr; } }
        
        .panel { background: #16213e; border-radius: 10px; padding: 20px; }
        .panel h3 { margin-top: 0; color: #e94560; border-bottom: 1px solid #0f3460; padding-bottom: 10px; }
        
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 5px; color: #aaa; font-size: 14px; }
        .form-group input { width: 100%; padding: 10px; border: 1px solid #0f3460; background: #0f3460; color: #eee; border-radius: 5px; font-size: 14px; }
        
        .btn-generate { width: 100%; padding: 12px; background: linear-gradient(135deg, #e94560, #ff6b6b); color: white; border: none; border-radius: 5px; font-size: 16px; font-weight: bold; cursor: pointer; }
        .btn-generate:hover { opacity: 0.9; }
        
        .btn-copy { background: #0f3460; color: #eee; padding: 5px 10px; border: none; border-radius: 3px; cursor: pointer; font-size: 12px; }
        .btn-copy:hover { background: #1a1a2e; }

        /* 按钮样式区分 */
        .btn-revoke { background: #ff6b6b; color: white; padding: 5px 10px; border: none; border-radius: 3px; cursor: pointer; font-size: 12px; text-decoration: none; display: inline-block; }
        .btn-revoke:hover { opacity: 0.8; }

        .btn-restore { background: #4ecca3; color: #1a1a2e; padding: 5px 10px; border: none; border-radius: 3px; cursor: pointer; font-size: 12px; text-decoration: none; display: inline-block; font-weight: bold; }
        .btn-restore:hover { opacity: 0.8; }
        
        .table-container { width: 100%; overflow-x: auto; }
        table { width: 100%; border-collapse: collapse; margin-top: 10px; min-width: 600px; }
        th, td { padding: 10px; text-align: left; border-bottom: 1px solid #0f3460; font-size: 13px; }
        th { color: #e94560; }
        .status-0 { color: #4ecca3; }
        .status-1 { color: #ff6b6b; }
        
        .msg { padding: 12px; border-radius: 5px; margin-bottom: 20px; text-align: center; }
        .msg-error { background: rgba(255, 107, 107, 0.2); border: 1px solid #ff6b6b; color: #ff6b6b; }
        .msg-success { background: rgba(78, 204, 163, 0.2); border: 1px solid #4ecca3; color: #4ecca3; }
        
        .new-cards-list { max-height: 300px; overflow-y: auto; background: #0f3460; border-radius: 5px; padding: 10px; margin-top: 10px; }
        .new-card-item { padding: 8px; border-bottom: 1px dashed #16213e; display: flex; justify-content: space-between; align-items: center; }
        .new-card-item:last-child { border-bottom: none; }

        .user-badge { background: #e94560; color: white; padding: 2px 6px; border-radius: 3px; font-size: 11px; margin-left: 5px; }
        .user-badge-revoked { background: #aaa; color: white; padding: 2px 6px; border-radius: 3px; font-size: 11px; margin-left: 5px; text-decoration: line-through; }
    </style>
</head>
<body>
    <div class="container">
        <?php if (!$is_logged_in): ?>
            <div class="login-box">
                <h2>🔐 管理员登录</h2>
                <?php if ($msg): ?><div class="msg msg-error"><?php echo $msg; ?></div><?php endif; ?>
                <form method="POST">
                    <input type="password" name="login_password" placeholder="请输入管理密码" required>
                    <button type="submit">登录</button>
                </form>
            </div>
        <?php else: ?>
            <div class="header">
                <h1>🎫 卡密生成系统</h1>
                <a href="?logout=1" class="btn-logout">退出登录</a>
            </div>
            
            <?php if (isset($_GET['logout'])) { session_destroy(); header('Location: sckm.php'); exit; } ?>
            <?php if ($msg): ?><div class="msg msg-<?php echo $msg_type; ?>"><?php echo $msg; ?></div><?php endif; ?>
            
            <div class="card-grid">
                <!-- 左侧：生成卡密 -->
                <div class="panel">
                    <h3>生成新卡密</h3>
                    <form method="POST">
                        <div class="form-group">
                            <label>生成数量 (最多100张)</label>
                            <input type="number" name="count" value="1" min="1" max="100" required>
                        </div>
                        <div class="form-group">
                            <label>面值 (小马币数量)</label>
                            <input type="number" name="value" value="10" min="1" required>
                        </div>
                        <div class="form-group">
                            <label>有效期 (天)</label>
                            <input type="number" name="expire_days" value="30" min="1" required>
                        </div>
                        <button type="submit" name="generate" class="btn-generate">立即生成</button>
                    </form>
                    
                    <?php if (!empty($new_cards)): ?>
                        <div class="new-cards-list">
                            <?php foreach ($new_cards as $card): ?>
                                <div class="new-card-item">
                                    <span><?php echo $card['code']; ?></span>
                                    <button class="btn-copy" onclick="copyText('<?php echo $card['code']; ?>', this)">复制</button>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
                
                <!-- 右侧：最近卡密列表 -->
                <div class="panel">
                    <h3>卡密记录</h3>
                    <div class="table-container">
                        <table>
                            <thead>
                                <tr>
                                    <th>卡密</th>
                                    <th>面值</th>
                                    <th>状态 / 使用者</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($recent_cards as $card): ?>
                                <tr>
                                    <td style="font-family: monospace; font-size: 12px;"><?php echo $card['card_code']; ?></td>
                                    <td><?php echo $card['value']; ?></td>
                                    <td>
                                        <?php if ($card['status'] == 0): ?>
                                            <span class="status-0">未使用</span>
                                            <?php if(!empty($card['used_by'])): ?>
                                                <!-- 如果未使用但有 used_by，说明是被撤销的 -->
                                                <span class="user-badge-revoked" title="已被撤销">原ID: <?php echo $card['used_by']; ?></span>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <span class="status-1">已使用</span>
                                            <?php if(!empty($card['used_by'])): ?>
                                                <span class="user-badge">ID: <?php echo $card['used_by']; ?></span>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($card['status'] == 1): ?>
                                            <!-- 已使用状态：显示撤销 -->
                                            <a href="?action=revoke&id=<?php echo $card['id']; ?>" class="btn-revoke" onclick="return confirm('确定撤销吗？将扣除该用户 <?php echo $card['value']; ?> 个小马币！')">撤销</a>
                                        <?php elseif ($card['status'] == 0 && !empty($card['used_by'])): ?>
                                            <!-- 未使用状态但有历史记录：显示恢复 -->
                                            <a href="?action=restore&id=<?php echo $card['id']; ?>" class="btn-restore" onclick="return confirm('确定恢复吗？将补发给用户 ID: <?php echo $card['used_by']; ?> 共 <?php echo $card['value']; ?> 个币！')">恢复</a>
                                        <?php else: ?>
                                            <!-- 全新卡密：显示复制 -->
                                            <button class="btn-copy" onclick="copyText('<?php echo $card['card_code']; ?>', this)">复制</button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
    
    <script>
    function copyText(text, btn) {
        navigator.clipboard.writeText(text).then(() => {
            btn.innerText = '已复制';
            setTimeout(() => btn.innerText = '复制', 1500);
        });
    }
    </script>
</body>
</html>
