<?php
// api/get_wallet_log.php - 讀取存摺
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

$uid = intval($_GET['user_id']);

try {
    // 1. 查餘額
    $stmt = $pdo->prepare("SELECT coins FROM users WHERE id = ?");
    $stmt->execute([$uid]);
    $balance = $stmt->fetchColumn();

    // 2. 查明細 (最近 50 筆)
    $stmt = $pdo->prepare("SELECT * FROM transactions WHERE user_id = ? ORDER BY created_at DESC LIMIT 50");
    $stmt->execute([$uid]);
    $logs = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 3. 翻譯類型
    foreach ($logs as &$log) {
        switch($log['type']) {
            case 'TASK_REWARD': $log['type_label'] = '🏆 任務賞金'; break;
            case 'ADMIN_GRANT': $log['type_label'] = '👑 官方撥款 (購買/贈送)'; break;
            case 'SPEND': $log['type_label'] = '🚀 發布任務扣款'; break;
            default: $log['type_label'] = '交易';
        }
    }

    echo json_encode(["status" => "success", "balance" => $balance, "data" => $logs]);

} catch (Exception $e) {
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}
?>