<?php

declare(strict_types=1);

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

use Illuminate\Database\Eloquent\Builder;
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\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|null
     */
    public ?string $state = null;
    /**
     * @var string|null
     */
    public ?string $type = null;
    /**
     * @var string
     */
    protected string $paginationTheme = 'bootstrap';
    /**
     * @var \Illuminate\Database\Eloquent\Collection|\Illuminate\Contracts\Pagination\Paginator
     */
    protected $udalosti;

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

    /**
     * @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();
    }

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

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

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

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