<?php

namespace App\Http\Middleware;

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

class CheckReferer
{
    public function handle(Request $request, Closure $next): Response
    {
        if ($request->isMethod('GET')) {
            return $next($request);
        }

        $referer = $request->header('Referer');
        $host = $request->getHost();

        if (empty($referer)) {
            abort(403, 'دسترسی بدون Referer مجاز نیست.');
        }

        if (! $this->isValidReferer($referer, $host)) {
            abort(403, 'دسترسی با این Referer مجاز نیست.');
        }

        return $next($request);
    }

    protected function isValidReferer(?string $referer, string $host): bool
    {
        if (empty($referer)) {
            return false;
        }

        $refererHost = parse_url($referer, PHP_URL_HOST);

        if (empty($refererHost)) {
            return false;
        }

        // Allow requests from the same host
        if ($refererHost === $host) {
            return true;
        }

        // Allow requests from trusted domains
        $trustedDomains = config('app.trusted_domains', []);
        if (in_array($refererHost, $trustedDomains)) {
            return true;
        }

        return false;
    }
}
