<?php

namespace App\Http\Middleware;

use App\Services\Security\SecurityEventLogger;
use Closure;
use Illuminate\Http\Request;

class VerifySameOrigin
{
    private $logger;

    public function __construct(SecurityEventLogger $logger)
    {
        $this->logger = $logger;
    }

    public function handle(Request $request, Closure $next)
    {
        if ($request->isMethodSafe() || $request->is('api/*')) {
            return $next($request);
        }

        $origin = $request->headers->get('Origin');
        $referer = $request->headers->get('Referer');

        if ($origin && ! $this->sameHost($request, $origin)) {
            return $this->deny($request, 'invalid_origin', $origin);
        }

        if (! $origin && $referer && ! $this->sameHost($request, $referer)) {
            return $this->deny($request, 'invalid_referer', $referer);
        }

        return $next($request);
    }

    private function sameHost(Request $request, string $url): bool
    {
        $incomingHost = parse_url($url, PHP_URL_HOST);
        $currentHost = $request->getHost();
        $appHost = parse_url(config('app.url'), PHP_URL_HOST);

        return $incomingHost && (
            strcasecmp($incomingHost, $currentHost) === 0 ||
            ($appHost && strcasecmp($incomingHost, $appHost) === 0)
        );
    }

    private function deny(Request $request, string $reason, string $value)
    {
        $this->logger->log('csrf_origin_check_failed', 'critical', [
            'reason' => $reason,
            'detected_value' => $value,
        ], $request);

        if ($request->expectsJson() || $request->ajax()) {
            return response()->json([
                'success' => false,
                'message' => 'The request source could not be verified.',
            ], 403);
        }

        abort(403, 'The request source could not be verified.');
    }
}
