<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Inertia\Middleware;
use App\Models\User;
use App\Models\Setting;
use App\Models\Message;
use App\Models\DynamicPage;
use App\Http\Middleware\CheckFeatureEnabled;

class HandleInertiaRequests extends Middleware
{
    /**
     * The root template that is loaded on the first page visit.
     *
     * @var string
     */
    protected $rootView = 'app';

    /**
     * Determine the current asset version.
     */
    public function version(Request $request): ?string
    {
        return parent::version($request);
    }

    /**
     * Define the props that are shared by default.
     *
     * @return array<string, mixed>
     */
    public function share(Request $request): array
    {
        $impersonatingFrom = $request->session()->get('impersonating_from');
        $originalAdmin = $impersonatingFrom ? User::find($impersonatingFrom) : null;
        $user = $request->user();

        // Get client profile if user is a client
        $clientProfile = null;
        if ($user && $user->role === 'client') {
            $clientProfile = $user->clientProfile;
        }

        // Get coach info for client portal
        $coach = null;
        if ($clientProfile && $clientProfile->coach) {
            $coach = [
                'id' => $clientProfile->coach->id,
                'name' => $clientProfile->coach->name,
                'avatar' => $clientProfile->coach->avatar ? '/storage/' . $clientProfile->coach->avatar : null,
            ];
        }

        // Get system branding (logo/favicon) from settings
        $logo = Setting::get('logo');
        $favicon = Setting::get('favicon');

        // Get unread messages count and notifications
        $unreadMessages = 0;
        $unreadChatMessages = 0;
        $systemNotifications = [];
        $chatNotifications = [];
        $subscription = null;

        if ($user) {
            if ($user->role === 'coach') {
                $subscription = $user->activeSubscription?->load('plan');
            }

            // Count unread messages in chat
            $unreadChatMessages = Message::where('receiver_id', $user->id)
                ->whereNull('read_at')
                ->count();

            // Separate notifications: chat messages vs system notifications
            $allNotifications = $user->unreadNotifications()->take(20)->get();

            foreach ($allNotifications as $notification) {
                $notificationData = [
                    'id' => $notification->id,
                    'type' => $notification->type,
                    'data' => $notification->data,
                    'created_at' => $notification->created_at->diffForHumans(),
                ];

                // Check if it's a chat message notification
                if (str_contains($notification->type, 'NewMessageNotification') ||
                    str_contains($notification->type, 'AdminNewSupportMessage')) {
                    $chatNotifications[] = $notificationData;
                } else {
                    // System notifications (subscriptions, payments, etc.)
                    $systemNotifications[] = $notificationData;
                }
            }

            // Legacy count for backward compatibility
            $unreadMessages = $unreadChatMessages;
        }
        // Calculate cart count from session
        $cart = $request->session()->get('cart', []);
        $cartCount = is_array($cart) ? array_sum($cart) : 0;
        
        // Build cart items array for slide-in cart
        $cartItems = [];
        foreach ($cart as $productId => $quantity) {
            $product = \App\Models\Product::find($productId);
            if ($product) {
                $cartItems[] = [
                    'product' => $product,
                    'quantity' => $quantity,
                    'subtotal' => $product->price * $quantity,
                ];
            }
        }

        // Get reCAPTCHA settings for frontend
        $recaptchaEnabled = Setting::get('recaptcha_enabled', false);
        $recaptchaSiteKey = $recaptchaEnabled ? Setting::get('recaptcha_key') : null;

        return [
            ...parent::share($request),
            'csrf_token' => csrf_token(),
            'auth' => [
                'user' => $user ? array_merge($user->toArray(), [
                    'avatar_url' => $user->avatar
                        ? (str_starts_with($user->avatar, 'http') || str_starts_with($user->avatar, '/storage/')
                            ? $user->avatar
                            : '/storage/' . $user->avatar)
                        : null,
                ]) : null,
            ],
            'client' => $clientProfile,
            'coach' => $coach,
            'appName' => Setting::get('site_name', config('app.name', 'CoachPro')),
            'appLogo' => $logo ? '/storage/' . $logo : null,
            'appFavicon' => $favicon ? '/storage/' . $favicon : null,
            'unreadMessages' => $unreadMessages, // Legacy - for backward compatibility
            'unreadChatMessages' => $unreadChatMessages, // New - chat messages count
            'systemNotifications' => $systemNotifications, // New - system notifications only
            'chatNotifications' => $chatNotifications, // New - chat notifications only
            'notifications' => $systemNotifications, // Legacy - keep for backward compatibility
            'subscription' => $subscription,
            'cartCount' => $cartCount,
            'cartItems' => $cartItems,
            'recaptcha' => [
                'enabled' => $recaptchaEnabled,
                'siteKey' => $recaptchaSiteKey,
            ],
            'features' => CheckFeatureEnabled::getAllFeatures(),
            'flash' => [
                'success' => fn () => $request->session()->get('success'),
                'error' => fn () => $request->session()->get('error'),
                'warning' => fn () => $request->session()->get('warning'),
            ],
            'impersonating' => $impersonatingFrom ? [
                'active' => true,
                'originalAdmin' => $originalAdmin ? [
                    'id' => $originalAdmin->id,
                    'name' => $originalAdmin->name,
                ] : null,
            ] : null,
            // Dynamic pages for header/footer navigation
            'headerPages' => fn () => DynamicPage::getHeaderPages(),
            'footerPages' => fn () => DynamicPage::getFooterPages(),
        ];
    }
}
