<?php

namespace App\Http\Middleware;

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

/**
 * Gate for the public marketing frontend.
 *
 * When the admin flips "Disable public frontend" on (settings → Frontend tab),
 * the homepage and the legal/marketing pages stop being publicly reachable —
 * anyone hitting them gets bounced straight to /login. Self-hosted operators
 * who use MailTrixy as a private internal tool (no public SaaS landing page)
 * use this to skip the marketing site entirely.
 *
 * Authenticated users keep working normally — they go to /dashboard or
 * /admin/dashboard depending on role.
 */
class EnsureFrontendEnabled
{
    public function handle(Request $request, Closure $next): Response
    {
        // SystemSetting stores booleans as the literal strings 'true'/'false'
        // (see SettingsController::update). PHP truthiness on those strings
        // is BOTH true — `!"false"` is false — so a naive `if (! get(...))`
        // check would never block. filter_var with VALIDATE_BOOLEAN handles
        // 'true', 'false', '1', '0', true, false uniformly.
        if (! filter_var(SystemSetting::get('frontend_disabled', false), FILTER_VALIDATE_BOOLEAN)) {
            return $next($request);
        }

        // Already signed in → route to the appropriate authenticated home
        // instead of bouncing to a login page they don't need.
        if ($request->user()) {
            return $request->user()->is_admin
                ? redirect()->route('admin.dashboard')
                : redirect('/dashboard');
        }

        return redirect()->route('login');
    }
}
