<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\View;
use Google\Cloud\Firestore\FirestoreClient;
use Google\Cloud\Core\Exception\FailedPreconditionException;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Paginator::useBootstrap();

        View::composer('partials.header', function ($view) {
            $adminNotifications = [];
            $recentMessages     = [];

            try {
                $fs = new FirestoreClient([
                    'projectId'   => env('FIREBASE_PROJECT_ID'),
                    'keyFilePath' => base_path(env('FIREBASE_CREDENTIALS')),
                    'transport'   => 'rest',
                ]);

               
                $supportChats = $fs->collection('supportChats')->listDocuments();
                foreach ($supportChats as $userRef) {
                    $userEmail = $userRef->id();

                   
                    $docs = $userRef
                        ->collection('adminMessages')
                        ->documents();

                    foreach ($docs as $doc) {
                        if (! $doc->exists()) {
                            continue;
                        }
                        $data = $doc->data();
                        $ts   = $data['timestamp'] ?? null;
                        $time = ($ts && method_exists($ts, 'get'))
                              ? $ts->get()->setTimezone(new \DateTimeZone('Asia/Kolkata'))
                              : null;

                        $adminNotifications[] = [
                            'user_email' => $userEmail,
                            'message'    => $data['text'] ?? '',
                            'time'       => $time,
                        ];
                    }
                }

               
                usort($adminNotifications, fn($a,$b)=>
                    ($b['time']?->getTimestamp()?:0)
                    <=>
                    ($a['time']?->getTimestamp()?:0)
                );
                $adminNotifications = array_slice($adminNotifications, 0, 5);

               
                foreach ($supportChats as $userRef) {
                    $userEmail = $userRef->id();

                    $docs = $userRef
                        ->collection('messages')
                        ->documents();

                    foreach ($docs as $doc) {
                        if (! $doc->exists()) {
                            continue;
                        }
                        $data = $doc->data();
                        $ts   = $data['timestamp'] ?? null;
                        $time = ($ts && method_exists($ts, 'get'))
                              ? $ts->get()->setTimezone(new \DateTimeZone('Asia/Kolkata'))
                              : null;

                        $recentMessages[] = [
                            'user_email' => $userEmail,
                            'text'       => $data['text'] ?? '',
                            'time'       => $time,
                        ];
                    }
                }

               
                usort($recentMessages, fn($a,$b)=>
                    ($b['time']?->getTimestamp()?:0)
                    <=>
                    ($a['time']?->getTimestamp()?:0)
                );
                $recentMessages = array_slice($recentMessages, 0, 4);

            } catch (FailedPreconditionException $e) {
                // missing index? nothing to do—arrays stay empty
            } catch (\Throwable $e) {
                \Log::error('Header Firestore error: '.$e->getMessage());
            }

            
            $view->with([
                'adminNotifications' => $adminNotifications,
                'recentMessages'     => $recentMessages,
            ]);
        });
    }
}
