<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\View;
use App\Models\Announcement;
use App\Models\AnnouncementDismissal;
use App\Models\Conversation;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        // Behind Apache SSL termination the app receives plain HTTP, so
        // url()/route()/form actions and Vite assets emit http:// and get
        // blocked as mixed content. Force https when APP_URL is https.
        if (str_starts_with((string) config('app.url'), 'https://')) {
            URL::forceScheme('https');
        }

        View::composer('*', function ($view) {
            static $activeAnnouncement = null;
            static $resolved = false;
            static $unreadMessagesCount = 0;

            if (!$resolved) {
                $isAuth = auth()->check();
                $query = Announcement::live()->forAudience($isAuth)->orderBy('starts_at', 'desc');

                if ($isAuth) {
                    $dismissed = AnnouncementDismissal::where('user_id', auth()->id())
                        ->pluck('announcement_id');
                    if ($dismissed->isNotEmpty()) {
                        $query->whereNotIn('id', $dismissed);
                    }

                    // Count unread messages for authenticated users
                    $unreadMessagesCount = Conversation::whereHas('participants', function($q) {
                        $q->where('user_id', auth()->id());
                    })
                    ->whereHas('messages', function($q) {
                        $q->where('user_id', '!=', auth()->id())
                          ->where('read_at', null)
                          ->where('created_at', '>', function($subQuery) {
                              $subQuery->selectRaw('COALESCE(last_read_at, created_at)')
                                      ->from('conversation_participants')
                                      ->whereColumn('conversation_id', 'conversations.id')
                                      ->where('user_id', auth()->id())
                                      ->limit(1);
                          });
                    })
                    ->count();
                }

                $activeAnnouncement = $query->first();
                $resolved = true;
            }

            $view->with('activeAnnouncement', $activeAnnouncement)
                 ->with('unreadMessagesCount', $unreadMessagesCount);
        });
    }
}
