<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Models\User;

class AdminBasicAuth
{
    public function handle(Request $request, Closure $next): Response
    {
        $userInput = (string) $request->getUser();
        $passInput = (string) $request->getPassword();

        /** @var User|null $admin */
        $admin = User::where('email', $userInput)->where('is_admin', true)->first();

        if (!$admin || !Hash::check($passInput, $admin->password)) {
            return response('Unauthorized', 401, ['WWW-Authenticate' => 'Basic']);
        }

        auth()->login($admin);

        return $next($request);
    }
}

