<?php

namespace App\Livewire;

use Livewire\Component;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;

class Notification extends Component
{
    public $notifs = [];


    public function mount()
    {
        $this->loadNotifications();
    }

    // Get filtered notifications based on the search input
    public function loadNotifications()
    {
        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/notification');
    
                // dd($response->json());

            if ($response->successful()) {
                // Properly use collect to handle the response data
                $this->notifs = collect($response->json()['data']['notifications'])->map(function ($notifs) {
                    return [
                        'id' => $notifs['id'],
                        'subject' => $notifs['subject'],
                        'description' => $notifs['description'],
                        'schedule' => $notifs['trigger_schedule']?? '-',
                        'expiration' => $notifs['expiration_date']?? '-',
                        'is_scheduled' => !empty($notifs['trigger_schedule']) ? 'Yes' : 'No',
                    ];
                });
            } else {
                $this->addError('notifications', 'Failed to load notifications.');
            }
        } catch (\Exception $e) {
            $this->addError('notifications', 'Error: ' . $e->getMessage());
        }
    }
    

    public function render()
    {
        return view('livewire.notification.notification', [
            'notification' => $this->notifs,  // Pass filtered notifs here
        ]);
    }
}
