<?php

namespace App\Http\Controllers\TeacherAuth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;

use Illuminate\Http\Request;
use App\User;

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.
    |
    */



    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    public $redirectTo = '/teacher_profile';

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

    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        return view('login-v2');
    }


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

        if(!$teacher){
            return redirect('/login-v2')->with('error','Unknown Email address!');
        }else{
            if($teacher->apply_status == 0){
                return redirect('/login-v2')->with('error', 'Your account is still under review.');
            }
            else{
                $credentials = [
                    'email' => $request->email,
                    'password' => $request->password,
                    'apply_status' => '1',
                    'status' => '1',
                ];

                if (Auth::guard('teacher')->attempt($credentials)) {

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

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

    public function logout(){
        $this->guard('teacher')->logout();
        request()->session()->invalidate();
        return redirect('/login-v2');

    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected function guard()
    {
        return Auth::guard('teacher');
    }
}
