<?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 CardType extends Component
{
    public $cardTypes = [];

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

    public function loadCardTypes()
    {
        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/cardType');

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

                // dd($response->json()['data']);
                // Properly use collect to handle the response data
                $this->cardTypes = collect($response->json()['data'])
                ->map(function ($cardTypes) {
                              
                    return [
                        'cardtype_uuid' => $cardTypes['cardtype_uuid'],
                        'code' => $cardTypes['code'],
                        'name' => $cardTypes['name'],

                    ];
                });
                    
            } else {
                $this->addError('card types', 'Failed to load top-up.');
            }
        } catch (\Exception $e) {
            $this->addError('card types', 'Error: ' . $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.about-us.card-type', [
            'users' => $this->cardTypes,  // Pass all users to the table
        ]);
    }
}
