<?php

namespace App\Livewire;

use Livewire\Component;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;
use Livewire\Attributes\Layout;  // Required for layout declaration

#[Layout('layouts.dashboard')]  // Attribute syntax for Laravel 11
class TopUp extends Component
{
    public $topUp = [];

    public function mount()
    {
        $this->loadTopUp();  // Load users initially
    }

    public function loadTopUp()
    {
        try {
            $token = Session::get('user')['access_token'] ?? null;
    
            if (!$token) {
                $this->addError('users', 'No access token found.');
                return;
            }
    
            $response = Http::withToken($token)
                ->get(config('services.backend_api.url') . '/api/cms/topUp');

            // dd($response->json());
            if ($response->successful()) {

                // dd($response->json()['data']);
                // Properly use collect to handle the response data
                $this->topUp = collect($response->json()['data'])
                ->map(function ($topUp) {
                              
                    return [
                        'topup_uuid' => $topUp['topup_uuid'],
                        'fee_code' => $topUp['fee_code'],
                        'name' => $topUp['name'],
                        'amount' => $topUp['amount'],
                        'type' => $topUp['type'],
                    ];
                });

                    // dd($this->loadLockedAccounts());
                    
            } else {
                $this->addError('users', 'Failed to load top-up.');
            }
        } catch (\Exception $e) {
            $this->addError('users', 'Error: ' . $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.top-up.top-up', [
            'top_up' => $this->topUp,  // Pass all users to the table
        ]);
    }
}