<?php
/**
 * Created by PhpStorm.
 * User: radko
 * Date: 19.11.18
 * Time: 13:56
 */

namespace Seka\Vzdelavanie\Composers\Kniznica;

use Core\Facades\Hasher;
use Illuminate\View\View;
use Illuminate\Support\Facades\DB;
use Seka\Vzdelavanie\Services\KategoriaServiceInterface;

/**
 * Class ZoznamUcebnychMaterialovPodlaKategoriiComposer
 * @package Seka\Vzdelavanie\Composers\Kniznica
 */
class ZoznamUcebnychMaterialovPodlaKategoriiComposer
{
    /**
     * @var \Seka\Vzdelavanie\Services\KategoriaServiceInterface
     */
    private $service;

    /**
     * ZoznamKategoriiComposer constructor.
     * @param \Seka\Vzdelavanie\Services\KategoriaServiceInterface $service
     */
    public function __construct(KategoriaServiceInterface $service)
    {
        $this->service = $service;
    }

    /**
     * @param \Illuminate\View\View $view
     *
     * @return \Illuminate\View\View
     */
    public function compose(View $view): View
    {
        $res = DB::select("
            select count(popularita_id) cnt, popularita_id, popularita_type, vku.nazov ucebnica_nazov, vkk.nazov kategoria_nazov, vkk.id kategoria_id, vku.id ucebnica_id
            from vzdelavanie_popularnost
            left join vzdelavanie_kniznica_ucebnice vku on vzdelavanie_popularnost.popularita_id = vku.id
            left join vzdelavanie_kniznica_kategorie vkk on vku.kategoria_id = vkk.id
            where popularita_type = 'MODEL_TYPE_KNIZNICA_UCEBNY_MATERIAL'
            and vku.stav = 'PUBLIKOVANE'
            group by popularita_id, popularita_type, vku.nazov, vkk.nazov, vkk.id, vku.id
            order by cnt desc
        ");

        $res = collect($res);
        $priemer = (int) $res->median('cnt');

        $grouped = $res
            ->groupBy('kategoria_nazov')
            ->transform(function ($ucebnice, $kategoria) use ($priemer) {
                return $ucebnice
                    ->filter(function ($ucebnica, $key) use ($priemer) {
                        return $ucebnica->cnt > $priemer;
                    })
                    ->take(3);
            })
            ->map(function ($ucebnice, $kategoria) {
                return $ucebnice
                    ->map(function ($ucebnica, $key) {
                        $ucebnica->kategoria_id = Hasher::encode($ucebnica->kategoria_id);
                        $ucebnica->ucebnica_id = Hasher::encode($ucebnica->ucebnica_id);

                        return $ucebnica;
                    });
            })
            ->reject(function ($ucebnice, $kategoria) {
                return $ucebnice->isEmpty();
            });

        return $view->with(
            'kategorieSUcebnymMaterialom',
            $grouped
        );
    }
}
