<?php

namespace App\Http\Controllers\Backend;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Http\Requests\Backend\Auth\LoginRequest;

class AuthController extends Controller
{
    public function index()
    {
        return view('auth.login');
    }

    public function login()
    // public function login(LoginRequest $request)
    {
        $request = request();
        
        $user = User::where('email', $request->email)->first();

        if (is_null($user)) {
            abort(Response::HTTP_NOT_FOUND, config('response-message.login_failed'));
        }

        if (!Hash::check($request->password, $user->password)) {
            abort(Response::HTTP_NOT_FOUND, config('response-message.login_failed'));
        }

        Auth::login($user);

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

    public function logout(Request $request)
    {
        Auth::logout();

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

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

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