<?php

declare(strict_types=1);

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

use Illuminate\Database\Eloquent\Builder;
use Livewire\Attributes\On;
use Livewire\Component;
use Livewire\WithPagination;
use Seka\Portal\Modul\Terminy\Entities\Udalost\DruhUdalosti;
use Seka\Portal\Modul\Terminy\Entities\Udalost\StavUdalosti;
use Seka\Portal\Modul\Terminy\Entities\Udalost\Udalost;

/**
 * Class Zoznam
 *
 * @package Seka\Portal\Modul\Terminy\Livewire\Components\Udalosti
 */
abstract class Zoznam extends Component
{
    use WithPagination;

    /**
     * @var int
     */
    protected const PER_PAGE = 15;

    /**
     * @var int
     */
    public int $sort = 0;

    /**
     * @var string|null
     */
    public ?string $state = null;

    /**
     * @var string|null
     */
    public ?string $type = null;

    /**
     * @param string|null $stav
     */
    #[On('filtrovatPodlaStavuUdalosti')]
    public function filterByState(string $stav = null): void
    {
        $this->state = $stav;

        $this->resetPage();
    }

    /**
     * @param string|null $druhUdalosti
     */
    #[On('filtrovatPodlaDruhuUdalosti')]
    public function filterByScheduleType(string $druhUdalosti = null): void
    {
        $this->type = $druhUdalosti;

        $this->resetPage();
    }

    /**
     * @return \Illuminate\Database\Eloquent\Builder
     */
    protected function getQuery(): Builder
    {
        $query = Udalost::withTrashed()->with('vytvoril');

        if (!is_null($this->state) && StavUdalosti::tryFrom($this->state)) {
            $query = $query->where('stav', $this->state);
        }

        if (!is_null($this->type) && DruhUdalosti::tryFrom($this->type)) {
            $query = $query->where('druh', $this->type);
        }

        return $query->orderBy('datum_od', $this->sort ? 'asc' : 'desc');
    }
}
