<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Session;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redirect;
use App\Rules\Captcha;
use DB;
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 = '/home';

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

    public function login(Request $request)
    {
        $login_url = (str_replace(url('/'), '', url()->previous()));  

        if($login_url!='/benthamsecurelogin/adminlogin' and $request->input('identity')==='eurekasadmin'){

           Session::flash('login_message', 'The username '.$request->input('identity').' has not been activated or is blocked.');
           return Redirect::to('/login');
        }

        if($login_url==='/benthamsecurelogin/managerlogin' and $request->input('identity')!='eurekasadmin'){
           
           $managerObj = DB::select("select users.name
                    FROM users, role_user, role
                    WHERE users.id = role_user.user_id
                    AND role_user.role_id = role.id and (users.name = '".trim($request->input('identity'))."' or users.email = '".trim($request->input('identity'))."')");
            if(empty($managerObj)){
                Session::flash('login_message', 'The username '.$request->input('identity').' has not been activated or is blocked.');
                //return Redirect::to('/login');
				return Redirect::to('/benthamsecurelogin/managerlogin');
            }
        }
        
        $md5pass = md5($request->input('password'));
        $userMd5 = DB::select("select * from users where (email='".$request->input('identity')."' or name='".$request->input('identity')."') and status=1 and (password is null and pass_md5 is not null) and pass_md5='".$md5pass."'" );
       
        if($userMd5){
            $passhash = Hash::make($request->input('password'));
            DB::select("update users set password='".$passhash."' where id='".$userMd5[0]->id."'");
        }

        $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)) {
            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);
    }
   protected function credentials(Request $request)
    {
         
    $type = filter_var($request->input('identity'), FILTER_VALIDATE_EMAIL)
    ? 'email'
    : 'name';

    $request->merge([
    $type => $request->input('identity')
    ]);

    // call the verifyCaptcha method to see if Google approves
    /*$captchaVerified = $this->verifyCaptcha($request->input('g-recaptcha-response'));
    request()->validate([            
            'g-recaptcha-response' => ['required', $captchaVerified]
            //'g-recaptcha-response' => $this->verifyCaptcha($request->input('g-recaptcha-response'))
        ]
        );*/
   
    return $request->only($type,'password');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
   
    protected function validateLogin(Request $request)
    {
        return $this->validate($request, [
             'g-recaptcha-response' => new Captcha()
        ]);    
    }

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

    public function authenticated(Request $request, $user) {
        
        if ($user->status != 1) {      
            Auth::logout($request);     
            return redirect()->back();
        }
        
        $user->last_login = Carbon::now()->toDateTimeString();
        $user->save();
        
        $logindata['uid'] = $user->id;
        $logindata['uname'] = $user->name;
        $logindata['remote_ip'] = $_SERVER['REMOTE_ADDR'];
        $logindata['client_ip'] = $request->ip();
        $logindata['login_datetime'] = Carbon::now()->toDateTimeString();
        DB::table('user_login_logs')->insert($logindata);
        redirect(url()->previous());
    }
    
}
