<?php

namespace App\Livewire;

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

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

    public function mount()
    {
        $this->loadStationRating();  // Load stationRating initially
    }

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

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

                // dd($response->json()['data']);
                // Properly use collect to handle the response data
                $this->stationRating = collect($response->json()['data'])
                ->map(function ($stationRating) {

                    // dd($this->stationRating);
                              
                    return [
                        'rating_uuid' => $stationRating['rating_uuid'],
                        'date' => $stationRating['date'],
                        'card_number' => $stationRating['card_number'],
                        'invoice' => $stationRating['invoice'],
                        'station' => $stationRating['station'],
                        'rating' => $stationRating['rate'],

                    ];
                    
                });

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

    public function render()
    {
        return view('livewire.report.station-rating-report', [
            'stationRating' => $this->stationRating, 
        ]);
    }
}
