<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Auth;

class ForcePasswordChange
{
    /**
     * Handle an incoming request.
     * Redirect user to force password change page if must_change_password is true.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Skip jika user belum login
        if (!Auth::check()) {
            return $next($request);
        }

        $user = Auth::user();

        // Skip jika route adalah:
        // - force-password-change (halaman ganti password)
        // - logout (agar user bisa logout)
        // - password reset routes (untuk self-service password reset)
        if ($request->routeIs('password.force-change*') || 
            $request->routeIs('logout') ||
            $request->routeIs('password.request') ||
            $request->routeIs('password.email') ||
            $request->routeIs('password.reset') ||
            $request->routeIs('password.store')) {
            return $next($request);
        }

        // Redirect jika user wajib ganti password
        if ($user->must_change_password) {
            return redirect()->route('password.force-change')
                ->with('warning', 'Anda wajib mengganti password sebelum melanjutkan. Password Anda telah direset oleh administrator.');
        }

        return $next($request);
    }
}
