<?php
/**
 * Created by PhpStorm.
 * User: radko
 * Date: 2018-12-13
 * Time: 10:04
 */

namespace Seka\Portal\Modul\Vzdelavanie\Http\Controllers\Api\Backend\Kniznica;

use Exception;
use Seka\Portal\Modul\Vzdelavanie\Http\Controllers\Api\Controller;
use Seka\Portal\Modul\Vzdelavanie\Http\Resources\UcebnicaResource;
use Seka\Portal\Modul\Vzdelavanie\Repositories\Exceptions\ModelNotFoundException;
use Seka\Portal\Modul\Vzdelavanie\Services\UcebnicaServiceInterface;

/**
 * Class UcebnicaController
 *
 * @package Seka\Portal\Modul\Vzdelavanie\Http\Controllers\Api\Backend\Kniznica
 */
class UcebnicaController extends Controller
{
    /** @var \Seka\Portal\Modul\Vzdelavanie\Services\UcebnicaServiceInterface */
    private $ucebnicaService;

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

    /**
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Resources\Json\AnonymousResourceCollection
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public function index()
    {
        try {
            $ucebnice = $this->ucebnicaService->strankovanieUcebnychMaterialovKategorie()->get();
        } catch (Exception $exc) {
            return response()->json([
                'error' => $exc->getMessage() ?: class_basename($exc),
            ], 500);
        }

        return UcebnicaResource::collection($ucebnice);
    }

    /**
     * @param int $id
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public function show(int $id)
    {
        try {
            $ucebnica = $this->ucebnicaService->vratUcebnyText($id);
        } catch (ModelNotFoundException) {
            return response()->json([
                'error' => 'Učebnica s požadovaným ID neexistuje.',
            ], 404);
        } catch (Exception $exc) {
            return response()->json([
                'error' => $exc->getMessage() ?: class_basename($exc),
            ], 500);
        }

        return UcebnicaResource::make($ucebnica);
    }
}
