<?php

namespace App\Livewire\Backend\Pouzivatelia;

use App\Models\Pouzivatel\Pouzivatel;
use Illuminate\Contracts\View\View;
use Livewire\Attributes\On;
use Livewire\Component;
use Livewire\WithPagination;

/**
 * Class Zoznam
 *
 * @package App\Livewire\Backend\Pouzivatelia
 */
class Zoznam extends Component
{
    use WithPagination;

    private const PER_PAGE = 15;

    public int $sort = 0;
    public ?string $kodPek = null;

    public function render(): View
    {
        $query = Pouzivatel::query();

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

        $pouzivatelia = $query->orderBy(
            'datum_posledneho_prihlasenia',
            $this->sort ? 'asc' : 'desc',
        )->paginate(self::PER_PAGE);

        return view('livewire.backend.pouzivatelia.zoznam', compact('pouzivatelia'));
    }

    public function updatedSort(int $sort): void
    {
        $this->sort = $sort;
    }

    #[On('filterByPekCode')]
    public function pekFilter(?string $kodPek): void
    {
        $this->kodPek = empty($kodPek) ? null : $kodPek;
    }
}