<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class BasicAuthMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        $username = env('API_USER');
        $password = env('API_PASS');

        $authHeader = $request->header('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Basic ')) {
            return response()->json(['error' => 'No autorizado'], 401);
        }

        $base64 = substr($authHeader, 6);
        $decoded = base64_decode($base64);

        if (!$decoded || !str_contains($decoded, ':')) {
            return response()->json(['error' => 'Credenciales inválidas'], 401);
        }

        [$user, $pass] = explode(':', $decoded, 2);

        if ($user !== $username || $pass !== $password) {
            return response()->json(['error' => 'Credenciales incorrectas'], 401);
        }

        return $next($request);
    }
}