<?php

declare(strict_types=1);

namespace Seka\Portal\Modul\Vzdelavanie\Composers\Testovanie;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\View\View;
use Seka\Portal\Modul\Vzdelavanie\Enums\ModelStatusEnum;
use Seka\Portal\Modul\Vzdelavanie\Models\Testovanie\Test;

/**
 * Class ZoznamTestovPodlaPopularnostiCompose
 *
 * @package Seka\Portal\Modul\Vzdelavanie\Composers\Testovanie
 */
final class ZoznamTestovPodlaPopularnostiCompose
{
    /**
     * @param \Illuminate\View\View $view
     *
     * @return \Illuminate\View\View
     */
    public function compose(View $view): View
    {
        $testy = Test::withCount('popularita')
            ->has('popularita', '>', 0)
            ->orderByDesc('popularita_count')
            ->get();

        $testy = $testy->groupBy('nazov');
        $out = [];

        $testy->each(function ($_testy, $nazov) use (&$out) {
            $_testy->each(function ($test) use ($nazov, &$out) {
                if (array_key_exists($nazov, $out)) {
                    if ($test->stav === ModelStatusEnum::PUBLIKOVANE) {
                        $out[$nazov]['id'] = $test->id;
                    }
                    $out[$nazov]['popularita_count'] = $out[$nazov]['popularita_count'] + $test->popularita_count;
                } else {
                    $out[$nazov] = [
                        'popularita_count' => $test->popularita_count,
                    ];
                    if ($test->stav === ModelStatusEnum::PUBLIKOVANE) {
                        $out[$nazov] = array_merge($out[$nazov], ['id' => $test->id]);
                    }
                }
            });
        });

        unset($testy);

        $arr = array_filter($out, function ($data) {
            if (array_key_exists('id', $data)) {
                return true;
            }

            return false;
        });

        $out = new Collection(array_map(function ($nazov, $data) {
            $t = new Test([
                'id' => $data['id'] ?? null,
                'nazov' => $nazov,
            ]);
            $t->popularita_cnt = $data['popularita_count'] ?? 0;
            return $t;
        }, array_keys($arr), $arr));

        unset($arr);

        return $view->with(
            'testy',
            $out->take(3),
        );
    }
}
