<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class BasicAuthMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $username = env('BASIC_AUTH_USERNAME');
        $password = env('BASIC_AUTH_PASSWORD');

        // If credentials are not set, deny access
        if (! $username || ! $password) {
            return response('Unauthorized', 401, ['WWW-Authenticate' => 'Basic']);
        }

        // Check if Authorization header is present
        if (! $request->header('Authorization')) {
            return response('Unauthorized', 401, ['WWW-Authenticate' => 'Basic']);
        }

        // Extract credentials from Authorization header
        $authHeader = $request->header('Authorization');
        if (! str_starts_with($authHeader, 'Basic ')) {
            return response('Unauthorized', 401, ['WWW-Authenticate' => 'Basic']);
        }

        $credentials = base64_decode(substr($authHeader, 6));
        [$inputUsername, $inputPassword] = explode(':', $credentials, 2);

        // Verify credentials
        if ($inputUsername !== $username || $inputPassword !== $password) {
            return response('Unauthorized', 401, ['WWW-Authenticate' => 'Basic']);
        }

        return $next($request);
    }
}
