<?php

namespace App\Http\Controllers;

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

class SaldoController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * ===============================
     * SALDO GAME (NX / FIVER)
     * ===============================
     */
    public function get_saldo(Request $request)
{
    try {
        $user = Auth::user();

        if (empty($user->extplayer)) {
            return response()->json([
                'error' => 'User belum memiliki extplayer'
            ], 400);
        }

        $api = new fiver();
        $response = $api->userBalance($user->extplayer);

        // ✅ FIX UTAMA DI SINI
        if (!isset($response['status']) || (int)$response['status'] !== 1) {
            Log::error('Get saldo gagal', [
                'user_id' => $user->id,
                'response' => $response
            ]);

            return response()->json([
                'error' => $response['msg'] ?? 'Gagal mengambil saldo'
            ], 400);
        }

        $saldo = $response['user']['balance'] ?? 0;

        return response()->json([
            'data' => 'IDR ' . number_format($saldo, 2)
        ]);

    } catch (\Throwable $e) {
        Log::error('Saldo Exception', [
            'msg' => $e->getMessage()
        ]);

        return response()->json([
            'error' => 'Internal server error'
        ], 500);
    }
}

    /**
     * ===============================
     * SALDO REFERRAL (DB LOKAL)
     * ===============================
     */
    public function get_saldo_referral()
    {
        $user = Auth::user();

        $saldo = Saldo::where('user_id', $user->id)->first();

        return response()->json([
            'data' => 'IDR ' . number_format($saldo->referral ?? 0, 2)
        ]);
    }
}