<?php

namespace App\Livewire\Events;

use App\Domain\Event\Enums\EventStatus;
use App\Domain\Event\Enums\EventType;
use App\Domain\Event\Models\Event;
use App\Livewire\Concerns\WithSorting;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('الأحداث')]
class EventList extends Component
{
    use WithPagination, WithSorting;

    #[Url]
    public string $search = '';

    #[Url]
    public string $status = '';

    #[Url]
    public string $type = '';

    public function mount(): void
    {
        $this->authorize('events.list');

        if (! request()->has('sortBy')) {
            $this->sortBy = 'starts_at';
        }
    }

    public function updatedSearch(): void
    {
        $this->resetPage();
    }

    public function updatedStatus(): void
    {
        $this->resetPage();
    }

    public function updatedType(): void
    {
        $this->resetPage();
    }

    public function render()
    {
        $events = Event::query()
            ->when($this->search, fn ($q) => $q->where('title', 'ilike', "%{$this->search}%"))
            ->when($this->status, fn ($q) => $q->where('status', $this->status))
            ->when($this->type, fn ($q) => $q->where('type', $this->type))
            ->withCount('registrations')
            ->orderBy($this->sortBy, $this->sortDir)
            ->paginate(15);

        return view('livewire.events.event-list', [
            'events' => $events,
            'statuses' => EventStatus::cases(),
            'types' => EventType::cases(),
        ]);
    }
}
