<?php
/**
 * Created by PhpStorm.
 * User: radko
 * Date: 15.11.18
 * Time: 11:19
 */

namespace Seka\Vzdelavanie\Http\Controllers\Frontend\Kniznica;

use Exception;
use Illuminate\Support\Facades\Log;
use Seka\Vzdelavanie\Http\Controllers\Controller;
use Seka\Vzdelavanie\Services\UcebnicaServiceInterface;
use Seka\Vzdelavanie\Services\KategoriaServiceInterface;
use Seka\Vzdelavanie\Repositories\Exceptions\ModelNotFoundException;

/**
 * Class KategoriaController
 * @package Seka\Vzdelavanie\Http\Controllers\Frontend\Kniznica
 */
class KategoriaController extends Controller
{
    /**
     * @var \Seka\Vzdelavanie\Services\KategoriaServiceInterface
     */
    protected $kategoriaService;

    /**
     * @var \Seka\Vzdelavanie\Services\UcebnicaServiceInterface
     */
    protected $ucebnicaService;

    /**
     * pocet zaznamov v zozname ucebnych materialov zvolenej kategorie
     */
    private const POCET_ZAZNAMOV_NA_STRANU = 15;

    /**
     * KategoriaUcebnicaController constructor.
     * @param \Seka\Vzdelavanie\Services\KategoriaServiceInterface $kategoriaService
     * @param \Seka\Vzdelavanie\Services\UcebnicaServiceInterface  $ucebnicaService
     */
    public function __construct(KategoriaServiceInterface $kategoriaService, UcebnicaServiceInterface $ucebnicaService)
    {
        $this->kategoriaService = $kategoriaService;
        $this->ucebnicaService = $ucebnicaService;
    }

    /**
     * @param int $kategoriaId
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public function index(int $kategoriaId)
    {
        $kategoria = null;
        $kategorie = null;
        $ucebneMaterialy = null;

        try {
            $kategoria = $this->kategoriaService->vratKategoriuSUcebnymiMaterialmi($kategoriaId);
            $ucebneMaterialy = $this->ucebnicaService->strankovanieUcebnychMaterialovKategorie(
                $kategoriaId,
                request('page', 1),
                self::POCET_ZAZNAMOV_NA_STRANU
            );
            $kategorie = $this->kategoriaService->vratVsetky();
        } catch (ModelNotFoundException $e) {
            flash()->error('Kategória učebného materiálu neexistuje.')->important();
        } catch (Exception $e) {
            Log::error($e->getMessage(), $e->getTrace());

            flash()->error($e->getMessage())->important();
        } finally {
            return view('Vzdelavanie::partials.kniznica.kategorie.zoznam_ucebnych_materialov')
                ->withKategoria($kategoria)
                ->withKategorie($kategorie)
                ->withUcebneMaterialy($ucebneMaterialy);
        }
    }
}
