<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Alert;


use Illuminate\Http\Request;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;
    /*protected function redirectTo()
    {
        if (Auth()->user()->roles == 'admin') {
            return route('admin.home');
        } else if (Auth()->user()->roles == 'teacher'){
            return route('teacher.home');
        }else{
            return route('student.home');
        }
    }*/
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function login(Request $request){
        $input = $request->all();
        $this->validate($request,[
            'email' => 'required|email|exists:users,email',
            'password' => 'required|min:8',
        ]);

        if(auth()->attempt(array('email'=>$input['email'], 'password'=>$input['password']))){
            if(auth()->user()->roles == 'admin'){
                Alert::success('Login Successfully!', 'Welcome to Admin Page!');
                return redirect()->route('admin.home');
            }else if(auth()->user()->roles == 'teacher'){
                Alert::success('Login Successfully!', 'Welcome to Teacher Page!'); 
                return redirect()->route('teacher.home');
            }else{
                Alert::success('Login Successfully!', 'Welcome to Student Page!');
                return redirect()->route('student.home');
            }
        }else{
            Alert::error('Oops! Login Failure.', 'Something went wrong!');
            return redirect()->back();
        }
    }
}