<?php

declare(strict_types=1);

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

use Livewire\Component;
use Livewire\WithPagination;
use Seka\Terminy\Models\Udalost\Udalost;
use Illuminate\Database\Eloquent\Builder;
use Seka\Terminy\Models\Udalost\StavUdalosti;
use Seka\Terminy\Models\Udalost\DruhUdalosti;

/**
 * Class Zoznam
 *
 * @package Seka\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::query()->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('updated_at', $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();
    }
}
