<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;
use App\Models\BlockedIp;
use App\Models\SecuritySetting;

class CheckBlockedIp
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        try {
            // Check if IP Blocking is enabled
            $settings = SecuritySetting::first();
            if ($settings && $settings->enable_ip_blocking) {
                $ip = $request->ip();
                $blocked = BlockedIp::where('ip_address', $ip)->first();

                if ($blocked) {
                    abort(403, 'Your IP address has been blocked: ' . ($blocked->reason ?? 'No reason provided'));
                }
            }
        } catch (\Exception $e) {
            // If security_settings table doesn't exist or other DB error, skip IP blocking
            // This prevents the app from crashing during setup
            \Log::warning('Security check failed: ' . $e->getMessage());
        }

        return $next($request);
    }
}
