<?php

namespace App\Http\Middleware;

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

class ValidateReferer
{
    /**
     * Handle an incoming request.
     *
     * This middleware validates the referer header to ensure that the request is coming
     * from a trusted source. It compares the referer against a list of valid referers,
     * which includes the application URL.
     *
     * @param  Request  $request  The incoming HTTP request.
     * @param  \Closure  $next  The next middleware or request handler.
     *
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response The HTTP response. Returns a JSON response with an error message
     *                                                                 if the referer is invalid, or the next middleware's response otherwise.
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Retrieve valid referers from the security config file.
        $validReferers = [parse_url(config('app.url'), PHP_URL_HOST)];

        $referer = $request->header('referer');

        if ($referer && !in_array(parse_url($referer, PHP_URL_HOST), $validReferers)) {
            return response()->json(['error' => 'The referer of the request is invalid. You do not have permission to access this page.'], 403);
        }

        // Validate the Host header.
        $host = $request->header('host');

        if ($host && !in_array($host, $validReferers, true)) {
            return response()->json([
                'error' => 'The host of the request is invalid. You do not have permission to access this page.',
            ], 403);
        }

        return $next($request);
    }
}
