<?php

declare(strict_types=1);

namespace Seka\Portal\Modul\Terminy\Livewire\Backend\Udalosti\Components\Registracie\Components;

use Illuminate\View\View;
use Livewire\Attributes\Locked;
use Livewire\Attributes\On;
use Livewire\Component;
use Seka\Portal\Modul\Terminy\Entities\Registracia\StavRegistracie;
use Seka\Portal\Modul\Terminy\Entities\Udalost\Udalost;

/**
 * Class Zoznam
 */
class Zoznam extends Component
{
    private const PER_PAGE = 15;

    #[Locked]
    public int $udalostId;

    public ?string $filterPek = null;

    public ?StavRegistracie $filterStavRegistracie = StavRegistracie::AKTIVNA;

    protected int $sort = 0;

    public function mount(Udalost $udalost): void
    {
        $this->udalostId = $udalost->id;
    }

    /**
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public function render(): View
    {
        $udalost = Udalost::query()->findOrFail($this->udalostId);
        $registracieRelation = $udalost->registracie();
        $registracieRelation = match ($this->filterStavRegistracie) {
            StavRegistracie::AKTIVNA => $registracieRelation,
            StavRegistracie::ZRUSENA => $registracieRelation->onlyTrashed(),
            default => $registracieRelation->withTrashed(),
        };

        if ($this->filterPek) {
            $registracieRelation = $registracieRelation->withWhereHas('pracovisko', function ($query) {
                $query->where('kod', $this->filterPek);
            });
        }

        $registracie = $registracieRelation
            ->orderBy('created_at', $this->sort ? 'asc' : 'desc')
            ->paginate(self::PER_PAGE);

        return view(
            'Terminy::livewire.backend.udalosti.components.registracie.components.zoznam',
            compact('udalost', 'registracie'),
        );
    }

    #[On('filterPodlaStavuRegistracie')]
    public function nastavFilterPodlaStavuRegistracie(string $stavRegistracie = ''): void
    {
        $this->filterStavRegistracie = StavRegistracie::tryFrom($stavRegistracie);
    }

    #[On('filterPodlaPracoviska')]
    public function nastavFilterPodlaRegistraciiZPracoviska(?string $kodPracoviska = null): void
    {
        $this->filterPek = empty($kodPracoviska) ? null : $kodPracoviska;
    }

    #[On('zoraditZoznamRegistracie')]
    public function zoradZoznamRegistracii(int $sort): void
    {
        $this->sort = $sort;
    }
}
