<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use RealRashid\SweetAlert\Facades\Alert;

class AuthController extends Controller
{
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }
    public function index()
    {
        if (Auth::check()) {
            return redirect()->route('dashboard');
        } else {
            return view('auth.login');
        }
    }

    public function login(Request $req)
    {
        $credentials = $req->validate([
            'email' => 'required|email',
            'password' => 'required'
        ], [
            '*.required' => 'Tidak Boleh Kosong',
            '*.email' => 'Email Tidak Valid',
        ]);

        if (Auth::attempt($credentials, $req->remember)) {
            if (Auth::user()->is_active == 1) {
                return redirect()->route('dashboard');
            } else {
                Auth::logout();
                $req->session()->invalidate();
                $req->session()->regenerateToken();
                return redirect()->route('login')->withInput()->withErrors([
                    'email' => 'Akun Tidak Aktif'
                ]);
            }
        }

        return back()->withInput()->withErrors([
            'email' => 'Email dan Password Tidak Cocok',
        ])->onlyInput('email');
    }

    public function logout(Request $req)
    {
        Auth::logout();
        $req->session()->invalidate();
        $req->session()->regenerateToken();
        return redirect('/');
    }

}
