<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
class FirewallMiddleware
{

public function handle(Request $request, Closure $next)
{
    $ip = $request->ip();
    $ua = $request->userAgent() ?? 'Unknown';
    $path = $request->path();
    $url = $request->fullUrl();
    
    if (Cache::has("blocked_ip_{$ip}")) {
        abort(403, 'Access Denied: Your IP has been temporarily blocked.');
    }

    $blockedPaths = [
        '.env', 'server-status', 'wp-login.php', 'vendor/phpunit',
        'phpinfo.php', 'config.php', 'setup.php', 'admin.php',
        'shell.php', 'cmd.php', 'xmlrpc.php', '.git', '.svn',
        'backup.zip', 'dump.sql', 'debug', 'h2-console',
    ];

    foreach ($blockedPaths as $pattern) {
        if (stripos($path, $pattern) !== false) {
            $this->logBlock($ip, $ua, "Blocked path: $pattern", $path);
            Cache::put("blocked_ip_{$ip}", true, now()->addHours(24));
            abort(403, 'Access Denied: Suspicious activity detected.');
        }
    }

    $blockedAgents = [
        'sqlmap', 'acunetix', 'nmap', 'masscan', 'dirbuster',
        'wpscan', 'fuzzer', 'netsparker', 'havij', 'nikto',
        'arachni', 'rat', 'malware', 'zaproxy', 'xss',
        'powershell', 'hacktool', 'injection',
    ];

    $allowedAgents = [
        'TelegramBot',
        'TwitterBot',
        'Slackbot',
        'Discordbot',
    ];

    foreach ($allowedAgents as $allowed) {
        if (stripos($ua, strtolower($allowed)) !== false) {
            return $next($request); // skip further checks
        }
    }

    foreach ($blockedAgents as $agent) {
        if (stripos($ua, $agent) !== false) {
            $this->logBlock($ip, $ua, "Blocked user-agent: $agent", $path);
            Cache::put("blocked_ip_{$ip}", true, now()->addHours(24));
            abort(403, 'Access Denied: Suspicious activity detected.');
        }
    }

    return $next($request);
}

    protected function logBlock($ip, $ua, $reason, $path)
    {
        $exists = DB::table('firewall_logs')
    ->where('ip', $ip)
    ->where('created_at', '>=', now()->subHours(24))
    ->exists();

        if (!$exists) {
             $location = @json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));
             $country = $location->country ?? null;
            DB::table('firewall_logs')->insert([
                'ip' => $ip,
                'user_agent' => $ua,
                'reason' => $reason,
                'path' => $path,
                'server_ip' => gethostbyname(gethostname()),
                'country' => $country,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
            
        }
    }

}

