<?php
class AuthMiddleware
{
    /**
     * BUG 5 FIX: Enforce must_change_password globally.
     * If the user is flagged, they cannot access ANY page except
     * /change-password and /logout. No module route bypasses this.
     */
    public function handle(Request $request): void
    {
        if (!Auth::check()) {
            if ($request->isAjax()) {
                Response::json(['success' => false, 'message' => 'Unauthorized'], 401);
            }
            Session::flash('redirect_after_login', $request->uri());
            Response::redirect('/login');
        }

        // Check must_change_password
        $sessionUser = Session::get('auth_user');
        if ($sessionUser && !empty($sessionUser['must_change_password'])) {
            $uri = $request->uri();
            // Allow only change-password and logout
            $allowed = ['/change-password', '/logout', '/lang/en', '/lang/ar'];
            $isAllowed = false;
            foreach ($allowed as $path) {
                if ($uri === $path || str_starts_with($uri, $path)) {
                    $isAllowed = true;
                    break;
                }
            }
            if (!$isAllowed) {
                Session::flash('warning', 'You must change your password before continuing.');
                Response::redirect('/change-password');
            }
        }
    }
}