<?php
/**
 * Created by PhpStorm.
 * User: radko
 * Date: 23.7.18
 * Time: 16:04
 */

namespace Seka\Vzdelavanie\Services;

use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Spatie\QueryBuilder\Filters\Filter;
use Seka\Vzdelavanie\Enums\ModelStatusEnum;
use Seka\Vzdelavanie\Repositories\Eloquent\Filters\LimitFilter;
use Seka\Vzdelavanie\Repositories\Exceptions\ModelNotFoundException;
use Seka\Vzdelavanie\Repositories\Contracts\SekciaRepositoryInterface;
use Seka\Vzdelavanie\Repositories\Contracts\UcebnicaRepositoryInterface;
use Illuminate\Database\Eloquent\ModelNotFoundException as EloquentModelNotFoundException;

/**
 * Class UcebnicaService
 * @package Seka\Vzdelavanie\Services
 */
class UcebnicaService extends Service implements UcebnicaServiceInterface
{
    /**
     * @var \Seka\Vzdelavanie\Repositories\Contracts\UcebnicaRepositoryInterface
     */
    protected $ucebnicaRepository;

    /**
     * @var \Seka\Vzdelavanie\Repositories\Contracts\SekciaRepositoryInterface
     */
    protected $sekciaRepository;

    /**
     * UcebnicaService constructor.
     * @param \Seka\Vzdelavanie\Repositories\Contracts\UcebnicaRepositoryInterface $ucebnicaRepository
     * @param \Seka\Vzdelavanie\Repositories\Contracts\SekciaRepositoryInterface   $sekciaRepository
     */
    public function __construct(
        UcebnicaRepositoryInterface $ucebnicaRepository,
        SekciaRepositoryInterface $sekciaRepository
    ) {
        $this->ucebnicaRepository = $ucebnicaRepository;
        $this->sekciaRepository = $sekciaRepository;
    }

    /**
     * @param array $udaje
     * @return \Illuminate\Database\Eloquent\Model|mixed
     * @throws \Throwable
     */
    public function vytvorit(array $udaje)
    {
        return $this->ucebnicaRepository->create($udaje);
    }

    /**
     * @param int $id
     * @return mixed|void
     * @throws \Exception
     */
    public function odstranit(int $id)
    {
        $this->ucebnicaRepository->delete($id);
    }

    /**
     * @inheritdoc
     */
    public function vratZoznamUcebnychTextov(bool $zoskupitPodlaKategorie = false)
    {
        /** @var \Illuminate\Support\Collection $ucebneTexty **/
        $ucebneTexty = $this->ucebnicaRepository->query()->get();

        if ($zoskupitPodlaKategorie) {
            $ucebneTexty = $ucebneTexty->mapToGroups(function ($ucebnyText) {
                /** @var \Seka\Vzdelavanie\Models\Ucebnica $ucebnyText*/
                return [$ucebnyText->kategoria->nazov => $ucebnyText];
            });
        }

        return $ucebneTexty;
    }

    /**
     * @param int|null $kategoriaId
     * @param int|null $strana
     * @param int|null $limit
     * @return mixed
     */
    public function strankovanieUcebnychMaterialovKategorie(int $kategoriaId = null, int $strana = null, int $limit = null)
    {
        $query = $this->ucebnicaRepository->query();

        if (false === Auth::user()->hasPermissionTo('vzdelavanie')) {
            $query->where('stav', ModelStatusEnum::PUBLIKOVANE()->value);
        }

        if (! is_null($kategoriaId)) {
            return $query
                ->where('kategoria_id', $kategoriaId)
                ->allowedSorts('nazov', 'updated_at')
                ->paginate($limit);
        }

        return $query
            ->allowedIncludes('kategoria')
            ->allowedFilters('id', 'kategoria_id', Filter::custom('limit', LimitFilter::class)->ignore(null))
            ->allowedSorts('updated_at');
    }

    /**
     * @param int $id
     * @return mixed
     * @throws \Seka\Vzdelavanie\Repositories\Exceptions\ModelNotFoundException
     */
    public function vratUcebnyText(int $id)
    {
        try {
            $query = $this->ucebnicaRepository->query();

            if (false === Auth::user()->hasPermissionTo('vzdelavanie')) {
                $query->where('stav', ModelStatusEnum::PUBLIKOVANE()->value);
            }

            return $query
                ->with('oblubene')
                ->allowedIncludes('sekcie')
                ->find($id);
        } catch (EloquentModelNotFoundException $e) {
            throw new ModelNotFoundException();
        }
    }

    /**
     * @param int   $id
     * @param array $udaje
     * @throws \Seka\Vzdelavanie\Repositories\Exceptions\ModelNotFoundException
     */
    public function upravit(int $id, array $udaje = []): void
    {
        $udaje['kategoria_id'] = $udaje['kategoria'];
        unset($udaje['kategoria']);

        $this->ucebnicaRepository->update($udaje, $id);
    }

    /**
     * @param string $text
     * @return \Illuminate\Support\Collection
     */
    public function vyhladaj(string $text): Collection
    {
        $query = $this->ucebnicaRepository->query();

        if (false === Auth::user()->hasPermissionTo('vzdelavanie')) {
            $query->where('stav', ModelStatusEnum::PUBLIKOVANE()->value);
        }

        return $query
            ->where('nazov', 'ilike', sprintf('%%%s%%', $text))
            ->orWhere('popis', 'ilike', sprintf('%%%s%%', $text))
            ->orWhere('autor', 'ilike', sprintf('%%%s%%', $text))
            ->get();
    }
}
