<?php

namespace App\Http\Middleware;

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

class ForceHttps
{
    public function handle(Request $request, Closure $next): Response
    {
        if ($this->shouldForce() && ! $request->secure()) {
            return redirect()->secure($request->getRequestUri(), 301);
        }

        return $next($request);
    }

    protected function shouldForce(): bool
    {
        if (! filter_var(env('FORCE_HTTPS', false), FILTER_VALIDATE_BOOLEAN)) {
            return false;
        }

        URL::forceScheme('https');

        return true;
    }
}
