<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class Laraminimate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    // In Laraminimate.php middleware
public function handle(Request $request, Closure $next)
{
    $excludedRoutes = [
        'unauthorized', // The route name or path for the unauthorized page
        'validate-purchase', // The route name or path for validating the purchase code
    ];

    if (in_array($request->path(), $excludedRoutes)) {
        return $next($request); // Skip domain validation for these routes
    }

    $host = $request->getHost();
    $allowedDomains = [];

    try {
        // Fetch allowed domains from an external API
        $response = Http::get('https://teeflow14.github.io/tundeblog-license-api/allowed-domains.json');

        if ($response->successful()) {
            $allowedDomains = $response->json();

            if (!is_array($allowedDomains)) {
                \Log::error('Invalid allowed domains format.');
                return to_route('unauthorized');
            }
        } else {
            \Log::error('Failed to fetch allowed domains.');
            return to_route('unauthorized');
        }
    } catch (\Exception $e) {
        \Log::error('Error fetching allowed domains: ' . $e->getMessage());
        return to_route('unauthorized');
    }

    // Check if the current domain is in the allowed list
    if (!in_array($host, $allowedDomains)) {
        return redirect()->route('unauthorized'); // Redirect to the purchase page
    }

    return $next($request);
}

}
