<?php

namespace App\Http\Middleware;

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

class EnsurePrinciplesAccepted
{
    /**
     * Routes that should be excluded from principles acceptance check.
     *
     * @var array
     */
    protected $excludedRoutes = [
        'static-principles',
        'logout',
        'verification.*',
        'login',
        'register',
        'password.*',
        'two-factor.*',
    ];

    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Only check for authenticated users on the web guard
        $user = Auth::guard('web')->user();

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

        // Check if the current route is excluded
        foreach ($this->excludedRoutes as $excludedRoute) {
            if ($request->routeIs($excludedRoute)) {
                return $next($request);
            }
        }

        // Check if user needs to accept or re-accept principles
        if ($user->needsToReacceptPrinciples()) {
            // Redirect to principles page with appropriate message
            $principlesUrl = LaravelLocalization::localizeUrl(route('static-principles'));

            $message = $user->hasAcceptedPrinciples()
                ? __('Our principles have been updated. Please review and accept the new version to continue.')
                : __('Please accept the platform principles to continue.');

            return redirect()->to($principlesUrl)
                ->with('warning', $message);
        }

        return $next($request);
    }
}
