<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

/**
 * Safety net: if an authenticated user still has force_password_change = true (e.g. old session),
 * log them out and send to login. Primary flow is handled at login (redirect to first-login set-password).
 */
class ForcePasswordChange
{
    public function handle(Request $request, Closure $next)
    {
        $user = $request->user();

        if (!$user) {
            return $next($request);
        }

        if (!$user->force_password_change) {
            return $next($request);
        }

        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('login')->withErrors(['email' => 'Please set your password first. Log in again to receive a new link.']);
    }
}

