<?php

declare(strict_types=1);

namespace Seka\Portal\Modul\Terminy\Livewire\Backend\MoznostiUdalosti\Components;

use Exception;
use Illuminate\Contracts\View\View;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Locked;
use Livewire\Component;
use Seka\Portal\Modul\Terminy\Entities\MoznostiUdalosti\MoznostUdalosti;
use Seka\Portal\Modul\Terminy\Entities\MoznostiUdalosti\StavMoznostiUdalostiEnum;

/**
 * Class Form
 *
 * @package Seka\Portal\Modul\Terminy\Livewire\Backend\MoznostiUdalosti\Components
 */
final class Form extends Component
{
    use AuthorizesRequests;

    #[Locked]
    public ?int $id = null;
    public ?string $nazov;
    public ?string $kod;
    public ?StavMoznostiUdalostiEnum $stav;
    public bool $exists = false;
    public bool $trashed = false;

    public function mount(?MoznostUdalosti $moznostUdalosti = null): void
    {
        $this->fill($moznostUdalosti?->only('id', 'nazov', 'kod', 'stav'));
        $this->exists = $moznostUdalosti?->exists;
        $this->trashed = $moznostUdalosti?->trashed();
    }

    /**
     * @return \Illuminate\Contracts\View\View
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public function render(): View
    {
        return view('Terminy::livewire.backend.moznosti-udalosti.components.form');
    }

    /**
     * @throws \Illuminate\Validation\ValidationException
     * @throws \Throwable
     */
    public function save()
    {
        $this->validate();

        try {
            $this->authorize('terminy');

            DB::beginTransaction();

            $moznostUdalosti = new MoznostUdalosti();

            if ($this->exists) {
                $moznostUdalosti = MoznostUdalosti::query()->findOrFail($this->id);
            }

            $moznostUdalosti->fill($this->except('id'));
            $moznostUdalosti->vytvoril()->associate(auth()->user());
            $moznostUdalosti->save();

            DB::commit();

            if ($this->exists) {
                $message = 'Možnosť udalosti bola aktualizovaná';
            } else {
                $message = 'Nová možnosť udalosti bola vytvorená';
            }

            flash()->overlay($message, 'Hlásenie')->success();
        } catch (Exception $e) {
            DB::rollBack();

            Log::error($e->getMessage(), $e->getTrace());

            flash()->overlay('Možnosť udalosti nebola úspešne uložená.', 'Hlásenie')->error();
        } finally {
            return redirect()->route('modul.terminy.backend.moznostiUdalosti.index');
        }
    }

    /**
     * Obnovit zneplatnenú možnosť udalosti
     *
     * @throws \Throwable
     */
    public function restore()
    {
        try {
            $this->authorize('terminy');

            if (!$this->trashed || !$this->exists) {
                return;
            }

            DB::beginTransaction();

            MoznostUdalosti::onlyTrashed()->findOrFail($this->id)->restore();

            DB::commit();

            flash()->overlay('Možnosť udalosti bola úspešne obnovená', 'Hlásenie')->success();
        } catch (Exception $e) {
            DB::rollBack();

            Log::error($e->getMessage(), $e->getTrace());

            flash()->overlay('Možnosť udalosti sa nepodarilo obnoviť.', 'Hlásenie')->error();
        } finally {
            return redirect()->route('modul.terminy.backend.moznostiUdalosti.index');
        }
    }

    /**
     * Zneplatnit možnosť udalosti
     *
     * @throws \Throwable
     */
    public function trash()
    {
        try {
            $this->authorize('terminy');

            DB::beginTransaction();

            if ($this->trashed || !$this->exists) {
                return;
            }

            // soft delete
            MoznostUdalosti::query()->findOrFail($this->id)->delete();

            DB::commit();

            flash()->overlay('Možnosť udalosti bola úspešne zneplatnená', 'Hlásenie')->success();

            return redirect()->route('modul.terminy.backend.moznostiUdalosti.index');
        } catch (Exception $e) {
            DB::rollBack();

            Log::error($e->getMessage(), $e->getTrace());

            flash()->overlay('Možnosť udalosti nebola zneplatnená.', 'Hlásenie')->error();
        } finally {
            return redirect()->route('modul.terminy.backend.moznostiUdalosti.index');
        }
    }

    /**
     * @return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public function cancel()
    {
        return redirect()->route('modul.terminy.backend.moznostiUdalosti.index');
    }

    /**
     * @return string[]
     */
    public function rules(): array
    {
        return [
            'nazov' => 'required',
            'stav' => [
                'required',
                Rule::enum(StavMoznostiUdalostiEnum::class),
            ],
        ];
    }

    /**
     * @return string[]
     */
    public function messages(): array
    {
        return [
            'nazov.required' => 'Názov možnosti udalosti je vyžadovaný',
            'stav.required' => 'Stav možnosti udalosti je vyžadovaný',
            'stav.enum' => 'Neznámi stav možnosti udalosti',
        ];
    }
}
