<?php

declare(strict_types=1);

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

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

/**
 * Class Zoznam
 *
 * @package Seka\Portal\Modul\Terminy\Http\Controllers\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
     */
    protected string $paginationTheme = 'bootstrap';

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

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

    /**
     * @var \Illuminate\Database\Eloquent\Collection|\Illuminate\Contracts\Pagination\Paginator
     */
    protected $udalosti;

    /**
     * @var string<string, string>
     */
    protected $listeners = [
        'filtrovatPodlaStavuUdalosti' => 'filterByState',
        'filtrovatPodlaDruhuUdalosti' => 'filterByScheduleType',
    ];

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

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

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

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

    /**
     * @param string|null $stav
     */
    public function filterByState(string $stav = null): void
    {
        $this->state = $stav;

        $this->resetPage();
    }

    /**
     * @param string|null $druhUdalosti
     */
    public function filterByScheduleType(string $druhUdalosti = null): void
    {
        $this->type = $druhUdalosti;

        $this->resetPage();
    }
}
