<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Auth;
use App\Models\UserCode;
use Illuminate\Contracts\Session\Session;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

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;

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

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function login(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'phone' => 'required|numeric|starts_with:0|digits:10'
        ], [
            'phone.required' => 'Le champ Téléphone est obligatoire!',
            'phone.digits' => 'Le champ téléphone doit comporter 10 chiffres.',
            'phone.starts_with' => 'Le champ téléphone doit commencer par zero(0).'
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withInput()->withErrors($validator);
        }

        $phone = $request->phone;

        $loginRequest = User::where('phone', '+225'.$phone )->first();
        // dd($loginRequest);
        // dd( '$loginRequest');

        if ($loginRequest) {

            if (Auth::loginUsingId($loginRequest->id)) {
                
                if (!auth()->user()->email_verified_at) {

                    auth()->user()->generateCode();
                }
                
                return redirect()->route('2fa.index');
            }
        }

        return redirect("register")->withSuccess('Oppes! You have entered invalid credentials');
    }

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