<?php

namespace App\Livewire\Notifications;

use App\Domain\Notification\Enums\NotificationChannel;
use App\Domain\Notification\Enums\NotificationStatus;
use App\Domain\Notification\Models\NotificationLog;
use App\Domain\Notification\Services\NotificationService;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

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

    #[Url]
    public string $filter = 'all';

    public function markAsRead(int $id, NotificationService $service): void
    {
        $service->markAsRead($id);
    }

    public function markAllAsRead(): void
    {
        NotificationLog::where('recipient_type', 'user')
            ->where('recipient_id', auth()->id())
            ->where('channel', NotificationChannel::InApp)
            ->where('status', NotificationStatus::Sent)
            ->update(['read_at' => now(), 'status' => NotificationStatus::Read->value]);
    }

    public function render()
    {
        $query = NotificationLog::where('recipient_type', 'user')
            ->where('recipient_id', auth()->id())
            ->where('channel', NotificationChannel::InApp)
            ->when($this->filter === 'unread', fn ($q) => $q->where('status', NotificationStatus::Sent))
            ->orderByDesc('created_at');

        $unreadCount = NotificationLog::where('recipient_type', 'user')
            ->where('recipient_id', auth()->id())
            ->where('channel', NotificationChannel::InApp)
            ->where('status', NotificationStatus::Sent)
            ->count();

        return view('livewire.notifications.notification-center', [
            'notifications' => $query->paginate(20),
            'unreadCount' => $unreadCount,
        ]);
    }
}
