<?php

namespace App\Http\Livewire;

use App\Models\AppNotification;
use Livewire\Attributes\On;
use Livewire\Component;

class NotificationBell extends Component
{
    public bool $open = false;

    public function toggle(): void
    {
        $this->open = ! $this->open;
    }

    #[On('notification.created')]
    public function refresh(): void
    {
        // Livewire re-renderiza con datos frescos
    }

    public function markRead(int $id): void
    {
        if (! auth()->id()) return;

        $notification = AppNotification::where('user_id', auth()->id())->find($id);
        if ($notification) {
            $notification->markAsRead();
            if ($notification->action_url) {
                $this->redirect($notification->action_url);
            }
        }
    }

    public function markAllSeen(): void
    {
        if (! auth()->id()) return;
        AppNotification::where('user_id', auth()->id())
            ->whereNull('read_at')
            ->update(['read_at' => now()]);
    }

    public function getUnreadCountProperty(): int
    {
        if (! auth()->id()) return 0;
        return AppNotification::where('user_id', auth()->id())->unread()->count();
    }

    public function getRecentProperty()
    {
        if (! auth()->id()) return collect();
        return AppNotification::where('user_id', auth()->id())
            ->orderByDesc('created_at')
            ->limit(8)
            ->get();
    }

    public function render()
    {
        return view('livewire.notification-bell', [
            'unread' => $this->unreadCount,
            'items'  => $this->recent,
        ]);
    }
}
