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

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

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

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

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

    /**
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    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 \Seka\Vzdelavanie\Http\Resources\UcebnicaResource
     */
    public function show(int $id)
    {
        try {
            $ucebnica = $this->ucebnicaService->vratUcebnyText($id);
        } catch (ModelNotFoundException $exc) {
            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);
    }
}
