<?php

declare(strict_types=1);

namespace Seka\Vzdelavanie\Composers\Kniznica;

use Illuminate\View\View;
use Illuminate\Support\Facades\Auth;
use Seka\Vzdelavanie\Models\Pouzivatel\Kniznica\Oblubene;

/**
 * Class ZoznamOblubenychPoloziekPouzivatelaComposer
 *
 * @package Seka\Vzdelavanie\Composers\Kniznica
 */
final class ZoznamOblubenychPoloziekPouzivatelaComposer
{
    /**
     * @param \Illuminate\View\View $view
     *
     * @return \Illuminate\View\View
     */
    public function compose(View $view): View
    {
        return $view->with('oblubenePolozky', $this->zoznam());
    }

    /**
     * @return \Illuminate\Support\Collection
     */
    protected function zoznam()
    {
        $newOblubene = collect();
        $ucebneMaterialy = collect();
        $oblubene = Oblubene::query()->with('oblubene')->where('pouzivatel_id', Auth::id())->get();

        $oblubene->each(function (Oblubene $obl) use ($ucebneMaterialy, $newOblubene) {
            $o = $obl->oblubene()->with('ucebnica')->first();

            if (is_null($o)) {
                return;
            }

            if (!$ucebneMaterialy->contains($o->ucebnica)) {
                $ucebneMaterialy->add($o->ucebnica);
            }

            $newOblubene->add($o);
            unset($obl);
        });

        unset($oblubene);

        $ucebneMaterialy->each(function ($mat) use ($newOblubene) {
            $newOblubene->each(function ($o) use (&$mat) {
                if ($o->ucebnica->id === $mat->id) {
                    $mat->oblubene->add($o);
                }
            });
        });

        unset($newOblubene);

        return $ucebneMaterialy;
    }
}
