<?php

namespace App\Http\Controllers\Web\Bo;

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

class AuthController extends Controller
{
    public function showLogin(): View
    {
        return view('bo.auth.login');
    }

    public function login(Request $request): RedirectResponse
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required', 'string'],
        ]);

        if (!Auth::attempt($credentials, $request->boolean('remember'))) {
            return back()->withErrors([
                'email' => 'Identifiants invalides.',
            ])->withInput($request->only('email'));
        }

        $request->session()->regenerate();

        if (!Auth::user()?->isAdmin()) {
            Auth::logout();

            return back()->withErrors([
                'email' => 'Acces reserve aux administrateurs.',
            ]);
        }

        return redirect()->intended(route('bo.dashboard'));
    }

    public function logout(Request $request): RedirectResponse
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('bo.login');
    }
}
