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

// 检查登录
if (!isset($_SESSION['user_logged_in']) || $_SESSION['user_logged_in'] !== true) {
    header('Location: index.php');
    exit;
}

$user_id = $_SESSION['user_id'];
$msg = '';
$success = false;

// 处理充值请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $card_code = trim($_POST['card_code'] ?? '');
    
    if (empty($card_code)) {
        $msg = '请输入卡密';
    } else {
        // 查询卡密信息
        $stmt = mysqli_prepare($conn, "SELECT * FROM cards WHERE card_code = ?");
        mysqli_stmt_bind_param($stmt, "s", $card_code);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        $card = mysqli_fetch_assoc($result);
        
        if (!$card) {
            $msg = '卡密不存在，请检查是否输入正确';
        } elseif ($card['status'] == 1) {
            $msg = '该卡密已被使用';
        } elseif (!empty($card['expire_time']) && strtotime($card['expire_time']) < time()) {
            $msg = '该卡密已过期';
        } else {
            // 开始事务
            mysqli_begin_transaction($conn);
            try {
                // 1. 增加用户小马币
                $stmt_update = mysqli_prepare($conn, "UPDATE users SET coins = coins + ? WHERE id = ?");
                mysqli_stmt_bind_param($stmt_update, "ii", $card['value'], $user_id);
                mysqli_stmt_execute($stmt_update);
                
                // 2. 标记卡密已使用
                $status = 1;
                $used_at = date('Y-m-d H:i:s');
                $stmt_card = mysqli_prepare($conn, "UPDATE cards SET status = ?, used_by = ?, used_at = ? WHERE id = ?");
                mysqli_stmt_bind_param($stmt_card, "iisi", $status, $user_id, $used_at, $card['id']);
                mysqli_stmt_execute($stmt_card);
                
                // 3. 【新增】写入日志记录
                // 先获取充值后的最新余额
                $stmt_bal = mysqli_prepare($conn, "SELECT coins FROM users WHERE id = ?");
                mysqli_stmt_bind_param($stmt_bal, "i", $user_id);
                mysqli_stmt_execute($stmt_bal);
                $new_balance = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt_bal))['coins'];
                
                // 插入日志到 coin_logs 表
                $log_type = 'recharge';
                $change_amount = $card['value'];
                $description = '卡密充值';
                $stmt_log = mysqli_prepare($conn, "INSERT INTO coin_logs (user_id, type, change_amount, balance_after, description, create_time) VALUES (?, ?, ?, ?, ?, NOW())");
                mysqli_stmt_bind_param($stmt_log, "isiis", $user_id, $log_type, $change_amount, $new_balance, $description);
                mysqli_stmt_execute($stmt_log);
                
                mysqli_commit($conn);
                $msg = '充值成功！获得 ' . $card['value'] . ' 个小马币';
                $success = true;
            } catch (Exception $e) {
                mysqli_rollback($conn);
                $msg = '充值失败，请稍后重试';
            }
        }
    }
}

