<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class BlockBadUserAgentsAndGetIP
{
    protected $blockedAgents = [
        "curl", "python-requests", "python", "Wget", "http-client", 
        "PostmanRuntime", "BurpSuite", "OWASP-ZAP"
    ];

    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next)
    {
        $userAgent = $request->header('User-Agent', '');

        foreach ($this->blockedAgents as $agent) {
            if (stripos($userAgent, $agent) !== false) {
                return response()->json(['error' => 'Forbidden.'], 403);
            }
        }

        // Get public IP address (ignore private/reserved IPs)
        $ip = $this->getPublicIP($request);

        // You can save IP in request attribute if you want to use it later
        $request->attributes->set('client_ip', $ip);

        return $next($request);
    }

    private function getPublicIP(Request $request)
    {
        $ipKeys = [
            'HTTP_CLIENT_IP',
            'HTTP_X_FORWARDED_FOR',
            'HTTP_X_FORWARDED',
            'HTTP_X_CLUSTER_CLIENT_IP',
            'HTTP_FORWARDED_FOR',
            'HTTP_FORWARDED',
            'REMOTE_ADDR'
        ];

        foreach ($ipKeys as $key) {
            if ($request->server($key)) {
                $ips = explode(',', $request->server($key));
                foreach ($ips as $ip) {
                    $ip = trim($ip);
                    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                        return $ip;
                    }
                }
            }
        }
        return $request->ip(); // fallback to Laravel's ip() method
    }
}
