<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class TenantMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Import Auth facade
        $auth = \Illuminate\Support\Facades\Auth::class;

        // Resolve tenant by subdomain or domain
        $host = $request->getHost();
        $tenant = null;

        // Example: if using subdomain as tenant identifier
        $parts = explode('.', $host);
        if (count($parts) > 2) {
            $subdomain = $parts[0];
            $tenant = \App\Models\Tenant::where('subdomain', $subdomain)->first();
        } else {
            // Or use domain
            $tenant = \App\Models\Tenant::where('domain', $host)->first();
        }

        // Fallback to authenticated user's tenant if not found by host
        if (!$tenant && $auth::check()) {
            $tenant = $auth::user()->tenant;
        }

        if (!$tenant) {
            abort(404, 'Tenant not found');
        }

        // Check if tenant has active subscription
        $isSubscriptionRoute = $request->route() && in_array($request->route()->getName(), ['subscriptions.create', 'subscriptions.store']);
        
        // Check if user is super admin (bypass subscription checks)
        $isSuperAdmin = false;
        if ($auth::check()) {
            $user = $auth::user();
            $isSuperAdmin = $user->hasRole('Super Admin') || $user->hasRole('super-admin');
        }

        $hasActiveSubscription = \App\Models\Subscription::where('tenant_id', $tenant->id)
            ->where('status', 'active')
            ->where(function ($query) {
                $query->whereNull('end_date')
                      ->orWhere('end_date', '>=', now());
            })
            ->exists();

        // Only check subscription if not super admin and not on subscription route
        if (!$hasActiveSubscription && !$isSubscriptionRoute && !$isSuperAdmin) {
            if ($auth::check()) {
                return redirect()->route('subscriptions.create')->with('warning', 'Please subscribe to a plan to access the dashboard.');
            } else {
                return redirect()->route('login');
            }
        }

        // Share tenant instance globally
        app()->instance('tenant', $tenant);
        $request->attributes->set('tenant', $tenant);
        session(['tenant_id' => $tenant->id]);

        // Optionally set tenant for authenticated user
        if ($auth::check()) {
            $user = $auth::user();
            if ($user->tenant_id !== $tenant->id) {
                $auth::logout();
                return redirect()->route('login')->withErrors('Unauthorized tenant access.');
            }

            // Check for active subscription (skip for super admin)
            $isSuperAdmin = $user->hasRole('Super Admin') || $user->hasRole('super-admin');
            $activeSubscription = $tenant->subscriptions()->where('status', 'active')->first();
            if (!$activeSubscription && !$isSuperAdmin && !in_array($request->route()->getName(), ['subscriptions.create', 'subscriptions.store'])) {
                return redirect()->route('subscriptions.create')->withErrors('Please subscribe to a plan to access the application.');
            }
        }

        return $next($request);
    }
}
