<?php

namespace App\Http\Middleware;

use App\Models\Setting;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class SessionIpCheck
{
    public function handle(Request $request, Closure $next): Response
    {
        // If the check is disabled, skip
        if (Setting::get('disable_session_ip_check', false)) {
            return $next($request);
        }

        // Only check for authenticated users with active sessions
        if (!$request->hasSession() || !$request->user()) {
            return $next($request);
        }

        $session = $request->session();
        $currentIp = $request->ip();
        $sessionIp = $session->get('_session_ip');

        if ($sessionIp === null) {
            // First request after login, store the IP
            $session->put('_session_ip', $currentIp);
        } elseif ($sessionIp !== $currentIp) {
            // IP changed, invalidate session
            $guard = $request->is('admin/*') ? 'admin' : 'client';

            auth()->guard($guard)->logout();
            $session->invalidate();
            $session->regenerateToken();

            $loginRoute = $guard === 'admin' ? 'admin.login' : 'store.auth.login';

            return redirect()->route($loginRoute)
                ->with('status', __('auth.session_ip_changed'));
        }

        return $next($request);
    }
}
