<?php

namespace App\Http\Middleware;

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

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 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
    {
        $user = null;
        if (auth()->check()) {
            $user = auth()->user();
        } else {
            $sess = session('user');
            $userId = is_array($sess) ? ($sess['id'] ?? null) : ($sess->id ?? null);
            if ($userId) {
                $user = \App\Models\User::find($userId);
            }
        }

        $userData = null;
        $unreadCount = 0;

        if ($user) {
            $sub = \Illuminate\Support\Facades\DB::table('subscriptions')
                ->where('user_id', $user->id)
                ->where('status', 'active')
                ->latest('id')
                ->first();

            $profile = \Illuminate\Support\Facades\DB::table('employer_profiles')
                ->where('user_id', $user->id)
                ->first();

            $unreadCount = \Illuminate\Support\Facades\DB::table('messages')
                ->join('conversations', 'messages.conversation_id', '=', 'conversations.id')
                ->where('conversations.employer_id', $user->id)
                ->where('messages.sender_type', 'worker')
                ->whereNull('messages.read_at')
                ->count();

            $userData = [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'role' => $user->role,
                'company_name' => $profile ? $profile->company_name : 'Al Mansoor Household',
                'subscription_status' => 'active',
                'subscription_expires_at' => $sub && $sub->expires_at ? date('M d', strtotime($sub->expires_at)) : 'Dec 31',
            ];
            
            // Sync with session so that controllers have access to the exact user
            session(['user' => (object) $userData]);
        }

        return [
            ...parent::share($request),
            'auth' => [
                'user' => $userData,
            ],
            'unread_messages_count' => $unreadCount,
            'flash' => [
                'status' => session('status'),
                'reason' => session('reason'),
                'success' => session('success'),
                'error' => session('error'),
                'first_login' => session('first_login'),
            ],
        ];
    }
}
