<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
use App\Models\AdminSetting;
use App\Models\UserDomain;
use App\Services\CPanelService;

class SubscriptionCheck
{
    // Routes always accessible (even expired/suspended)
    private const ALLOWED_ROUTES = [
        'billing.expired',
        'billing.suspended',
        'billing.contact',
        'hosting.expired',
        'logout',
        'support.send',
        'support.messages',
        'support.unread',
    ];

    public function handle(Request $request, Closure $next): Response
    {
        if (!Auth::check()) return $next($request);

        $user = Auth::user();

        // Admins bypass all checks
        if ($user->isAdmin()) return $next($request);

        // Allow billing/support routes
        foreach (self::ALLOWED_ROUTES as $route) {
            if ($request->routeIs($route)) return $next($request);
        }

        $status = $user->subscriptionStatus();

        // Auto-apply domain redirects on first detection of expiry/suspension
        if (in_array($status, ['suspended', 'expired']) && !$user->redirect_applied) {
            $this->applyDomainRedirects($user);
            $user->update(['redirect_applied' => true]);
        }

        if ($status === 'suspended') {
            return redirect()->route('billing.suspended');
        }

        if ($status === 'expired') {
            return redirect()->route('billing.expired');
        }

        return $next($request);
    }

    private function applyDomainRedirects($user): void
    {
        // Use user-specific URL, then global renew_url, then panel's own expired page
        $renewUrl = $user->renew_url
            ?: AdminSetting::get('renew_url', '')
            ?: url('/hosting-expired');

        try {
            $cpanel = new CPanelService();

            $domains = UserDomain::where('user_id', $user->id)->get();
            foreach ($domains as $ud) {
                $cpanel->addDomainRedirect('domains/' . $ud->domain, $renewUrl);
            }

            if ($user->primary_domain) {
                $cpanel->addDomainRedirect('domains/' . $user->primary_domain, $renewUrl);
            }
        } catch (\Throwable) {
            // Silently fail — don't break the user's redirect to billing page
        }
    }
}
