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

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

    public function loadCardMembers()
    {
        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/member');
    
                // dd($response->json());
            if ($response->successful()) {
                // Properly use collect to handle the response data
                $this->cardMembers = collect($response->json()['data'])
                ->filter(function ($cardMembers) {return $cardMembers['is_locked'] == 0;})
                ->map(function ($cardMembers) {
                    return [
                        'lcard_uuid' => $cardMembers['lcard_uuid'],
                        'card_number' => $cardMembers['card_number'],
                        'firstname' => $cardMembers['firstname'],
                        'lastname' => $cardMembers['lastname'],
                        'birthdate' => $cardMembers['birthdate'],
                        'cardtype_id' => $cardMembers['card_type'],
                        'status' => $cardMembers['status'],
                    ];
                });
                
            } else {
                $this->addError('card members', 'Failed to load card members.');
            }
        } catch (\Exception $e) {
            $this->addError('card members', 'Error: ' . $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.member-management.card-member', [
            'card_members' => $this->cardMembers,  // Pass all users to the table
        ]);
    }
}
