<?php

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

use Exception;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Seka\Vzdelavanie\Http\Controllers\Controller;
use Seka\Vzdelavanie\Services\SekciaServiceInterface;
use Seka\Vzdelavanie\Services\UcebnicaServiceInterface;
use Seka\Vzdelavanie\Events\Kniznica\UcebnyMaterialOpened;

/**
 * Class UcebnicaController
 * @package Seka\Vzdelavanie\Http\Controllers\Frontend\Kniznica
 */
final class UcebnicaController extends Controller
{
    /**
     * @var \Seka\Vzdelavanie\Services\SekciaServiceInterface
     */
    protected $sekciaService;

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

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

    /**
     * @param int $vzdKnzncUcbnMtrlId
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public function show(int $vzdKnzncUcbnMtrlId)
    {
        $ucebnyText = null;
        $sekcie = null;

        try {
            $ucebnyText = $this->ucebnicaService->vratUcebnyText($vzdKnzncUcbnMtrlId);
            $sekcie = $this->sekciaService->vratZoznamSekciiUcebnehoTextu($vzdKnzncUcbnMtrlId, true);
            event(new UcebnyMaterialOpened($ucebnyText, Auth::user()));
        } catch (Exception $e) {
            Log::error($e->getMessage(), $e->getTrace());

            flash()->error($e->getMessage())->important();
        } finally {
            return view('Vzdelavanie::pages.kniznica.ucebne_materialy.show')
                ->withUcebnyText($ucebnyText)
                ->withSekcie($sekcie);
        }
    }
}