// 获取当前余额
$stmt = mysqli_prepare($conn, "SELECT coins FROM users WHERE id = ?");
mysqli_stmt_bind_param($stmt, "i", $user_id);
mysqli_stmt_execute($stmt);
$coins = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt))['coins'];
?>
<!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>
        body { background-color: #f4f6f9; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; margin: 0; display: flex; justify-content: center; align-items: center; min-height: 100vh; }
        .recharge-container { max-width: 600px; width: 95%; background: #fff; padding: 30px; border-radius: 10px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); text-align: center; }
        .title { font-size: 22px; color: #333; margin-bottom: 20px; font-weight: bold; }
        .coin-display { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 15px; border-radius: 8px; margin-bottom: 25px; }
        .coin-num { font-size: 28px; font-weight: bold; }
        .coin-label { font-size: 12px; opacity: 0.9; }

        .package-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
            margin-bottom: 25px;
        }
        .package-item {
            background: #f9f9f9;
            border-radius: 8px;
            padding: 12px 8px;
            text-align: center;
            font-size: 14px;
            line-height: 1.6;
        }
        .package-price {
            color: #ff6b6b;
            font-weight: bold;
            margin-bottom: 6px;
        }
        .buy-btn {
            display: inline-block;
            padding: 4px 10px;
            background: #ffd740;
            color: #333;
            border-radius: 4px;
            font-size: 12px;
            text-decoration: none;
        }
        .buy-btn:hover {
            background: #ffc107;
        }

        .form-group { margin-bottom: 20px; text-align: left; }
        .form-group label { display: block; margin-bottom: 8px; color: #666; font-size: 14px; }
        .form-group input { width: 100%; padding: 12px; border: 2px solid #e0e0e0; border-radius: 8px; box-sizing: border-box; font-size: 16px; transition: border-color 0.3s; }
        .form-group input:focus { border-color: #667eea; outline: none; }
        
        .btn-recharge { width: 100%; padding: 12px; background: linear-gradient(135deg, #ff6b6b 0%, #ee5a5a 100%); color: white; border: none; border-radius: 8px; font-size: 16px; font-weight: bold; cursor: pointer; transition: opacity 0.3s; }
        .btn-recharge:hover { opacity: 0.9; }
        
        .msg-box { padding: 12px; border-radius: 6px; margin-bottom: 20px; font-size: 14px; }
        .msg-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .msg-error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        
        .btn-back { display: inline-block; margin-top: 20px; color: #666; text-decoration: none; font-size: 14px; }
    </style>
</head>
<body>
<div class="recharge-container">
    <div class="title">💎 充值小马币 💎</div>
    
    <div class="coin-display">
        <div class="coin-label">当前余额</div>
        <div class="coin-num"><?php echo intval($coins); ?> 个</div>
    </div>

    <div class="package-grid">
        <div class="package-item">
            5个<br>
            <div class="package-price">0.09元</div>
            <a href="http://ai.99520.xyz/?mod=buy&cid=126&tid=4176" target="_blank" class="buy-btn">购买</a>
        </div>
        <div class="package-item">
            10个<br>
            <div class="package-price">0.17元</div>
            <a href="http://ai.99520.xyz/?mod=buy&cid=126&tid=4183" target="_blank" class="buy-btn">购买</a>
        </div>
        <div class="package-item">
            20个<br>
            <div class="package-price">0.3元</div>
            <a href="http://ai.99520.xyz/?mod=buy&cid=126&tid=4182" target="_blank" class="buy-btn">购买</a>
        </div>

        <div class="package-item">
            50个<br>
            <div class="package-price">0.74元</div>
            <a href="http://ai.99520.xyz/?mod=buy&cid=126&tid=4184" target="_blank" class="buy-btn">购买</a>
        </div>
        <div class="package-item">
            100个<br>
            <div class="package-price">1.44元</div>
            <a href="http://ai.99520.xyz/?mod=buy&cid=126&tid=4185" target="_blank" class="buy-btn">购买</a>
        </div>
        <div class="package-item">
            200个<br>
            <div class="package-price">2.82元</div>
            <a href="http://ai.99520.xyz/?mod=buy&cid=126&tid=4186" target="_blank" class="buy-btn">购买</a>
        </div>

        <div class="package-item">
            500个<br>
            <div class="package-price">6.9元</div>
            <a href="http://ai.99520.xyz/?mod=buy&cid=126&tid=4187" target="_blank" class="buy-btn">购买</a>
        </div>
        <div class="package-item">
            1000个<br>
            <div class="package-price">13.5元</div>
            <a href="http://ai.99520.xyz/?mod=buy&cid=126&tid=4188" target="_blank" class="buy-btn">购买</a>
        </div>
        <div class="package-item">
            2000个<br>
            <div class="package-price">19.3元</div>
            <a href="http://ai.99520.xyz/?mod=buy&cid=126&tid=4189" target="_blank" class="buy-btn">购买</a>
        </div>
    </div>

    <?php if ($msg): ?>
        <div class="msg-box <?php echo $success ? 'msg-success' : 'msg-error'; ?>">
            <?php echo $msg; ?>
        </div>
    <?php endif; ?>
    
    <form method="POST">
        <div class="form-group">
            <label>请输入充值卡密</label>
            <input type="text" name="card_code" placeholder="请输入卡密..." required>
        </div>
        <button type="submit" class="btn-recharge">立即充值</button>
    </form>
    
    <a href="home.php" class="btn-back">← 返回个人中心</a>
</div>
</body>
</html>
