<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    /**
     * Handle user login.
     */
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'user_email' => [
                'required',
                'email',
            ],
            'password' => [
                'required',
            ],
        ]);


        if (Auth::attempt([
            'user_email' => $credentials['user_email'],
            'password' => $credentials['password'],
            'is_active' => 1,
        ])) {

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

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


        return back()
            ->withErrors([
                'user_email' => 'Invalid email or password.',
            ])
            ->onlyInput('user_email');
    }


    /**
     * Handle user logout.
     */
    public function logout(Request $request)
    {
        Auth::logout();


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

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


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