<?php

namespace App\Http\Controllers\Auth;

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

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;
    public $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }


    public function showLoginForm()
    {
        return view('auth.login');
    }



    public function login(Request $request)
    {
        $student = User::where(
            'user_type',1
        )->where(
            'email',$request->email
        )->where(
            'sign_up',1 
        )->first();

        if(!$student){
            return redirect('/login')->with('error','Unknown Email address!');
        }else{
            if($student->email_verification == 0){
                return redirect('/login')->with('error', 'Account is not verified!. Please check your email.');
            }else{
                $credentials = [
                    'email' => $request->email,
                    'password' => $request->password,
                    'status' => '1',
                    'email_verification'=>'1',
                    'sign_up'=>'1',
                ];

                if (Auth::attempt($credentials)) {

                    $student->last_logged_timezone=$request->last_logged_timezone;
                    $student->last_logged_at=now();
                    $student->update();

                    return redirect('home');
                  }
                  else{
                    return redirect('/login')->with('error','Wrong Email/Password combination');
                }
            }
        }
    }




}
