<?php

declare(strict_types=1);

namespace Seka\Portal\Modul\Terminy\Http\Controllers\Frontend\Registracie;

use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Contracts\Auth\Authenticatable;
use Seka\Portal\Modul\Terminy\Entities\Udalost\Udalost;
use Seka\Portal\Modul\Terminy\Http\Controllers\Controller;
use Seka\Portal\Modul\Terminy\Exceptions\TerminyException;
use Seka\Portal\Modul\Terminy\Exceptions\UdalostSaUzKonala;
use Seka\Portal\Modul\Terminy\Exceptions\UdalostUzPrebieha;
use Seka\Portal\Modul\Terminy\Entities\Registracia\Registracia;
use Seka\Portal\Modul\Terminy\Exceptions\NaUdalostNieJePovolenaRegistracia;
use Seka\Portal\Modul\Terminy\Exceptions\PouzivatelNemaOpravnenieNaZrusenieRegistracie;

/**
 * Class PracoviskoController
 *
 * @package Seka\Portal\Modul\Terminy\Http\Controllers\Frontend\Registracie
 */
final class PracoviskoController extends Controller
{
    /**
     * @var \Illuminate\Contracts\Auth\Authenticatable
     */
    protected Authenticatable $user;

    /**
     * PracoviskoController constructor.
     *
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            $this->user = auth()->user();

            return $next($request);
        });
    }

    /**
     * @return mixed
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public function index(int $udalostId)
    {
        $udalost = Udalost::query()
            ->zverejnena()
            ->findOrFail($udalostId);

        $registracieQuery = $udalost->registracie()
            ->with('pracovisko', 'pouzivatel', 'vytvoril', 'udalost')
            ->wherePracoviskoId($this->user->pracovisko_id)
            ->orderByDesc('updated_at');

        /** @var \Illuminate\Database\Eloquent\Collection $registracieAktivne */
        $registracieAktivne = (clone $registracieQuery)->withoutTrashed()->get();
        /** @var \Illuminate\Database\Eloquent\Collection $registracieZrusene */
        $registracieZrusene = (clone $registracieQuery)->onlyTrashed()->get();

        return view('Terminy::pages.udalosti.registracie.frontend.pracovisko')
            ->withUdalost($udalost)
            ->withRegistracieAktivne($registracieAktivne)
            ->withRegistracieZrusene($registracieZrusene);
    }

    /**
     * @param int $udalostId
     * @param int $registraciaId
     *
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public function delete(int $udalostId, int $registraciaId)
    {
        try {
            /** @var \Seka\Portal\Modul\Terminy\Entities\Udalost\Udalost $udalost */
            $udalost = Udalost::query()
                ->with('registracie', 'registracie.pracovisko', 'registracie.pouzivatel', 'registracie.vytvoril')
                ->findOrFail($udalostId);

            if (false === $udalost->jePovolenaRegistracia()) {
                throw new NaUdalostNieJePovolenaRegistracia();
            }

            if ($udalost->skoncila) {
                throw new UdalostSaUzKonala();
            }

            if (true === $udalost->prebieha) {
                throw new UdalostUzPrebieha();
            }

            /** @var Registracia $registracia */
            $registracia = $udalost->registracie()->findOrFail($registraciaId);

            if ($registracia->pracovisko_id !== $this->user->pracovisko_id) {
                throw new PouzivatelNemaOpravnenieNaZrusenieRegistracie();
            }

            DB::beginTransaction();
            $registracia->delete();
            DB::commit();

            flash()->overlay('Registrácia bola úspešne zrušená')->success();
        } catch(TerminyException $e) {
            flash()->overlay($e->getMessage())->warning();
        } catch(Exception $e) {
            DB::rollBack();
            Log::error($e->getMessage(), $e->getTrace());
            flash()->overlay('Vyskytla sa neznáma chyba, ak problém pretrváva, tak kontaktujte prosím podporu.')->error();
        } finally {
            return redirect()->back();
        }
    }
}
