<?php

namespace App\Listeners;

use App\Dtos\InformaciaDto;
use App\Events\InformaciaZverejnenaEvent;
use App\Models\Pouzivatel\Pouzivatel;
use App\Notifications\Push\MAAISEKInformaciaPouzivatelPushNotification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Collection;

/**
 * Class SendInformaciaPouzivatelPushNotificationListener
 *
 * Listener pre odosielanie push notifikacii po zverejneni informacie
 *
 * @package App\Listeners
 * @author  Radoslav Lukac <dev@seka.sk>
 */
class SendInformaciaPouzivatelPushNotificationListener implements ShouldQueue
{
    /**
     * Spracovanie eventu zverejnenia informacie
     */
    public function handle(InformaciaZverejnenaEvent $event): void
    {
        if (!$event->informacia->odoslat_push_notifikacie_pouzivatelom) {
            return;
        }

        $informaciaDto = InformaciaDto::from($event->informacia);

        // Získame používateľov podľa rolí
        $users = $this->getUsersByRoles($informaciaDto->zverejnit_pre_pouzivatelov_podla_role);

        foreach ($users as $user) {
            $user->notify(new MAAISEKInformaciaPouzivatelPushNotification($informaciaDto));
        }
    }

    /**
     * Ziskanie pouzivatelov podla roli
     */
    private function getUsersByRoles(?array $roles): Collection
    {
        /** @var Collection $pouzivatelia */
        $pouzivatelia = Pouzivatel::aktivny()->get();

        if (empty($roles)) {
            return $pouzivatelia;
        }

        return $pouzivatelia->filter(function ($pouzivatel) use ($roles) {
            return $pouzivatel->hasAnyRole($roles);
        });
    }
}
