<?php

namespace App\Http\Middleware;

use App\Services\SettingsService;
use Illuminate\Foundation\Inspiring;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Inertia\Middleware;
use Tighten\Ziggy\Ziggy;

class HandleInertiaRequests extends Middleware
{
    /**
     * The root template that's loaded on the first page visit.
     *
     * @see https://inertiajs.com/server-side-setup#root-template
     *
     * @var string
     */
    protected $rootView = 'app';

    /**
     * Determines whether the page data should be encrypted.
     *
     * @see https://inertiajs.com/history-encryption
     */
    public function encryptHistory(Request $request): bool
    {
        return true;
    }

    /**
     * Determines the current asset version.
     *
     * @see https://inertiajs.com/asset-versioning
     */
    public function version(Request $request): ?string
    {
        return parent::version($request);
    }

    /**
     * Define the props that are shared by default.
     *
     * @see https://inertiajs.com/shared-data
     *
     * @return array<string, mixed>
     */
    public function share(Request $request): array
    {
        [$message, $author] = str(Inspiring::quotes()->random())->explode('-');

        $user = $request->user();

        $settings = SettingsService::getAll();

        $appName = config('app.name', 'Perfect World');
        $appLogoPath = $settings['app_logo'] ?? null;
        $appLogoUrl = $appLogoPath ? asset($appLogoPath) : null;

        $appLogoWebP = null;
        if ($appLogoPath) {
            $pathInfo = pathinfo($appLogoPath);
            $webpPath = $pathInfo['dirname'].'/logo-'.basename($pathInfo['filename']).'.webp';
            if (file_exists(public_path($webpPath))) {
                $appLogoWebP = asset($webpPath);
            }
        }

        $loginBackgroundPath = $settings['login_background'] ?? null;
        $loginBackgroundUrl = $loginBackgroundPath ? asset($loginBackgroundPath) : null;
        $loginBackgroundPosition = $settings['login_background_position'] ?? 'right';

        // Hero background settings
        $heroBackgroundPath = $settings['hero_background'] ?? null;
        $heroBackgroundUrl = $heroBackgroundPath ? asset($heroBackgroundPath) : null;
        $heroHeight = (int) ($settings['hero_height'] ?? 40);

        $paymentSettings = Cache::remember('settings:payment', 3600, function () {
            return [
                'ipaymu' => DB::table('ipaymu_settings')->first(),
                'duitku' => DB::table('duitku_settings')->first(),
                'tripay' => DB::table('tripay_settings')->first(),
                'pakasir' => DB::table('pakasir_settings')->first(),
            ];
        });

        $socialMedia = [
            'facebook' => [
                'enabled' => ($settings['social_facebook_enabled'] ?? '0') === '1',
                'url' => $settings['social_facebook_url'] ?? '',
            ],
            'discord' => [
                'enabled' => ($settings['social_discord_enabled'] ?? '0') === '1',
                'url' => $settings['social_discord_url'] ?? '',
            ],
            'instagram' => [
                'enabled' => ($settings['social_instagram_enabled'] ?? '0') === '1',
                'url' => $settings['social_instagram_url'] ?? '',
            ],
            'tiktok' => [
                'enabled' => ($settings['social_tiktok_enabled'] ?? '0') === '1',
                'url' => $settings['social_tiktok_url'] ?? '',
            ],
            'youtube' => [
                'enabled' => ($settings['social_youtube_enabled'] ?? '0') === '1',
                'url' => $settings['social_youtube_url'] ?? '',
            ],
        ];

        $sidebarTheme = $settings['admin_sidebar_theme'] ?? 'default';
        $sidebarCustomColors = json_decode($settings['admin_sidebar_custom_colors'] ?? '{}', true);

        // Default theme colors
        $defaultSidebarColors = [
            'background' => '#ffffff',
            'foreground' => '#1f2937',
            'primary' => '#3b82f6',
            'accent' => '#e5e7eb',
            'border' => '#d1d5db',
        ];

        // Theme presets with respectsSystemTheme flag
        $themePresets = [
            'default' => [
                'colors' => $defaultSidebarColors,
                'respectsSystemTheme' => true,
            ],
            'dark' => [
                'colors' => [
                    'background' => '#1f2937',
                    'foreground' => '#f9fafb',
                    'primary' => '#60a5fa',
                    'accent' => '#4b5563',
                    'border' => '#4b5563',
                ],
                'respectsSystemTheme' => true,
            ],
            'adminlte_blue' => [
                'colors' => [
                    'background' => '#343a40',
                    'foreground' => '#c2c7d0',
                    'primary' => '#007bff',
                    'accent' => '#494e53',
                    'border' => '#4b545c',
                ],
                'respectsSystemTheme' => false,
            ],
            'adminlte_dark' => [
                'colors' => [
                    'background' => '#212529',
                    'foreground' => '#dee2e6',
                    'primary' => '#17a2b8',
                    'accent' => '#2c3035',
                    'border' => '#373b3e',
                ],
                'respectsSystemTheme' => false,
            ],
            'midnight' => [
                'colors' => [
                    'background' => '#0f172a',
                    'foreground' => '#e2e8f0',
                    'primary' => '#3b82f6',
                    'accent' => '#1e293b',
                    'border' => '#334155',
                ],
                'respectsSystemTheme' => false,
            ],
            'purple_dream' => [
                'colors' => [
                    'background' => '#2e1065',
                    'foreground' => '#faf5ff',
                    'primary' => '#a855f7',
                    'accent' => '#4c1d95',
                    'border' => '#5b21b6',
                ],
                'respectsSystemTheme' => false,
            ],
            'forest' => [
                'colors' => [
                    'background' => '#064e3b',
                    'foreground' => '#ecfdf5',
                    'primary' => '#10b981',
                    'accent' => '#065f46',
                    'border' => '#047857',
                ],
                'respectsSystemTheme' => false,
            ],
            'sunset' => [
                'colors' => [
                    'background' => '#7c2d12',
                    'foreground' => '#fff7ed',
                    'primary' => '#f97316',
                    'accent' => '#9a3412',
                    'border' => '#c2410c',
                ],
                'respectsSystemTheme' => false,
            ],
            'ocean' => [
                'colors' => [
                    'background' => '#134e4a',
                    'foreground' => '#f0fdfa',
                    'primary' => '#14b8a6',
                    'accent' => '#115e59',
                    'border' => '#0f766e',
                ],
                'respectsSystemTheme' => false,
            ],
            'rose' => [
                'colors' => [
                    'background' => '#881337',
                    'foreground' => '#fff1f2',
                    'primary' => '#f43f5e',
                    'accent' => '#9f1239',
                    'border' => '#be123c',
                ],
                'respectsSystemTheme' => false,
            ],
            'slate' => [
                'colors' => [
                    'background' => '#334155',
                    'foreground' => '#f8fafc',
                    'primary' => '#64748b',
                    'accent' => '#475569',
                    'border' => '#52647b',
                ],
                'respectsSystemTheme' => false,
            ],
            'indigo' => [
                'colors' => [
                    'background' => '#312e81',
                    'foreground' => '#eef2ff',
                    'primary' => '#6366f1',
                    'accent' => '#4338ca',
                    'border' => '#4f46e5',
                ],
                'respectsSystemTheme' => false,
            ],
        ];

        // Get current theme data
        $currentPreset = $themePresets[$sidebarTheme] ?? $themePresets['default'];
        $themeColors = $currentPreset['colors'];
        $respectsSystemTheme = $currentPreset['respectsSystemTheme'] ?? false;

        if ($sidebarTheme === 'custom' && ! empty($sidebarCustomColors)) {
            $themeColors = array_merge($defaultSidebarColors, $sidebarCustomColors);
            $respectsSystemTheme = false; // Custom themes don't respect system theme
        }

        return [
            ...parent::share($request),
            'name' => config('app.name'),
            'appName' => $appName,
            'appLogoUrl' => $appLogoUrl,
            'appLogoWebP' => $appLogoWebP,
            'loginBackgroundUrl' => $loginBackgroundUrl,
            'loginBackgroundPosition' => $loginBackgroundPosition,
            'heroBackgroundUrl' => $heroBackgroundUrl,
            'heroHeight' => $heroHeight,
            'csrfToken' => csrf_token(),  // Changed from csrf_token to csrfToken for consistency
            'quote' => ['message' => trim($message), 'author' => trim($author)],
            'auth' => [
                'user' => $user,
            ],
            'ziggy' => function () use ($request, $user) {
                // Return filtered routes based on both user role and current page scope.
                $routeName = (string) optional($request->route())->getName();
                $isAdminPage = $request->is('admin*') || str_starts_with($routeName, 'admin.');
                $shouldExposeAdminRoutes = $user && $user->role === 'admin' && $isAdminPage;

                // Get all routes using Ziggy
                // Use base URL only, not the current request URL
                $baseUrl = rtrim(config('app.url'), '/');
                $ziggy = new Ziggy($shouldExposeAdminRoutes ? null : 'frontend', $baseUrl);
                $routes = $ziggy->toArray()['routes'] ?? [];

                // If not admin, filter out admin routes
                if (! $shouldExposeAdminRoutes) {
                    $routes = array_filter($routes, function ($key) {
                        return ! str_starts_with($key, 'admin.');
                    }, ARRAY_FILTER_USE_KEY);
                }

                return [
                    'url' => config('app.url'),
                    'port' => null,
                    'defaults' => [],
                    'routes' => $routes,
                    'location' => $request->url(),
                ];
            },
            'sidebarOpen' => ! $request->hasCookie('sidebar_state') || $request->cookie('sidebar_state') === 'true',
            'flash' => [
                'success' => $request->session()->get('success'),
                'error' => $request->session()->get('error'),
                'info' => $request->session()->get('info'),
                'warning' => $request->session()->get('warning'),
            ],
            'services' => [
                'ipaymu_active' => $paymentSettings['ipaymu'] ? (bool) $paymentSettings['ipaymu']->is_active : false,
                'duitku_active' => $paymentSettings['duitku'] ? (bool) $paymentSettings['duitku']->is_active : false,
                'tripay_active' => $paymentSettings['tripay'] ? (bool) $paymentSettings['tripay']->is_active : false,
                'pakasir_active' => $paymentSettings['pakasir'] ? (bool) $paymentSettings['pakasir']->is_active : false,
                'menu_voucher_enabled' => ($settings['menu_voucher_enabled'] ?? null) === '1' || ($settings['menu_voucher_enabled'] ?? null) === null,
                'menu_shop_enabled' => ($settings['menu_shop_enabled'] ?? null) === '1' || ($settings['menu_shop_enabled'] ?? null) === null,
                'menu_topspender_enabled' => ($settings['menu_topspender_enabled'] ?? null) === '1' || ($settings['menu_topspender_enabled'] ?? null) === null,
                'menu_ingame_enabled' => ($settings['menu_ingame_enabled'] ?? null) === '1' || ($settings['menu_ingame_enabled'] ?? null) === null,
                'menu_streamer_enabled' => ($settings['menu_streamer_enabled'] ?? null) === '1' || ($settings['menu_streamer_enabled'] ?? null) === null,
                'menu_event_enabled' => ($settings['menu_event_enabled'] ?? null) === '1' || ($settings['menu_event_enabled'] ?? null) === null,
                'menu_topup_enabled' => ($settings['menu_topup_enabled'] ?? null) === '1' || ($settings['menu_topup_enabled'] ?? null) === null,
                'enable_pickup_logs' => ($settings['enable_pickup_logs'] ?? null) === '1' || ($settings['enable_pickup_logs'] ?? null) === 'true' || ($settings['enable_pickup_logs'] ?? null) === null,
                'enable_trade_logs' => ($settings['enable_trade_logs'] ?? null) === '1' || ($settings['enable_trade_logs'] ?? null) === 'true' || ($settings['enable_trade_logs'] ?? null) === null,
            ],
            'turnstile' => [
                'enabled' => ($settings['turnstile_enabled'] ?? '0') === '1',
                'siteKey' => $settings['turnstile_site_key'] ?? '',
            ],
            'appLogoPath' => $appLogoPath,
            'appLogoPath' => $appLogoPath,
            'appFont' => $settings['app_font'] ?? 'The Golden Blade.woff2',
            'appNameColor' => $settings['app_name_color'] ?? '#fbbf24',
            'heroUseLogo' => ($settings['hero_use_logo'] ?? '0') === '1',
            'socialMedia' => $socialMedia,
            'sidebarTheme' => [
                'theme' => $sidebarTheme,
                'colors' => $themeColors,
                'respectsSystemTheme' => $respectsSystemTheme,
            ],
            'shutdownTimer' => function () use ($request) {
                $timer = $request->session()->get('shutdown_timer');
                if (! $timer) {
                    return null;
                }

                $now = time();
                $remaining = $timer['end_time'] - $now;

                if ($remaining <= 0) {
                    // Timer expired, clear it
                    $request->session()->forget('shutdown_timer');

                    return null;
                }

                return [
                    'startTime' => $timer['start_time'],
                    'endTime' => $timer['end_time'],
                    'duration' => $timer['duration'],
                    'remaining' => $remaining,
                ];
            },
        ];
    }
}
