<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class WhitelistIp
{
    /**
     * List of allowed IP addresses.
     *
     * @var array
     */
    protected $whitelist = [
    '178.128.104.179', // IP TokoPay
    '52.74.250.133',
    '194.233.92.170',// IP tambahan
    '45.87.242.188',
    '206.183.128.153',
    '95.111.200.230'
];


    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // Get client IP
        $clientIp = $request->ip();

        // Check if client IP is in whitelist
        if (!in_array($clientIp, $this->whitelist)) {
            // Optionally log the unauthorized access
            \Log::warning("Unauthorized IP access attempt: " . $clientIp);

            // Return a forbidden response
            return response()->json(['error' => 'Unauthorized IP'], 403);
        }

        // If IP is allowed, proceed with the request
        return $next($request);
    }
}