<?php

namespace App\Livewire\Notifications;

use App\Domain\Notification\Enums\NotificationChannel;
use App\Domain\Notification\Models\NotificationTemplate;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('قوالب الإشعارات')]
class NotificationTemplateList extends Component
{
    use WithPagination;

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

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

    public function mount(): void
    {
        $this->authorize('notifications.manage');
    }

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

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

    public function toggleActive(int $templateId): void
    {
        $template = NotificationTemplate::findOrFail($templateId);
        $template->update(['is_active' => !$template->is_active]);
    }

    public function render()
    {
        $query = NotificationTemplate::query()
            ->when($this->search, function ($q) {
                $search = $this->search;
                $q->where(function ($q2) use ($search) {
                    $q2->where('event_type', 'ilike', "%{$search}%")
                       ->orWhere('subject', 'ilike', "%{$search}%");
                });
            })
            ->when($this->channelFilter, fn ($q) => $q->where('channel', $this->channelFilter))
            ->orderByDesc('created_at');

        return view('livewire.notifications.notification-template-list', [
            'templates' => $query->paginate(20),
            'channels' => NotificationChannel::cases(),
        ]);
    }
}
