<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Api\fiver;
use Illuminate\Support\Facades\Auth;

class BalanceController extends Controller
{
    public function getBalance(Request $request)
    {
        try {
            $user = Auth::user();

            // ⬇️ pastikan extplayer ada
            if (empty($user->extplayer)) {
                return response()->json([
                    'balance' => 0,
                    'message' => 'User belum memiliki extplayer'
                ], 400);
            }

            $api = new fiver();

            // 🔑 extplayer dipakai ke API
            $response = $api->userBalance($user->extplayer);

            if (!isset($response['status']) || $response['status'] !== true) {
                return response()->json([
                    'balance' => 0,
                    'message' => $response['message'] ?? 'Gagal ambil saldo'
                ], 400);
            }

            return response()->json([
                'balance' => (float) ($response['user']['balance'] ?? 0)
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'balance' => 0,
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
