<?php

namespace App\Livewire;

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

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

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

    public function loadLockedAccounts()
    {
        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?_locked=1');


    
    
            if ($response->successful()) {

                // dd($response->json()['data']);
                // Properly use collect to handle the response data
                $this->lockedAccounts = collect($response->json()['data'])
                
                ->filter(function ($lockedAccounts) {return (int) $lockedAccounts['is_locked'] == 1;})
                ->map(function ($lockedAccounts) {
                              
                    return [
                        'lcard_uuid' => $lockedAccounts['lcard_uuid'],
                        'card_number' => $lockedAccounts['card_number'],
                        'firstname' => $lockedAccounts['firstname'],
                        'lastname' => $lockedAccounts['lastname'],
                        'birthdate' => $lockedAccounts['birthdate'],
                        'cardtype_id' => $lockedAccounts['card_type'],
                        'status' => $lockedAccounts['status'],
                    ];
                });

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

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