<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AdminLoginController extends Controller
{
    public function showLoginForm()
    {
        return view('auth.admin-login');
    }

    public function login(Request $request)
    {
        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required|min:6'
        ]);

        if (auth()->guard()->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))) {
            // Check if the user has the 'user' role
            $user = Auth::user();
            if ($user && !$user->hasRole('admin')) {
                // Log the user out if they don't have the 'user' role
                Auth::logout();
                return redirect()->route('login')->withErrors(['email' => 'You do not have permission to access this site.']);
            }
            return redirect()->intended(route('admin.dashboard'));
        }

        return back()->withInput($request->only('email', 'remember'));
    }
}
