<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function showLogin()
    {
        if (session('admin_logged_in')) {
            return redirect()->route('admin.dashboard');
        }

        return view('admin.login');
    }

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

        $user = User::where('email', $request->email)->where('is_admin', true)->first();

        if ($user && Hash::check($request->password, $user->password)) {
            session([
                'admin_logged_in' => true,
                'admin_name'      => $user->name,
                'admin_email'     => $user->email,
                'admin_id'        => $user->id,
            ]);

            return redirect()->route('admin.dashboard')->with('success', 'Bienvenue, ' . $user->name . ' !');
        }

        return back()->withErrors(['email' => 'Identifiants incorrects.'])->withInput();
    }

    public function logout(Request $request)
    {
        session()->forget(['admin_logged_in', 'admin_name', 'admin_email', 'admin_id']);

        return redirect()->route('admin.login')->with('success', 'Vous avez été déconnecté.');
    }
}
