<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Livewire\Livewire;

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

    public function boot(): void
    {
        // Fix for MySQL key length limits on older engines on shared hosting
        \Illuminate\Support\Facades\Schema::defaultStringLength(191);

        // Register Livewire storefront components
        Livewire::component('storefront.product-list', \App\Http\Livewire\Storefront\ProductList::class);

        if (! app()->runningInConsole()) {
            $root = request()->root();
            config([
                'app.url' => $root,
                'filesystems.disks.public.url' => $root . '/storage',
            ]);
        }

        try {
            if (\Illuminate\Support\Facades\Schema::hasTable('settings')) {
                $smtpHost = \App\Models\Setting::getValue('smtp_host');
                if ($smtpHost) {
                    config([
                        'mail.mailers.smtp.host' => $smtpHost,
                        'mail.mailers.smtp.port' => (int) \App\Models\Setting::getValue('smtp_port', 587),
                        'mail.mailers.smtp.username' => \App\Models\Setting::getValue('smtp_username'),
                        'mail.mailers.smtp.password' => \App\Models\Setting::getValue('smtp_password'),
                        'mail.mailers.smtp.encryption' => \App\Models\Setting::getValue('smtp_encryption', 'tls'),
                        'mail.from.address' => \App\Models\Setting::getValue('smtp_from_address', 'no-reply@sawdabazar.com'),
                        'mail.from.name' => \App\Models\Setting::getValue('smtp_from_name', config('app.name', 'Sawdabazar')),
                    ]);
                }

                // Dynamic Storage Configuration
                $activeDisk = \App\Models\Setting::getValue('active_storage_disk', 'public');
                $r2Bucket = \App\Models\Setting::getValue('r2_bucket');
                if ($activeDisk === 'r2' && !empty($r2Bucket)) {
                    config([
                        'filesystems.default'          => 'r2',
                        'filesystems.disks.r2.key'     => \App\Models\Setting::getValue('r2_access_key_id'),
                        'filesystems.disks.r2.secret'  => \App\Models\Setting::getValue('r2_secret_access_key'),
                        'filesystems.disks.r2.region'  => \App\Models\Setting::getValue('r2_region', 'auto'),
                        'filesystems.disks.r2.bucket'  => $r2Bucket,
                        'filesystems.disks.r2.endpoint'=> \App\Models\Setting::getValue('r2_endpoint'),
                        'filesystems.disks.r2.url'     => \App\Models\Setting::getValue('r2_url'),
                        'backup.backup.destination.disks' => ['local', 'r2'],
                        // Spatie MediaLibrary: also use R2 for product/category images
                        'media-library.disk_name'      => 'r2',
                    ]);
                } else {
                    config([
                        'filesystems.default'          => 'public',
                        'backup.backup.destination.disks' => ['local'],
                        // Spatie MediaLibrary: use public disk for product/category images
                        'media-library.disk_name'      => 'public',
                    ]);
                }

                // Dynamic backup encryption password
                $backupPassword = \App\Models\Setting::getValue('backup_encryption_password');
                if (!empty($backupPassword)) {
                    config([
                        'backup.backup.password' => $backupPassword,
                        'backup.backup.encryption' => 'default',
                    ]);
                } else {
                    config([
                        'backup.backup.password' => null,
                        'backup.backup.encryption' => 'none',
                    ]);
                }
            }
        } catch (\Exception $e) {
            // Silence DB exception during early bootstrap/migrations
        }

        // Sync uploaded favicon to public/favicon.ico if missing (e.g. after deploy/server restart)
        try {
            if (!app()->runningInConsole() && \Illuminate\Support\Facades\Schema::hasTable('settings')) {
                $faviconSetting = \App\Models\Setting::getValue('admin_favicon');
                if ($faviconSetting) {
                    $source = storage_path('app/public/' . $faviconSetting);
                    $publicIco = public_path('favicon.ico');
                    $publicPng = public_path('favicon.png');
                    if (file_exists($source)) {
                        if (!file_exists($publicIco) || filemtime($source) > filemtime($publicIco)) {
                            @copy($source, $publicIco);
                            @copy($source, $publicPng);
                        }
                    }
                }
            }
        } catch (\Exception $e) {
            // Silence favicon sync errors
        }

        // Listen to login success events
        \Illuminate\Support\Facades\Event::listen(
            \Illuminate\Auth\Events\Login::class,
            function ($event) {
                \App\Services\AuditLogger::log(
                    'login_success',
                    'User logged in successfully: ' . $event->user->name . ' (' . $event->user->email . ')',
                    null,
                    null,
                    $event->user->id
                );
            }
        );

        // Listen to login failure events
        \Illuminate\Support\Facades\Event::listen(
            \Illuminate\Auth\Events\Failed::class,
            function ($event) {
                $email = $event->credentials['email'] ?? 'unknown';
                \App\Services\AuditLogger::log(
                    'login_failed',
                    'Failed login attempt for email: ' . $email
                );
            }
        );

        // Prevent browser forced dark mode color inversion issues
        \Filament\Support\Facades\FilamentView::registerRenderHook(
            'panels::head.end',
            fn (): string => new \Illuminate\Support\HtmlString('<meta name="color-scheme" content="light">')
        );

        // Make Filament tables horizontally scrollable on mobile
        \Filament\Support\Facades\FilamentView::registerRenderHook(
            'panels::body.start',
            fn (): string => new \Illuminate\Support\HtmlString(
                '<style>' .
                'html { scrollbar-gutter: stable !important; }' .
                '@media (max-width: 1023px) { .fi-ta-table { min-width: 950px !important; } }' .
                '@media (max-width: 639px) {' .
                '    .fi-ta-header-toolbar { flex-direction: row-reverse !important; flex-wrap: nowrap !important; align-items: center !important; justify-content: space-between !important; gap: 8px !important; }' .
                '    .fi-ta-header-toolbar > div { width: auto !important; }' .
                '    .fi-ta-header-toolbar > div:last-child { flex-shrink: 1 !important; min-width: 0 !important; }' .
                '    .fi-ta-header-toolbar input { min-width: 80px !important; width: 100% !important; }' .
                '    .fi-ta-header-toolbar .fi-ta-actions { flex-shrink: 0 !important; }' .
                '    .fi-ta-selection-indicator { display: flex !important; flex-direction: row !important; align-items: center !important; justify-content: space-between !important; padding: 8px 12px !important; gap: 8px !important; }' .
                '    .fi-ta-selection-indicator span { font-size: 11.5px !important; }' .
                '    .fi-ta-selection-indicator button { font-size: 11.5px !important; font-weight: 600 !important; }' .
                '}' .
                '.fi-ta-ctn:has(.fi-ta-empty-state) { overflow-x: auto !important; }' .
                '.fi-ta-ctn:has(.fi-ta-empty-state) .fi-ta-content { overflow-x: visible !important; }' .
                '/* Premium Segmented Tabs styling - Light Mode */' .
                'html:not(.dark) .fi-ta-header-ctn .fi-tabs, html:not(.dark) .fi-ta-content .fi-tabs { background: #f8fafc !important; border: 1px solid #e2e8f0 !important; }' .
                'html:not(.dark) .fi-ta-header-ctn .fi-tabs-item, html:not(.dark) .fi-ta-content .fi-tabs-item { color: #64748b !important; }' .
                'html:not(.dark) .fi-ta-header-ctn .fi-tabs-item:hover:not(.fi-active), html:not(.dark) .fi-ta-content .fi-tabs-item:hover:not(.fi-active) { background-color: #f1f5f9 !important; color: #334155 !important; }' .
                'html:not(.dark) .fi-ta-header-ctn .fi-tabs-item:not(.fi-active) svg, html:not(.dark) .fi-ta-content .fi-tabs-item:not(.fi-active) svg { color: #94a3b8 !important; }' .
                '/* Premium Segmented Tabs styling - Dark Mode */' .
                '.dark .fi-ta-header-ctn .fi-tabs, .dark .fi-ta-content .fi-tabs { background: #18181b !important; border: 1px solid #27272a !important; }' .
                '.dark .fi-ta-header-ctn .fi-tabs-item, .dark .fi-ta-content .fi-tabs-item { color: #a1a1aa !important; }' .
                '.dark .fi-ta-header-ctn .fi-tabs-item:hover:not(.fi-active), .dark .fi-ta-content .fi-tabs-item:hover:not(.fi-active) { background-color: #27272a !important; color: #ffffff !important; }' .
                '.dark .fi-ta-header-ctn .fi-tabs-item:not(.fi-active) svg, .dark .fi-ta-content .fi-tabs-item:not(.fi-active) svg { color: #71717a !important; }' .
                '/* Premium Segmented Tabs styling - Common Base Styles */' .
                '.fi-ta-header-ctn .fi-tabs, .fi-ta-content .fi-tabs { border-radius: 12px !important; padding: 5px !important; display: inline-flex !important; flex-wrap: wrap !important; gap: 4px !important; width: auto !important; margin-bottom: 24px !important; box-shadow: inset 0 2px 4px 0 rgba(0, 0, 0, 0.04) !important; }' .
                '.fi-ta-header-ctn .fi-tabs-item, .fi-ta-content .fi-tabs-item { background: transparent !important; border: none !important; border-radius: 8px !important; padding: 8px 16px !important; font-size: 13.5px !important; font-weight: 600 !important; transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1) !important; display: inline-flex !important; align-items: center !important; gap: 6px !important; cursor: pointer !important; box-shadow: none !important; margin: 0 !important; }' .
                '/* Premium Segmented Tabs styling - Active Tab (Common Highlight) */' .
                '.fi-ta-header-ctn .fi-tabs-item.fi-active, .fi-ta-content .fi-tabs-item.fi-active { background-color: var(--primary-600) !important; color: #ffffff !important; box-shadow: 0 4px 10px -2px color-mix(in srgb, var(--primary-600) 40%, transparent) !important; border: none !important; }' .
                '.fi-ta-header-ctn .fi-tabs-item.fi-active *, .fi-ta-content .fi-tabs-item.fi-active *, .fi-ta-header-ctn .fi-tabs-item.fi-active span, .fi-ta-content .fi-tabs-item.fi-active span, .fi-ta-header-ctn .fi-tabs-item.fi-active svg, .fi-ta-content .fi-tabs-item.fi-active svg, .fi-ta-header-ctn .fi-tabs-item.fi-active .fi-tabs-item-label, .fi-ta-content .fi-tabs-item.fi-active .fi-tabs-item-label { color: #ffffff !important; }' .
                '.fi-ta-header-ctn .fi-tabs-item.fi-active .fi-badge, .fi-ta-content .fi-tabs-item.fi-active .fi-badge { background-color: #ffffff !important; }' .
                                '.fi-ta-header-ctn .fi-tabs-item.fi-active .fi-badge *, .fi-ta-content .fi-tabs-item.fi-active .fi-badge * { color: var(--primary-600) !important; }' .
                '/* Stabilize vertical settings tab list width to prevent layout shift/blinking */' .
                '@media (min-width: 768px) {' .
                '    .fi-sc-tabs.fi-vertical { display: flex !important; flex-direction: row !important; align-items: flex-start !important; gap: 24px !important; }' .
                '    .fi-sc-tabs.fi-vertical > nav.fi-tabs.fi-vertical { width: 250px !important; min-width: 250px !important; flex-shrink: 0 !important; }' .
                '    .fi-sc-tabs.fi-vertical > :not(nav) { flex-grow: 1 !important; min-width: 0 !important; }' .
                '}' .
                '/* Premium Matte Black Header (Topbar) styling */' .
                '.fi-topbar { background-color: #18181b !important; border-bottom: 1px solid #27272a !important; }' .
                '.fi-topbar svg, .fi-topbar button, .fi-topbar a, .fi-topbar span { color: #ffffff !important; }' .
                '/* Global search wrapper & input styling on dark header */' .
                '.fi-global-search-field { background-color: transparent !important; }' .
                '.fi-global-search-field .fi-input-wrp { background-color: #27272a !important; border-color: #3f3f46 !important; box-shadow: none !important; --tw-ring-color: transparent !important; --tw-ring-shadow: none !important; }' .
                '.fi-global-search-field input { color: #ffffff !important; }' .
                '.fi-global-search-field svg, .fi-global-search-field svg * { color: #ffffff !important; }' .
                '.fi-global-search-field ::placeholder, .fi-global-search-field input::placeholder { color: #a1a1aa !important; opacity: 1 !important; }' .
                '/* Reset colors inside dropdown panels for Light Mode only */' .
                'html:not(.dark) .fi-dropdown-panel a, html:not(.dark) .fi-dropdown-panel button, html:not(.dark) .fi-dropdown-panel span, html:not(.dark) .fi-dropdown-panel svg, html:not(.dark) .fi-dropdown-panel div, html:not(.dark) .fi-dropdown-panel li { color: #1f2937 !important; }' .
                'html:not(.dark) .fi-dropdown-panel a:hover, html:not(.dark) .fi-dropdown-panel button:hover { background-color: #f3f4f6 !important; }' .
                '/* Reset colors inside dropdown panels for Dark Mode */' .
                '.dark .fi-dropdown-panel a, .dark .fi-dropdown-panel button, .dark .fi-dropdown-panel span, .dark .fi-dropdown-panel svg, .dark .fi-dropdown-panel div, .dark .fi-dropdown-panel li { color: #ffffff !important; }' .
                '.dark .fi-dropdown-panel a:hover, .dark .fi-dropdown-panel button:hover { background-color: #27272a !important; }' .
                '/* Topbar logo section (above the sidebar menu) should match the header dark Zinc background */' .
                 '.fi-main-ctn-sidebar-open .fi-topbar-start { width: 16rem !important; background-color: #18181b !important; border-right: 1px solid #27272a !important; border-bottom: 1px solid #27272a !important; padding-left: 1.5rem !important; padding-right: 1.5rem !important; height: 100% !important; display: flex !important; align-items: center !important; gap: 1rem !important; transition: width 75ms ease-in-out !important; }' .
                 '.fi-main-ctn:not(.fi-main-ctn-sidebar-open) .fi-topbar-start { width: 4.5rem !important; background-color: #18181b !important; border-right: 1px solid #27272a !important; border-bottom: 1px solid #27272a !important; padding-left: 0 !important; padding-right: 0 !important; height: 100% !important; display: flex !important; align-items: center !important; justify-content: center !important; transition: width 75ms ease-in-out !important; }' .
                '.fi-topbar-start .fi-logo { color: #ffffff !important; font-weight: 700 !important; }' .
                '/* Premium Sidebar Submenu Indicator Lines - Light Mode */' .
                'html:not(.dark) .fi-main-sidebar.fi-sidebar-open .fi-sidebar-group[data-group-label]:not([data-group-label=""]) .fi-sidebar-group-items { border-left: 1.5px solid #e2e8f0 !important; }' .
                'html:not(.dark) .fi-main-sidebar.fi-sidebar-open .fi-sidebar-group[data-group-label]:not([data-group-label=""]) .fi-sidebar-group-items li::after { background-color: #e2e8f0 !important; }' .
                '/* Premium Sidebar Submenu Indicator Lines - Dark Mode */' .
                '.dark .fi-main-sidebar.fi-sidebar-open .fi-sidebar-group[data-group-label]:not([data-group-label=""]) .fi-sidebar-group-items { border-left: 1.5px solid #3f3f46 !important; }' .
                '.dark .fi-main-sidebar.fi-sidebar-open .fi-sidebar-group[data-group-label]:not([data-group-label=""]) .fi-sidebar-group-items li::after { background-color: #3f3f46 !important; }' .
                '/* Premium Sidebar Submenu Base Styles (Common) */' .
                '.fi-main-sidebar.fi-sidebar-open .fi-sidebar-group[data-group-label]:not([data-group-label=""]) .fi-sidebar-group-items { margin-left: 19px !important; padding-left: 12px !important; display: flex !important; flex-direction: column !important; gap: 4px !important; margin-top: 4px !important; margin-bottom: 4px !important; }' .
                '.fi-main-sidebar.fi-sidebar-open .fi-sidebar-group[data-group-label]:not([data-group-label=""]) .fi-sidebar-group-items li { position: relative !important; }' .
                '.fi-main-sidebar.fi-sidebar-open .fi-sidebar-group[data-group-label]:not([data-group-label=""]) .fi-sidebar-group-items li::after { content: "" !important; position: absolute !important; left: -12px !important; top: 50% !important; transform: translateY(-50%) !important; width: 8px !important; height: 1.5px !important; z-index: 5 !important; }' .
                '.fi-main-sidebar.fi-sidebar-open .fi-sidebar-group[data-group-label]:not([data-group-label=""]) .fi-sidebar-group-items li.fi-active::before { content: "" !important; position: absolute !important; left: -16.5px !important; top: 50% !important; transform: translateY(-50%) !important; width: 8px !important; height: 8px !important; background-color: var(--primary-600) !important; border-radius: 50% !important; box-shadow: 0 0 5px color-mix(in srgb, var(--primary-600) 70%, transparent) !important; z-index: 10 !important; }' .
                '/* Premium Sidebar Color styling (Light Theme) */' .
                'html:not(.dark) .fi-sidebar-group-label { color: #475569 !important; font-weight: 600 !important; }' .
                'html:not(.dark) .fi-sidebar-group.fi-active .fi-sidebar-group-label { color: var(--primary-600) !important; font-weight: 700 !important; }' .
                'html:not(.dark) .fi-sidebar-group-btn svg { color: #94a3b8 !important; }' .
                'html:not(.dark) .fi-sidebar-group.fi-active .fi-sidebar-group-btn svg { color: var(--primary-600) !important; }' .
                'html:not(.dark) .fi-sidebar-item:not(.fi-active) .fi-sidebar-item-label { color: #64748b !important; }' .
                'html:not(.dark) .fi-sidebar-item:not(.fi-active) .fi-sidebar-item-icon { color: #94a3b8 !important; }' .
                'html:not(.dark) .fi-sidebar-item:not(.fi-active) .fi-sidebar-item-btn:hover { background-color: #f1f5f9 !important; }' .
                'html:not(.dark) .fi-sidebar-item:not(.fi-active) .fi-sidebar-item-btn:hover .fi-sidebar-item-label { color: #0f172a !important; }' .
                'html:not(.dark) .fi-sidebar-item:not(.fi-active) .fi-sidebar-item-btn:hover .fi-sidebar-item-icon { color: #0f172a !important; }' .
                'html:not(.dark) .fi-sidebar-item.fi-active:not(.fi-sidebar-group-items *) .fi-sidebar-item-btn { background-color: #f1f5f9 !important; }' .
                '/* Premium Sidebar Color styling (Dark Theme) */' .
                '.dark .fi-sidebar-group-label { color: #a1a1aa !important; font-weight: 600 !important; }' .
                '.dark .fi-sidebar-group.fi-active .fi-sidebar-group-label { color: var(--primary-600) !important; font-weight: 700 !important; }' .
                '.dark .fi-sidebar-group-btn svg { color: #71717a !important; }' .
                '.dark .fi-sidebar-group.fi-active .fi-sidebar-group-btn svg { color: var(--primary-600) !important; }' .
                '.dark .fi-sidebar-item:not(.fi-active) .fi-sidebar-item-label { color: #a1a1aa !important; }' .
                '.dark .fi-sidebar-item:not(.fi-active) .fi-sidebar-item-icon { color: #71717a !important; }' .
                '.dark .fi-sidebar-item:not(.fi-active) .fi-sidebar-item-btn:hover { background-color: #27272a !important; }' .
                '.dark .fi-sidebar-item:not(.fi-active) .fi-sidebar-item-btn:hover .fi-sidebar-item-label { color: #ffffff !important; }' .
                '.dark .fi-sidebar-item:not(.fi-active) .fi-sidebar-item-btn:hover .fi-sidebar-item-icon { color: #ffffff !important; }' .
                '.dark .fi-sidebar-item.fi-active:not(.fi-sidebar-group-items *) .fi-sidebar-item-btn { background-color: #27272a !important; }' .
                '/* Active highlights (Common) */' .
                '.fi-sidebar-group-items .fi-sidebar-item.fi-active .fi-sidebar-item-btn { background-color: transparent !important; }' .
                '.fi-sidebar-item.fi-active .fi-sidebar-item-label { color: var(--primary-600) !important; font-weight: 700 !important; }' .
                '.fi-sidebar-item.fi-active .fi-sidebar-item-icon { color: var(--primary-600) !important; }' .
                '</style>' .
                '<script>' .
                '(function () {' .
                '    const syncActiveSidebarGroup = (sidebar) => {' .
                '        try {' .
                '            const activeItem = document.querySelector(".fi-sidebar-item.fi-active");' .
                '            let activeGroupLabel = null;' .
                '            if (activeItem) {' .
                '                const parentGroup = activeItem.closest(".fi-sidebar-group");' .
                '                if (parentGroup) {' .
                '                    activeGroupLabel = parentGroup.getAttribute("data-group-label");' .
                '                }' .
                '            }' .
                '            document.querySelectorAll(".fi-sidebar-group.fi-collapsible").forEach(group => {' .
                '                const groupLabel = group.getAttribute("data-group-label");' .
                '                if (groupLabel) {' .
                '                    const shouldCollapse = (groupLabel !== activeGroupLabel);' .
                '                    const isCollapsed = sidebar.groupIsCollapsed(groupLabel);' .
                '                    if (shouldCollapse && !isCollapsed) {' .
                '                        sidebar.toggleCollapsedGroup(groupLabel);' .
                '                    }' .
                '                }' .
                '            });' .
                '        } catch (e) {}' .
                '    };' .
                '    const hookSidebarStore = (sidebar) => {' .
                '        if (sidebar && !sidebar._accordionHooked) {' .
                '            sidebar._accordionHooked = true;' .
                '            setTimeout(() => syncActiveSidebarGroup(sidebar), 100);' .
                '            document.addEventListener("livewire:navigated", () => syncActiveSidebarGroup(sidebar));' .
                '            document.addEventListener("livewire:update", () => syncActiveSidebarGroup(sidebar));' .
                '            const originalToggle = sidebar.toggleCollapsedGroup;' .
                '            sidebar.toggleCollapsedGroup = function (label) {' .
                '                if (this.groupIsCollapsed(label)) {' .
                '                    document.querySelectorAll(".fi-sidebar-group.fi-collapsible").forEach(group => {' .
                '                        const groupLabel = group.getAttribute("data-group-label");' .
                '                        if (groupLabel && groupLabel !== label) {' .
                '                            if (!this.groupIsCollapsed(groupLabel)) {' .
                '                                originalToggle.call(this, groupLabel);' .
                '                            }' .
                '                        }' .
                '                    });' .
                '                }' .
                '                originalToggle.call(this, label);' .
                '            };' .
                '        }' .
                '    };' .
                '    let pollCount = 0;' .
                '    const pollInterval = setInterval(() => {' .
                '        pollCount++;' .
                '        if (pollCount > 100) clearInterval(pollInterval);' .
                '        try {' .
                '            if (window.Alpine && typeof window.Alpine.store === "function") {' .
                '                const sidebar = window.Alpine.store("sidebar");' .
                '                if (sidebar) {' .
                '                    hookSidebarStore(sidebar);' .
                '                    clearInterval(pollInterval);' .
                '                }' .
                '            }' .
                '        } catch (e) {}' .
                '    }, 100);' .
                '})();' .
                '</script>'
            )
        );

        // Register Observers for Inventory Management
        \App\Models\Product::observe(\App\Observers\ProductObserver::class);
        \App\Models\ProductVariant::observe(\App\Observers\ProductVariantObserver::class);
        \App\Models\Order::observe(\App\Observers\OrderObserver::class);
        \App\Models\ReturnRequest::observe(\App\Observers\ReturnRequestObserver::class);
        \App\Models\OrderItem::observe(\App\Observers\OrderItemObserver::class);
    }
}
