<?php
session_start();
require_once '../config.php';
// 引入等级计算核心逻辑
require_once 'level_check.php';

// 检测登录
if (!isset($_SESSION['user_logged_in']) || $_SESSION['user_logged_in'] !== true) {
    echo json_encode(['status' => 'error', 'message' => '请先登录']);
    exit;
}

$user_id = $_SESSION['user_id'];
$cost = 5; // 扣费金额：5个小马币

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // 1. 检查用户余额
    $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);
    $res_bal = mysqli_stmt_get_result($stmt_bal);
    $user_bal = mysqli_fetch_assoc($res_bal);

    if (!$user_bal) {
        echo json_encode(['status' => 'error', 'message' => '用户不存在']); exit;
    }

    if ($user_bal['coins'] < $cost) {
        echo json_encode(['status' => 'error', 'message' => "小马币不足，修改头像需要 {$cost} 个币"]); exit;
    }

    // 2. 处理上传文件夹
    $upload_dir = '../uploads/avatars/';
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }

    // 3. 接收 base64 图片数据
    $image_data = $_POST['image_data'] ?? '';

    if (strpos($image_data, 'data:image') === 0) {
        // 解析图片格式
        preg_match('/data:image\/(\w+);base64,/', $image_data, $type_matches);
        $extension = $type_matches[1] ?? 'png'; // 获取图片后缀
        if (!in_array($extension, ['jpg', 'jpeg', 'png', 'gif'])) {
            $extension = 'png';
        }

        $file_name = 'avatar_' . $user_id . '_' . time() . '.' . $extension;
        $file_path = $upload_dir . $file_name;
        
        // 解码图片
        $image_parts = explode(';base64,', $image_data);
        $image_base64 = base64_decode($image_parts[1]);
        
        // 先保存文件到磁盘
        if (file_put_contents($file_path, $image_base64)) {
            
            $db_path = 'uploads/avatars/' . $file_name; // 存入数据库的相对路径
            
            // 4. 开启事务处理数据库逻辑
            mysqli_begin_transaction($conn);
            try {
                // A. 更新用户头像路径
                $stmt_up = mysqli_prepare($conn, "UPDATE users SET avatar = ? WHERE id = ?");
                mysqli_stmt_bind_param($stmt_up, "si", $db_path, $user_id);
                mysqli_stmt_execute($stmt_up);

                // B. 扣除小马币
                $new_coins = $user_bal['coins'] - $cost;
                $stmt_coin = mysqli_prepare($conn, "UPDATE users SET coins = ? WHERE id = ?");
                mysqli_stmt_bind_param($stmt_coin, "ii", $new_coins, $user_id);
                mysqli_stmt_execute($stmt_coin);

                // C. 写入消费日志
                $log_desc = '修改头像消费';
                $stmt_log = mysqli_prepare($conn, "INSERT INTO coin_logs (user_id, change_amount, balance_after, type, description) VALUES (?, ?, ?, 'consume', ?)");
                $change_amount = -$cost; // 负数表示消费
                mysqli_stmt_bind_param($stmt_log, "iiis", $user_id, $change_amount, $new_coins, $log_desc);
                mysqli_stmt_execute($stmt_log);

                // 提交事务
                mysqli_commit($conn);

                // --- 检测并处理升级 ---
                $new_lv = checkAndUpdateLevel($user_id, $conn);

                // 返回成功信息，包含最新余额和升级信息
                echo json_encode([
                    'status'  => 'success', 
                    'url'     => '../' . $db_path,
                    'coins'   => $new_coins,
                    'level_up'=> $new_lv // 如果升级了，返回新等级，否则返回 false
                ]);

            } catch (Exception $e) {
                // 回滚事务
                mysqli_rollback($conn);
                // 删除已上传的文件，防止垃圾文件堆积
                if (file_exists($file_path)) {
                    unlink($file_path);
                }
                echo json_encode(['status' => 'error', 'message' => '数据库操作失败: ' . $e->getMessage()]);
            }

        } else {
            echo json_encode(['status' => 'error', 'message' => '图片保存失败，请检查目录权限']);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => '无效的图片数据']);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => '请求方式错误']);
}
?>
