<?php

/*
|--------------------------------------------------------------------------
| OwnStore - Build your own online store
| Author: TakfeDev (MKJUEL)
| All Rights Reserved
|--------------------------------------------------------------------------
*/

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Inertia\Middleware;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;
use App\Models\Setting;
use App\Models\Language;
use App\Models\PageGroup;
use App\Models\CustomPage;
use App\Models\Currency;
use App\Models\Category;

class HandleInertiaRequests extends Middleware
{
    protected $rootView = 'app';

    public function version(Request $request): ?string
    {
        $manifestPath = public_path('build/manifest.json');
        
        if (file_exists($manifestPath)) {
            return md5_file($manifestPath);
        }

        return parent::version($request);
    }

    public function share(Request $request): array
    {
        $dbSettings = Cache::rememberForever('app_settings', function () {
            if (Schema::hasTable('settings')) {
                return Setting::pluck('value', 'key')->toArray();
            }
            return [];
        });

        $footerData = Cache::rememberForever('footer_data', function () {
            if (Schema::hasTable('page_groups') && Schema::hasTable('custom_pages')) {
                return [
                    'groups' => PageGroup::with(['pages' => function($q) {
                        $q->where('is_active', true)->orderBy('sort_order');
                    }])->where('is_active', true)->orderBy('sort_order')->get()->toArray(),
                    'bottomLinks' => CustomPage::where('is_bottom_link', true)
                        ->where('is_active', true)
                        ->orderBy('sort_order')
                        ->get(['id', 'title', 'slug'])->toArray()
                ];
            }
            return ['groups' => [], 'bottomLinks' => []];
        });

        $globalCategories = Cache::remember('global_categories', 3600, function () {
            if (Schema::hasTable('categories')) {
                return Category::with(['subcategories' => function($q) {
                    $q->where('is_active', true)->orderBy('name');
                }])
                ->whereNull('parent_id')
                ->where('is_active', true)
                ->orderBy('name')
                ->get()->toArray();
            }
            return [];
        });

        $availableLanguages = Cache::rememberForever('active_languages', function () {
            if (Schema::hasTable('languages')) {
                return Language::orderBy('name')->get(['code', 'name', 'is_rtl', 'is_default'])->toArray();
            }
            return [];
        });

        $locale = session('locale');
        $isRtl = session('is_rtl', false);
        
        if (!$locale && Schema::hasTable('languages')) {
            $defaultLang = Language::where('is_default', true)->first();
            if ($defaultLang) {
                $locale = $defaultLang->code;
                $isRtl = $defaultLang->is_rtl;
                session(['locale' => $locale, 'is_rtl' => $isRtl]);
                session()->save();
            } else {
                $locale = 'en';
                $isRtl = false;
            }
        } elseif (!$locale) {
            $locale = 'en';
            $isRtl = false;
        }

        app()->setLocale($locale);

        $translations = [];
        $langPath = base_path("lang/{$locale}.json");
        if (file_exists($langPath)) {
            $decoded = json_decode(file_get_contents($langPath), true);
            if (is_array($decoded)) {
                $translations = $decoded;
            }
        }

        $currencies = Cache::rememberForever('active_currencies', function () {
            if (Schema::hasTable('currencies')) {
                return Currency::where('is_active', true)->get(['code', 'symbol', 'exchange_rate'])->toArray();
            }
            return [];
        });

        $activeCurrencyCode = session('currency');
        if (!$activeCurrencyCode && !empty($currencies)) {
            $default = collect($currencies)->firstWhere('is_default', true) ?? $currencies[0];
            $activeCurrencyCode = $default['code'];
            session(['currency' => $activeCurrencyCode]);
        }

        $activeCurrency = collect($currencies)->firstWhere('code', $activeCurrencyCode) ?? null;

        return [
            ...parent::share($request),
            'auth' => [
                'user' => $request->user(),
            ],

            'cartCount' => function () use ($request) {
                if ($request->user() && Schema::hasTable('carts')) {
                    return \App\Models\Cart::where('user_id', $request->user()->id)->count();
                }
                return 0;
            },

            // --- Global Unread Messages Count ---
            'unreadMessagesCount' => function () use ($request) {
                if ($request->user() && Schema::hasTable('messages') && Schema::hasTable('conversations')) {
                    return \App\Models\Message::whereHas('conversation', function ($q) use ($request) {
                        $q->where('buyer_id', $request->user()->id)
                          ->orWhere('seller_id', $request->user()->id);
                    })
                    ->where('sender_id', '!=', $request->user()->id)
                    ->whereNull('read_at')
                    ->count();
                }
                return 0;
            },

             'unreadNotificationsCount' => function () use ($request) {
                if ($request->user() && \Illuminate\Support\Facades\Schema::hasTable('notifications')) {
                    return $request->user()->unreadNotifications()->count();
                }
                return 0;
            },
            
            'locale' => $locale,
            'isRtl' => $isRtl,
            'translations' => $translations,
            'availableLanguages' => $availableLanguages,
            'activeCurrency' => $activeCurrency,
            'currencies' => $currencies,
            'footerData' => $footerData,
            'globalCategories' => $globalCategories,
            
            'appSettings' => [
                'name' => config('app.name', 'Laravel'),
                'lightLogo' => Storage::disk('public')->exists('settings/light_logo.png') 
                    ? asset('storage/settings/light_logo.png') . '?v=' . time() : null,
                'darkLogo' => Storage::disk('public')->exists('settings/dark_logo.png') 
                    ? asset('storage/settings/dark_logo.png') . '?v=' . time() : null,
                'favicon' => Storage::disk('public')->exists('settings/favicon.png') 
                    ? asset('storage/settings/favicon.png') . '?v=' . time() : null,
                'ogImage' => Storage::disk('public')->exists('settings/og_image.png') 
                    ? asset('storage/settings/og_image.png') . '?v=' . time() : null,
                'protection_badge_name' => $dbSettings['protection_badge_name'] ?? 'Buyer Protection',
                'protection_slogan' => $dbSettings['protection_slogan'] ?? 'Protects your orders from payment to delivery.',
                'enable_refund_system' => filter_var($dbSettings['enable_refund_system'] ?? true, FILTER_VALIDATE_BOOLEAN),
                'about_us_text' => $dbSettings['about_us_text'] ?? 'OwnStore is a powerful B2B/B2C marketplace built by TakfeDev. We make it easy for every store owner to manage their business globally with seamless tools and secure transactions.',
                'contact_us_text' => $dbSettings['contact_us_text'] ?? "Email: support@example.com\nPhone: +1 234 567 890",
                'enable_footer_payment_image' => filter_var($dbSettings['enable_footer_payment_image'] ?? true, FILTER_VALIDATE_BOOLEAN),
                'footer_payment_image' => Storage::disk('public')->exists('settings/footer_payment.png') 
                    ? asset('storage/settings/footer_payment.png') . '?v=' . time() : null,
                'ai_chat_assistant' => filter_var($dbSettings['ai_chat_assistant'] ?? true, FILTER_VALIDATE_BOOLEAN),
                'ai_product_assistant' => filter_var($dbSettings['ai_product_assistant'] ?? true, FILTER_VALIDATE_BOOLEAN),
                'appearance' => [
                    'light' => [
                        'primary' => ($dbSettings['appearance_light_primary_h'] ?? '222.2') . ' ' . ($dbSettings['appearance_light_primary_s'] ?? '47.4%') . ' ' . ($dbSettings['appearance_light_primary_l'] ?? '11.2%'),
                        'primary_fg' => ($dbSettings['appearance_light_primary_fg_h'] ?? '210') . ' ' . ($dbSettings['appearance_light_primary_fg_s'] ?? '40%') . ' ' . ($dbSettings['appearance_light_primary_fg_l'] ?? '98%'),
                    ],
                    'dark' => [
                        'primary' => ($dbSettings['appearance_dark_primary_h'] ?? '210') . ' ' . ($dbSettings['appearance_dark_primary_s'] ?? '40%') . ' ' . ($dbSettings['appearance_dark_primary_l'] ?? '98%'),
                        'primary_fg' => ($dbSettings['appearance_dark_primary_fg_h'] ?? '222.2') . ' ' . ($dbSettings['appearance_dark_primary_fg_s'] ?? '47.4%') . ' ' . ($dbSettings['appearance_dark_primary_fg_l'] ?? '11.2%'),
                    ],
                    'radius' => $dbSettings['appearance_radius'] ?? '0.5rem',
                ]
            ],
        ];
    }
}