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

    public function mount()
    {
        $this->loadBranches();  // Load branches initially
    }

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

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

                // dd($response->json()['data']); this gets the data
                // Properly use collect to handle the response data
                $this->branches = collect($response->json()['data'])
                ->map(function ($branches) {
                              //returns null
            return [
                'station_uuid' => $branches['station_uuid'],
                'station_code' => $branches['code'],
                'station_name' => $branches['description'],
                'branch' => $branches['city'],
                'created_at' => $branches['created_at'],
                'created_by' => $branches['created_by'],
                'modified_by' => $branches['modified_by'],
                'date_modified' => $branches['modified_at'], // ✅ correct spelling
            ];
                });
              
                    // dd($this->loadLockedAccounts());
                    
            } else {
                $this->addError('users', 'Failed to load branches.');
            }
        } catch (\Exception $e) {
            $this->addError('users', 'Error: ' . $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.station-locator.branch', [
            'branches' => $this->branches,  // Pass all branches to the table
        ]);
    }
}
