<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Cache;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Contracts\Auth\Authenticatable;
use App\Http\Requests\ValidateSecretRequest;
use Carbon\Carbon;
use Illuminate\Support\Facades\Hash;
use App\Support\Google2FAAuthenticator;
use Log;
class LoginController extends Controller
{

    protected $maxAttempts = 2; // Amount of bad attempts user can make

    protected $decayMinutes = 2;

    protected $username = 'username';


    /*
    |--------------------------------------------------------------------------
    | 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 = '/home';

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


    public function loginUsername()
    {
        return 'username';
    }

    public function username()
    {
        return 'username';
    }

       /**
 * Handle a login request to the application.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
protected function validateLogin(\Illuminate\Http\Request $request)
{
    //dd($request->all());
    $this->validate($request, [
        $this->loginUsername() => 'required', 
        'password' => 'required',
        'CaptchaCode' => 'required|valid_captcha'
    ]);
}

 /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function login(Request $request)
    {

        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if (method_exists($this, 'hasTooManyLoginAttempts') &&
            $this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
           $request->session()->regenerate();
           $this->clearLoginAttempts($request);
           $user = Auth::user();
           if($user->status != 'ACTIVE'){
                $this->logout($request);

            // Return them to the log in form.
                return redirect()->back()
                    ->withInput($request->only($this->loginUsername(), 'remember'))
                    ->withErrors([
                    // This is where we are passing the message back.
                        $this->loginUsername() => 'Your account is '.$user->status.', Please contact to admin'
                    ]);
           }
            return $this->redirectTo2fa($request);
            //return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }



    public function handleAfterLogin($request){
        //Log::info('handleafterlogin');
        return $this->authenticated($request, $this->guard()->user())
        ?: redirect()->intended($this->redirectPath());
    }

    private function redirectTo2fa($request){
        //Log::info('redirect2fa');
        $authenticator = app(Google2FAAuthenticator::class)->boot($request);
        if(!$authenticator->isAuthenticated()){
            //$request->session()->put('from', 'login');
            return $authenticator->makeRequestOneTimePasswordResponse(); 
        }else{
            return $this->handleAfterLogin($request);
        }
    
    }
    private function authenticated(Request $request, Authenticatable $user)
    {
        Log::info('authenticated on');
        $user = Auth::user();

        if(empty($user->password_changed_at)){
            return redirect()->route('password.expired');
        }else{
            $password_changed_at = new Carbon(($user->password_changed_at));

            if ((Carbon::now()->diffInDays($password_changed_at) >= config('auth.password_expires_days'))) {
                return redirect()->route('password.expired');
            }else if(!$user->passwordSecurity){
                return redirect('2fa');  
            }
        }

        //Log::info('authenticated');

        // if ($user->google2fa_secret) {
        //     Auth::logout();

        //     $request->session()->put('2fa:user:id', $user->id);

        //     return redirect('2fa/validate');
        // }

        // return redirect()->intended($this->redirectTo);
    }

    // public function getValidateToken()
    // {
    //     if (session('2fa:user:id')) {
    //         return view('2fa/validate');
    //     }

    //     return redirect('login');
    // }

    /**
     *
     * @param  App\Http\Requests\ValidateSecretRequest $request
     * @return \Illuminate\Http\Response
     */
    // public function postValidateToken(ValidateSecretRequest $request)
    // {
    //     //get user id and create cache key
    //     $userId = $request->session()->pull('2fa:user:id');
    //     $key    = $userId . ':' . $request->totp;

    //     //use cache to store token to blacklist
    //     Cache::add($key, true, 4);

    //     //login and redirect user
    //     Auth::loginUsingId($userId);

    //     return redirect()->intended($this->redirectTo);
    // }

    public function logout(Request $request)
    {
        Log::info('logging out user ');
        $this->guard()->logout();

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

        return $this->loggedOut($request) ?: redirect('/login');
    }

    public function redirect(){
        return redirect()->intended($this->redirectPath());
    }
}
