<?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()
    {
        // Event uses BelongsToBranch in shared mode, so the global scope already
        // returns this branch's events plus the academy-wide ones. The old
        // whereHas('facility') clause did the opposite of isolation: it dropped
        // every event with a null facility_id — i.e. every external-location
        // event — out of every branch the moment a branch was selected.
        $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(),
        ]);
    }
}
