<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Validation\ValidationException;

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

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

    /**
     * Handle a login request to the application.
     *
     * @param Request $request
     * @return RedirectResponse|Response|JsonResponse
     *
     * @throws 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 (!$credentials = $this->credentials($request)) {
            return $this->sendFailedLoginResponse($request);
        }

        $username = $credentials[array_key_first($credentials)];
        $user = User::where(array_key_first($credentials), $username)->first();

        if (!$user) {
            return $this->sendFailedLoginResponse($request);
        } elseif ($user->status == 'banned') {
            return redirect()->back()
                ->withInput(['username' => $username])
                ->withErrors(['auth_result' => trans('auth.banned')]);
        } elseif ($user->status == 'disabled') {
            return redirect()->back()
                ->withInput(['username' => $username])
                ->withErrors(['auth_result' => trans('auth.disabled')]);
        } elseif (config('must_verify_email') and !$user->email_verified_at) {
            return redirect()->back()
                ->withInput(['username' => $username])
                ->withErrors(['auth_result' => trans('auth.email.verify')]);
        } elseif (config('must_verify_mobile') and !$user->mobile_verified_at) {
            return redirect()->back()
                ->withInput(['username' => $username])
                ->withErrors(['auth_result' => trans('auth.mobile.verify')]);
        }

        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);
    }


    /**
     * Get the needed authorization credentials from the request.
     *
     * @param Request $request
     * @return array|boolean
     */
    protected function credentials(Request $request)
    {
        $username = $request->input($this->username());
        $password = $request->only('password');

        if (preg_match('/^09\d{9}$/', $username)) {
            $username = ['mobile' => $username];
        } elseif (filter_var($username, FILTER_VALIDATE_EMAIL)) {
            $username = ['email' => $username];
        } else {
            $username = ['username' => $username];
        }

        return array_merge($username, $password);
    }


    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function username()
    {
        return 'username';
    }
}
