<?php

namespace App\Listeners;

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

/**
 * Class SendInformaciaPouzivatelNotificationListener
 *
 * Sluzi na odosielanie emailovych notifikacii pouzivatelom po zverejneni informacie
 *
 * @package App\Listeners
 * @author  Radoslav Lukac <dev@seka.sk>
 */
class SendInformaciaPouzivatelNotificationListener implements ShouldQueue
{
    /**
     * Spracuje event zverejnenia informacie
     *
     * @param InformaciaZverejnenaEvent $event Event obsahujuci zverejnenu informaciu
     */
    public function handle(InformaciaZverejnenaEvent $event): void
    {
        if (!$event->informacia->odoslat_email_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 InformaciaPouzivatelNotification($informaciaDto));
        }
    }

    /**
     * Ziska vsetkych pouzivatelov podla zadanych roli
     *
     * @param array|null $roles Pole s nazvami roli
     */
    private function getUsersByRoles(?array $roles): Collection
    {
        /** @var Collection $pouzivatelia */
        $pouzivatelia = Pouzivatel::query()->aktivny()->get();

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

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