<?php

namespace App\View\Composers;

use App\Models\Message;
use Illuminate\View\View;

class HeaderComposer
{
    public function compose(View $view): void
    {
        if (!auth()->check()) {
            return;
        }

        $userId = auth()->id();

        // Conversaciones donde el último mensaje es del otro usuario (pendiente de respuesta)
        $pendingConversations = Message::where(function ($q) use ($userId) {
                $q->where('receiver_id', $userId)
                  ->orWhere('user_id', $userId);
            })
            ->with('sender')
            ->orderBy('created_at', 'desc')
            ->get()
            ->groupBy(function ($msg) use ($userId) {
                return $msg->user_id === $userId ? $msg->receiver_id : $msg->user_id;
            })
            ->filter(function ($msgs) use ($userId) {
                return $msgs->first()->user_id !== $userId;
            })
            ->map(fn($msgs) => $msgs->first())
            ->take(5);

        $unreadConversations  = $pendingConversations;
        $unreadMessagesCount  = $pendingConversations->count();

        // Notificaciones no leídas
        $unreadNotifications = auth()->user()
            ->unreadNotifications()
            ->latest()
            ->take(5)
            ->get();

        $unreadNotificationsCount = auth()->user()->unreadNotifications()->count();

        $view->with([
            'headerUnreadConversations'      => $unreadConversations,
            'headerUnreadMessagesCount'      => $unreadMessagesCount,
            'headerUnreadNotifications'      => $unreadNotifications,
            'headerUnreadNotificationsCount' => $unreadNotificationsCount,
        ]);
    }
}
