<?php

namespace App\Livewire\User;

use Livewire\Component;
use Livewire\Attributes\On;
use Illuminate\Support\Facades\Auth;
use App\Models\Notification;

class NotificationBell extends Component
{
    public $layout; // 'desktop' or 'mobile'

    #[On('order-created')]
    #[On('notification-updated')]
    public function refreshNotif()
    {
        // Re-renders the component with real-time notification data
    }

    public function markAllRead()
    {
        Notification::where('id_user', Auth::user()->id_user)->where('is_read', false)->update(['is_read' => true]);
    }

    public function deleteNotif($id)
    {
        Notification::where('id_notification', $id)->where('id_user', Auth::user()->id_user)->delete();
    }

    public function deleteAllNotif()
    {
        Notification::where('id_user', Auth::user()->id_user)->delete();
    }

    public function render()
    {
        $user = Auth::user();
        if (!$user) {
            return <<<'HTML'
                <div></div>
            HTML;
        }

        $notifikasi = Notification::where('id_user', $user->id_user)
            ->where('created_at', '>=', now()->subDay())
            ->orderBy('created_at', 'desc')
            ->take(10)
            ->get();

        $unreadCount = Notification::where('id_user', $user->id_user)
            ->where('is_read', false)
            ->where('created_at', '>=', now()->subDay())
            ->count();

        return view('livewire.user.notification-bell', [
            'notifikasi' => $notifikasi,
            'unreadCount' => $unreadCount,
        ]);
    }
}
