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

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

    public function loadPhotoSliders()
    {
        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/photoSlider');
    
                // dd($response->json());
            if ($response->successful()) {
                // Properly use collect to handle the response data
                $this->photoSliders = collect($response->json()['data'])
                ->map(function ($photoSliders) {
                    return [
                        'photoslider_uuid' => $photoSliders['photoslider_uuid'],
                        'title' => $photoSliders['title'],
                        'promotion_id' => $photoSliders['type'],
                        'date_start' => $photoSliders['date_start'],
                        'date_end' => $photoSliders['date_end'],
                    ];
                });
                
            } else {
                $this->addError('users', 'Failed to load photo sliders.');
            }
        } catch (\Exception $e) {
            $this->addError('users', 'Error: ' . $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.home-page-mobile.photo-slider', [
            'photo_slider' => $this->photoSliders,  // Pass all users to the table
        ]);
    }
}
