<?php
session_name('user_session');
session_start();
require '../config.php'; // 确保引入配置文件

// 检查用户是否已登录
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => 'error', 'message' => '用户未登录。']);
    exit;
}

// 获取当前用户ID
$userId = $_SESSION['user_id'];

// 处理卡密兑换
if (isset($_POST['redeem_card'])) {
    $cardCode = $_POST['card_code'];

    // 防止XSS注入
    $cardCode = htmlspecialchars($cardCode, ENT_QUOTES, 'UTF-8');

    $stmt = $pdo->prepare("SELECT * FROM " . table('cards') . " WHERE code = :code AND status = 0");
    $stmt->execute(['code' => $cardCode]);
    $card = $stmt->fetch();

    if ($card) {
        // 更新卡密状态和使用信息
        $updateStmt = $pdo->prepare("UPDATE " . table('cards') . " SET status = 1, redeemed_at = NOW(), user_id = :user_id WHERE id = :id");
        $updateStmt->execute([
            'user_id' => $userId,
            'id' => $card['id']
        ]);

        // 增加用户余额
        $updateBalanceStmt = $pdo->prepare("UPDATE " . table('users') . " SET balance = balance + :amount WHERE id = :user_id");
        $updateBalanceStmt->execute([
            'amount' => $card['amount'],
            'user_id' => $userId
        ]);

        // 记录余额变动日志
        $stmt = $pdo->prepare("INSERT INTO " . table('balance_logs') . " (user_id, change_amount, new_balance, reason) VALUES (:user_id, :change_amount, :new_balance, :reason)");
        $stmt->execute([
            'user_id' => $userId,
            'change_amount' => $card['amount'], // 变动的金额为正值
            'new_balance' => $card['amount'] + getUserBalance($userId, $pdo), // 使用当前余额加上奖励金额
            'reason' => "卡密兑换成功，兑换码: " . $cardCode // 变动的原因
        ]);

        $message = "卡密兑换成功，您的余额已增加 " . number_format($card['amount'], 2) . "！";
    } else {
        $message = "该卡密无效或已被兑换！";
    }
}

// 功能函数：获取用户余额
function getUserBalance($userId, $pdo)
{
    $stmt = $pdo->prepare("SELECT balance FROM " . table('users') . " WHERE id = ?");
    $stmt->execute([$userId]);
    return $stmt->fetchColumn();
}
?>

<?php include 'header.php'; ?>
<div class="main-content">
    <div class="page-content">
        <div class="container-fluid">
            <h1>卡密管理 - 兑换卡密</h1>

            <form method="POST" action="exchange.php">
                <div class="mb-3">
                    <label for="card_code" class="form-label">卡密</label>
                    <input type="text" class="form-control" name="card_code" required>
                </div>
                <button type="submit" name="redeem_card" class="btn btn-primary">兑换</button>
            </form>

            <?php if (isset($message)): ?>
                <div class="alert alert-info"><?php echo $message; ?></div>
            <?php endif; ?>
        </div>
    </div>
</div>
</body>

</html>