<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Inertia\Middleware;

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
    {
        return [
            ...parent::share($request),
            'auth' => [
                'user' => $request->user(),
            ],
            'flash' => [
                'success' => fn () => $request->session()->get('success'),
                'error' => fn () => $request->session()->get('error'),
                'status' => fn () => $request->session()->get('status'),
            ],
            'cart_count' => fn () => $request->user() 
                ? \App\Models\CartItem::whereHas('cart', function($q) use ($request) {
                    $q->where('user_id', $request->user()->id);
                })->sum('qty') 
                : 0,
            'site_settings' => function () {
                try {
                    if (\Schema::hasTable('settings')) {
                        return array_merge(
                            \App\Models\Setting::all()->pluck('value', 'key')->toArray(),
                            ['app_version' => file_exists(base_path('version.json')) ? (json_decode(file_get_contents(base_path('version.json')), true)['version'] ?? 'v1.0.0') : 'v1.0.0']
                        );
                    }
                } catch (\Exception $e) {
                    // DB not ready
                }
                return ['app_version' => 'v1.0.0'];
            },
            'popular_categories' => function () {
                try {
                    if (\Schema::hasTable('categories')) {
                        return \App\Models\Category::take(5)->get(['id', 'name', 'slug'])->toArray();
                    }
                } catch (\Exception $e) {
                    // DB not ready
                }
                return [];
            },
            'promo_voucher' => function () {
                try {
                    if (\Schema::hasTable('vouchers')) {
                        return \App\Models\Voucher::where('end_date', '>', now())
                            ->where('start_date', '<=', now())
                            ->where('stock', '>', 0)
                            ->latest()
                            ->first();
                    }
                } catch (\Exception $e) {
                    // DB not ready
                }
                return null;
            },
            'unread_paid_orders_count' => function () use ($request) {
                try {
                    if ($request->user() && $request->user()->role === 'admin' && \Schema::hasTable('orders')) {
                        return \App\Models\Order::where(function($query) {
                            $query->where('status', 'paid')
                                  ->orWhere(function($q) {
                                      $q->where('status', 'waiting_payment')
                                        ->whereHas('payment', function($qp) {
                                            $qp->whereNotNull('payment_proof');
                                        });
                                  });
                        })->count();
                    }
                } catch (\Exception $e) {
                    // DB not ready
                }
                return 0;
            },
            'unread_messages_count' => function () use ($request) {
                try {
                    if ($request->user() && $request->user()->role === 'admin' && \Schema::hasTable('contact_messages')) {
                        return \App\Models\ContactMessage::where('status', 'unread')->count();
                    }
                } catch (\Exception $e) {
                    // DB not ready
                }
                return 0;
            },
            'pending_withdrawals_count' => function () use ($request) {
                try {
                    if ($request->user() && $request->user()->role === 'admin' && \Schema::hasTable('withdrawal_requests')) {
                        return \App\Models\WithdrawalRequest::where('status', 'pending')->count();
                    }
                } catch (\Exception $e) {
                    // DB not ready
                }
                return 0;
            },
        ];
    }
}
