<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
use Illuminate\Pagination\Paginator;
use App\Models\Seller;
use App\Models\Quote;
use App\Models\Inquiry;
use App\Models\KycDocument;
use App\Models\Transaction;

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

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Paginator::useBootstrap();

        // Optimized Admin Sidebar Counts
        View::composer('admin.partials.sidebar', function ($view) {
            $view->with('pendingSellers', Seller::where('is_verified', false)->count());
            $view->with('pendingQuotes', Quote::where('status', 'pending')->count());
            $view->with('newInquiries', Inquiry::where('status', 'new')->count());
            $view->with('pendingKyc', KycDocument::where('status', 'pending')->count());
            $view->with('pendingTrans', Transaction::where('status', 'pending')->count());
        });

        // Share global banners with the master layout - REMOVED as per request
        // \Illuminate\Support\Facades\View::composer('layouts.master', function ($view) { ... });

        // Share data for Header (TradeIndia style)
        // Share data for Header (TradeIndia style) - Using share to ensure availability
        // Share Total Users (Buyers + Sellers, excluding Admins)
        try {
            $totalUsers = 999; // Debugging hardcoded value
            \Illuminate\Support\Facades\View::share('totalUsers', $totalUsers);
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\View::share('totalUsers', 'Err: ' . $e->getMessage());
        }

        // Share Header Cities
        try {
            // Get top cities from sellers
            $dbCities = \App\Models\Seller::whereNotNull('city')
                ->select('city')
                ->distinct()
                ->take(10)
                ->pluck('city')
                ->toArray();
            
            $staticCities = ['Delhi', 'Mumbai', 'Bangalore', 'Chennai', 'Kolkata', 'Pune', 'Ahmedabad', 'Hyderabad', 'Surat', 'Jaipur'];
            
            // Merge and unique
            $headerCities = array_unique(array_merge($dbCities, $staticCities));
            sort($headerCities);

            \Illuminate\Support\Facades\View::share('headerCities', $headerCities);
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\View::share('headerCities', ['Delhi', 'Mumbai', 'Bangalore', 'Chennai', 'Kolkata']);
        }

        // Share Categories Globally
        try {
            $categories = \App\Models\Category::whereNull('parent_id')
                ->with('children')
                ->withCount('products')
                ->take(8)
                ->get();
            
            // Fallback
            if ($categories->isEmpty()) {
                $categories = \App\Models\Category::withCount('products')->take(8)->get();
            }

            // Use View::share for simple global availability
            \Illuminate\Support\Facades\View::share('categories', $categories);
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\View::share('categories', collect());
        }

        // Dynamic Mail Configuration
        try {
            $mailSettings = \App\Models\Setting::where('group', 'email')->pluck('value', 'key');
            
            if ($mailSettings->isNotEmpty()) {
                if (isset($mailSettings['mail_mailer'])) config(['mail.default' => $mailSettings['mail_mailer']]);
                if (isset($mailSettings['mail_host'])) config(['mail.mailers.smtp.host' => $mailSettings['mail_host']]);
                if (isset($mailSettings['mail_port'])) config(['mail.mailers.smtp.port' => $mailSettings['mail_port']]);
                if (isset($mailSettings['mail_username'])) config(['mail.mailers.smtp.username' => $mailSettings['mail_username']]);
                if (isset($mailSettings['mail_password'])) config(['mail.mailers.smtp.password' => $mailSettings['mail_password']]);
                if (isset($mailSettings['mail_encryption'])) config(['mail.mailers.smtp.encryption' => $mailSettings['mail_encryption']]);
                if (isset($mailSettings['mail_from_address'])) config(['mail.from.address' => $mailSettings['mail_from_address']]);
                if (isset($mailSettings['mail_from_name'])) config(['mail.from.name' => $mailSettings['mail_from_name']]);
            }
        } catch (\Exception $e) {
            // Fallback to default config if database connection fails or settings missing
        }
    }
}
