<?php
/**
 * 卡密充值API
 */
require_once '../config.php';

header('Content-Type: application/json');

// 检查登录
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

$user = currentUser();
$card_code = trim($_POST['card_code'] ?? '');

if (empty($card_code)) {
    echo json_encode(['success' => false, 'message' => '请输入卡密']);
    exit;
}

// 格式化卡密（去除空格和转大写）
$card_code = strtoupper(preg_replace('/[^A-Z0-9]/', '', $card_code));

// 查询卡密
$card = $db->fetchOne("SELECT * FROM card_codes WHERE card_code = '$card_code'");

if (!$card) {
    echo json_encode(['success' => false, 'message' => '卡密不存在']);
    exit;
}

if ($card['status'] == 1) {
    echo json_encode(['success' => false, 'message' => '卡密已被使用']);
    exit;
}

if ($card['expire_at'] && strtotime($card['expire_at']) < time()) {
    echo json_encode(['success' => false, 'message' => '卡密已过期']);
    exit;
}

// 充值
$db->query("START TRANSACTION");

try {
    // 更新用户余额
    $db->query("UPDATE users SET balance = balance + {$card['amount']} WHERE id = {$user['id']}");
    
    // 更新卡密状态
    $db->query("UPDATE card_codes SET status = 1, used_by = {$user['id']}, used_at = NOW() WHERE id = {$card['id']}");
    
    // 记录余额日志
    addBalanceLog($user['id'], $card['amount'], 'recharge', "卡密充值：{$card_code}");
    
    $db->query("COMMIT");
    
    // 发送邮件通知
    require_once '../includes/mail_helper.php';
    if (!empty($user['email']) && ($user['email_notify'] ?? 1)) {
        sendRechargeNotification($user, $card['amount'], "卡密充值");
    }
    
    echo json_encode(['success' => true, 'message' => '充值成功！金额：¥' . number_format($card['amount'], 2)]);
    
} catch (Exception $e) {
    $db->query("ROLLBACK");
    echo json_encode(['success' => false, 'message' => '充值失败，请重试']);
}