<?php

namespace App\Components;

use Illuminate\Notifications\DatabaseNotification;
use Livewire\Attributes\Lazy;
use Livewire\Attributes\On;
use Livewire\Component;

#[Lazy]
class NotificationBell extends Component
{
    public $notifications;
    public int $unreadCount = 0;
    public bool $open = false;
    public int $userId = 0;

    public function mount(): void
    {
        $this->userId = auth()->id();
        $this->load();
    }

    public function load(): void
    {
        $this->notifications = auth()->user()
            ->notifications()
            ->latest()
            ->limit(20)
            ->get();

        $this->unreadCount = auth()->user()->unreadNotifications()->count();
    }

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

    public function markAllRead(): void
    {
        auth()->user()->unreadNotifications()->update(['read_at' => now()]);
        $this->load();
    }

    public function markRead(string $id): void
    {
        DatabaseNotification::findOrFail($id)->markAsRead();
        $this->load();
    }

    #[On('echo-private:App.Models.User.{userId},Illuminate\\Notifications\\Events\\BroadcastNotificationCreated')]
    public function notificationReceived(): void
    {
        $this->load();
    }

    public function placeholder(): string
    {
        return '<div class="mt-4 me-4"><button type="button" class="noti-icon" style="background:none;border:none;padding:0 16px;color:white;"><i class="mdi mdi-bell-outline"></i></button></div>';
    }

    public function render()
    {
        return view('components.notification-bell');
    }
}
