<?php

declare(strict_types=1);

namespace Seka\Portal\Modul\Vzdelavanie\Listeners\Kniznica;

use Illuminate\Contracts\Queue\ShouldQueue;
use Seka\Portal\Modul\Vzdelavanie\Events\Kniznica\Frontend\UcebnyMaterialOpened;
use Seka\Portal\Modul\Vzdelavanie\Models\Kniznica\Ucebnica;
use Seka\Portal\Modul\Vzdelavanie\Models\Popularita\Popularita;

/**
 * Class UcebnyMaterialCreatePopularityRecord
 *
 * @package Seka\Portal\Modul\Vzdelavanie\Listeners\Kniznica
 */
final class UcebnyMaterialCreatePopularityRecord implements ShouldQueue
{
    /**
     * UcebnyMaterialCreatePopularityRecord constructor.
     */
    public function __construct() {}

    /**
     * @param \Seka\Portal\Modul\Vzdelavanie\Events\Kniznica\Frontend\UcebnyMaterialOpened $event
     */
    public function handle(UcebnyMaterialOpened $event): void
    {
        $popularita = new Popularita();
        $popularita->pouzivatel()->associate($event->pouzivatel->getAuthIdentifier());

        /** @var Ucebnica $ucebnica */
        $ucebnica = Ucebnica::query()->with('popularita')->findOrFail($event->ucebnica->id);
        $ucebnica->popularita()->save($popularita);
    }
}
