<?php

namespace App\Livewire\Notifications;

use App\Models\Notification;
use Livewire\Component;

class Bell extends Component
{
    public int   $unreadCount   = 0;
    public array $notifications = [];

    public function mount(): void
    {
        $this->loadNotifications();
    }

    public function refresh(): void
    {
        $userId   = auth()->id();
        $newCount = Notification::where('user_id', $userId)->whereNull('read_at')->count();

        if ($newCount > $this->unreadCount) {
            $this->dispatch('new-notification');
        }

        $this->loadNotifications();
    }

    public function markRead(string $id): void
    {
        Notification::where('user_id', auth()->id())
            ->where('id', $id)
            ->update(['read_at' => now()]);

        $this->loadNotifications();
    }

    public function markAllRead(): void
    {
        Notification::where('user_id', auth()->id())
            ->whereNull('read_at')
            ->update(['read_at' => now()]);

        $this->loadNotifications();
    }

    public function deleteNotification(string $id): void
    {
        Notification::where('user_id', auth()->id())
            ->where('id', $id)
            ->delete();

        $this->loadNotifications();
    }

    public function deleteAllRead(): void
    {
        Notification::where('user_id', auth()->id())
            ->whereNotNull('read_at')
            ->delete();

        $this->loadNotifications();
    }

    public function deleteAll(): void
    {
        Notification::where('user_id', auth()->id())->delete();
        $this->loadNotifications();
    }

    private function loadNotifications(): void
    {
        $userId = auth()->id();

        $this->unreadCount = Notification::where('user_id', $userId)
            ->whereNull('read_at')
            ->count();

        $this->notifications = Notification::where('user_id', $userId)
            ->latest()
            ->take(15)
            ->get()
            ->map(fn ($n) => [
                'id'         => $n->id,
                'type'       => $n->type,
                'title'      => $n->title,
                'message'    => $n->message,
                'read_at'    => $n->read_at?->toISOString(),
                'created_at' => $n->created_at->toISOString(),
            ])
            ->toArray();
    }

    public function render()
    {
        return view('livewire.notifications.bell');
    }
}
