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

    public function mount()
    {
        $this->loadStations();  // Load stations initially
    }

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

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

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

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