<?php

namespace twa\ecomauth\controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use League\Flysystem\Config;
use twa\apilibs\controllers\PhoneFunctionsController;
use twa\apilibs\traits\APITrait;
use twa\cms\models\User;
use twa\ecomauth\models\EcomUsersVerificationChallengesModel;
use twa\ecomgeneral\mail\EmailFromTemplate;
use twa\ecomgeneral\models\EcomUsersModel;
use twa\htmlhelpers\helpers\urlHelper;
use Validator;

class AccountLoginController extends Controller
{
    use APITrait;

    // Render Pages
    public function render($values = []){
        $values = $this->ProcessValues($values);
        $Check = $this->ProcessRequired($values, []);
        if ($Check!==true) {
            return $Check;
        }

        return view('EcomAuthViews::authentication.render' , ['forceCompleteProfile' => $values->get('forceCompleteProfile')])->render();
    }
    public function renderGuestCheckout(){
        $config = config('ecom-auth');
        $type = false;
        $type = $config['primary'];
        $country_code = country()->code();
        if($country_code == null){
            if(isset(ecom('stores')->getCurrent()['flag_countries_id']['code'])){
                $country_code = ecom('stores')->getCurrent()['flag_countries_id']['code'];
            }else{
                $country_code = "LB";
            }
        }
        switch ($type) {
            case 'phone':
                return view('EcomAuthViews::authentication.guest-mobile',[ "type" => $type, 'country_code'=>$country_code]);
                break;
            case 'email':
                return view('EcomAuthViews::authentication.guest-mobile',[ "type" => $type ]);
                break;
        }

    }




    public function renderCompleteProfile($store, $lang, $user_id, $token){
        if (md5($user_id) != $token) {
            return abort("404");
        }

        $user = EcomUsersModel::find($user_id);

        if (!$user) {
            return abort("404");
        }

        $fields = $this->checkProfileComplete($user);

        return view('EcomAuthViews::authentication.complete-profile',compact('user','fields'));

    }

    public function renderAuthenticate($store, $lang, $type = null)
    {

        session(["email" => null, "phone" => null]);

        $config = config('ecom-auth');

        $type = $type ? $type : $config['primary'];

        $available_login_methods = collect($config['providers'])->where('active' , true)->map(function($provider){
            return [
                'icon' => $provider['provider'], 'label' => ___($provider['label']), 'href' => ''
            ];
        });

        $alternative_types = array_diff($config['auth_types'], [$type]);
        foreach($alternative_types as $alternative_type) {
            try {
                $available_login_methods->push([
                    'icon' => $alternative_type,
                    'label' => ___('authentication.login_' . $alternative_type),
                    'href' => route('account-auth', ['type' => $alternative_type])
                ]);
            }catch(\Throwable $th){

            }
        }

        $country_code = country()->code();
        if($country_code == null){
            if(isset(ecom('stores')->getCurrent()['flag_countries_id']['code'])){
                $country_code = ecom('stores')->getCurrent()['flag_countries_id']['code'];
            }else{
                $country_code = "LB";
            }
        }

        return view('EcomAuthViews::authentication.auth', compact('country_code', 'available_login_methods', 'type'));
    }

    public function renderLoginPassword($store, $lang, $type, $user_id, $token)
    {

        if (md5($user_id) != $token) {
            return abort("404");
        }

        $user = EcomUsersModel::find($user_id);

        if (!$user) {
            return abort("404");
        }

        return view('EcomAuthViews::authentication.login', compact('user', 'type'));
    }

    public function renderLoginPin($store, $lang, $type, $user_id, $token)
    {
        //dd($user_id);
        //$phoneInput=request()->input('phoneInput',null);
        //$message=request()->input('message',null);
        return view('EcomAuthViews::authentication.login', compact('challenge', 'message', 'phoneInput'));
    }

    public function renderLogin($store, $lang, $action ,$login_type, $type, $user_id, $token)
    {
        if (md5($user_id) != $token) {
            return abort("404");
        }

        $config = config('ecom-auth');
        $password_exist = $this->passwordEnabled();

        $user = EcomUsersModel::find($user_id);

        if (!$user) {
            return abort("404");
        }

        if(request()->input('resend') == "true"){
            $challenge = $this->sendChallenge($user , 'sms');
            if(!$challenge){
                $notification =self::GetNofication(55)->getOriginalContent();
                return redirect(twaURL()->addParameter( ecom('url')->prefix(true).'/account/auth/phone' ,[ 'title' => $notification[1] ,'notification' => $notification[2] ]));
            }else{
                return redirect(ecom('url')->prefix().'/account/get/redirect/otp/phone/'.$user['id'].'/'.md5($user['id']));
            }
        }

        $action = $this->getLoginAction($user , $type);


        $challenge = session('challenge');

        if (!$challenge && $login_type == "otp") {
            $notification =self::GetNofication(55)->getOriginalContent();
            return redirect(twaURL()->addParameter(redirect()->back()->getTargetUrl(),[ 'title' => $notification[1] ,'notification' => $notification[2] ]));
//            return abort("403", "Session Expired");
        }

        if (isset($challenge['challenge'])) {
            $challenge = $challenge['challenge'];
        }


        $other_auth_methods = [];

        if ($login_type == "otp") {
            if ($action == "password_login") {
                $other_auth_methods [] = [
                    'label' => "Login using Password",
                    'link' => str_replace("/login/otp/", "/login/password/", url()->current())
                ];
            }

        }else{
            $other_auth_methods [] = [
                'label' => "Login using OTP",
//                'link' => str_replace(["/login/password/" , "get/"], ["/redirect/otp/" , ""], url()->current())

            'link'=>route('redirect-otp', ['action'=>'otp' , 'login_type' => 'otp' , 'type' => $type , 'user_id' => $user->id , 'token' => $this->generateRouteToken($user->id)])
            ];

        }

        if ($password_exist) {
            $other_auth_methods [] = [
                'label' => "Reset Password",
                'link' => route("redirect-otp" , [
                    'action' => 'reset' ,
                    'login_type' => 'otp' ,
                    'type' => $type ,
                    'user_id' => $user_id,
                    'token' => $token
                    ])
            ];
        }

        return view('EcomAuthViews::authentication.login',compact('user','type','login_type' , 'challenge' ,'config' ,'other_auth_methods'));

    }

    public function renderRegister($store , $lang , $type = null){
        $config= config('ecom-auth');
        $type = $type ? $type : $config['primary'];

        $alternative_type = $type == "email" ? "phone" : "email";

        $register_data = session($type);

        $data['email'] = isset($register_data['email']) ? $register_data['email'] : "";
        $data['phone'] = isset($register_data['phone_original']) ? $register_data['phone_original'] : "";
        $data['phone_country_code'] = isset($register_data['phone_country_code']) ? $register_data['phone_country_code'] : "";

       $fields = $this->getRegisterFields();

        return view('EcomAuthViews::authentication.register' ,compact('type', 'config' , 'data' , 'fields'));
    }

    public function renderAddNewIdentity($store , $lang , $type , $user_id , $token){

        if (md5($user_id) != $token) { return abort("404"); }

        $user = EcomUsersModel::find($user_id);

        if(!$user){ return abort("403" , "User not found"); }

        return view('EcomAuthViews::authentication.add-identity' ,compact('type' , 'user'));
    }

    public function renderResetPassword($store , $lang , $type ,$user_id , $token){

        if (md5($user_id) != $token) { return abort("404"); }

        $user = EcomUsersModel::find($user_id);

        if(!$user){ return abort("403" , "User not found"); }

        return view('EcomAuthViews::authentication.reset-password' , ['user' => $user , 'type' => $type]);
    }

    // Post Actions

    public function authenticate($store , $lang , $type = null){
        $config= config('ecom-auth');
        $type = $type ? $type : $config['primary'];
        $auth_types = $config['auth_types'];

        switch ($type) {
            case 'phone':

                $PhoneValidation = null;

                $validator = Validator::make(request()->all(), [
                    'phone_country_code' => 'required',
                    'phone' => 'required'
                ])->after(function ($validator) use(&$PhoneValidation){
                    $PhoneValidation = \twa\apilibs\controllers\PhoneFunctionsController::validatePhoneNumber(request()->input('phone'), request()->input('phone_country_code'));
                    if (!$PhoneValidation['valid']) {
                        $validator->errors()->add('phone', 'Please enter a valid phone number');
                    }
                })->validate();

                $user = \twa\ecomauth\models\EcomUsersModel::query()->where('guest_user', 0)->where('cancelled', 0)
                    ->where('phone', request()->full_number)->first();

                session(['guest' => request()->input('guest')]);

                if (!$user) {
                    session([$type => ['phone_original' => request()->phone, 'phone_country_code' => request()->phone_country_code]]);

                    $register_fields = $this->getRegisterFields()->reject(function($field) use($type , $auth_types){
                        if(in_array($field['name'] , $auth_types)){ return true; }
                    })->filter()->values();


                    if(count($register_fields) > 0 && session('guest') != 1){
                        return redirect()->route('account-register', ['type' => $type]);
                    }

                    $new_user = new EcomUsersModel();
                    $new_user->phone = $PhoneValidation['phone'];
                    $new_user->phone_original = request()->phone;
                    $new_user->phone_country_code = request()->phone_country_code;
                    $new_user->guest_user = 0;
                    $new_user->save();

                    session([ 'challenge' => $this->sendChallenge($new_user , 'sms')]);

                    return redirect()->route('account-action',[  'action' => 'login' ,'user_id'=>$new_user['id'] , 'login_type' => 'otp'  ,'type' =>  $type , 'token' => md5($new_user['id'])]);
                }



                break;

            case 'email':

                request()->validate([
                    'email' => 'required|email'
                ]);

                $user = \twa\ecomauth\models\EcomUsersModel::query()
                    ->where('cancelled', 0)
                    ->where('guest_user', 0)
                    ->where('email', request()->email)->first();
                session(['guest' => request()->input('guest')]);
                if (!$user) {
                    session([$type => ['email' => request()->email]]);

                    $register_fields = $this->getRegisterFields()->reject(function($field) use($type , $auth_types){
                        if(in_array($field['name'] , $auth_types)){ return true; }
                    })->filter()->values();


                    if(count($register_fields) > 0 && session('guest') != 1){
                        return redirect()->route('account-register', ['type' => $type]);
                    }

                    $new_user = new EcomUsersModel();
                    $new_user->email = request()->email;
                    $new_user->guest_user = 0;
                    $new_user->save();

                    session(['challenge' => $this->sendChallenge($new_user , 'email')]);
                    return redirect()->route('account-action',[ 'action' => 'login' ,'user_id'=>$new_user['id'] , 'login_type' => 'otp'  ,'type' =>  $type , 'token' => md5($new_user['id'])]);
                }





                break;
        }


        $action = $this->getLoginAction($user , $type);

        switch($action){
            case "otp_login" :
                session(['challenge' => $this->sendChallenge($user , 'sms')]);
                return redirect()->route('account-action',[ 'action' => 'login' ,'user_id'=>$user['id'] , 'login_type' => 'otp'  ,'type' =>  $type , 'token' => md5($user['id'])]);

            case "password_login":
                return redirect()->route('account-action',[ 'action' => 'login' ,'user_id'=>$user['id'] , 'login_type' => 'password'  ,'type' =>  $type , 'token' => md5($user['id'])]);
                break;
        }

    }

    public function completeProfile($store , $lang , $user_id , $token){
        if (md5($user_id) != $token) { return abort("404"); }
        $user = EcomUsersModel::find($user_id);
        if(!$user){ return abort("403" , "User not found"); }

        $required = [];
        $input_values = request()->all();

        $config = config('ecom-auth');
        $verification_strict = $config['verification_strict'];

        $all_required = $this->getValidations();
        $complete_profile = collect($this->checkProfileComplete($user))->pluck('name');

//        foreach($required as $key => $rule){
//            if(isset($complete_profile[$key])){
//                    unset($required[$key]);
//            }
//        }

        $required = [];

        foreach($complete_profile as $cp){
            if(isset($all_required[$cp])){
                $required [$cp] = $all_required[$cp];
            }
        }

        $register_config = [
            'email' => [  'verifiy' => 'verified'],
            'phone' => [  'verifiy' => 'mobile_verification']
        ];

        $has_phone = isset($required['phone']);
        $has_email = isset($required['email']);



        $validator = Validator::make(request()->all(), $required)->after(function ($validator) use ($verification_strict , $has_phone , $has_email){

            $field_value = null;
            $verification_field = null;
            if($has_phone) {
                $PhoneValidation = \twa\apilibs\controllers\PhoneFunctionsController::validatePhoneNumber(request()->input('phone'), request()->input('phone_country_code'));
                if (!$PhoneValidation['valid']) {
                    $validator->errors()->add('phone', 'Please enter a valid phone number');
                }
                $unique_phone = $PhoneValidation['phone'];
                $verification_field =  "mobile_verification";
                $field_value= ["phone" ,$PhoneValidation['phone']];
            }elseif($has_email){
                $verification_field = "verified";
                $field_value= ["email" ,request()->email];
            }

            if($field_value) {

                $user = \twa\ecomauth\models\EcomUsersModel::where('cancelled', 0)
                    ->where($field_value[0], $field_value[1])
                    ->where('guest_user', 0);

                $user = $user->first();

                if ($user) {
                    $validator->errors()->add($field_value[0], $field_value[0] . '_already_exists');
                }
            }
        })->validate();


        $response =  (new EcomUsersRegistration())->updateUser($user , request()->all());

        if ($response->getStatusCode() != 200) {
            dd($response->getOriginalContent());
           dd("error updating user");
        }



        return view('EcomAuthViews::redirection',['url'=>ecom('url')->prefix().'/']);



    }

    public function addNewIdentity($store , $lang , $type , $user_id , $token){
        if (md5($user_id) != $token) { return abort("404"); }

        $user = EcomUsersModel::find($user_id);

        if(!$user){ return abort("403" , "User not found"); }


        switch ($type){
            case 'phone':

                $PhoneValidation = null;

                $validator = Validator::make(request()->all(), [
                    'phone_country_code' => 'required',
                    'phone' => 'required'
                ])->after(function($validator) use(&$PhoneValidation) {
                    $PhoneValidation = \twa\apilibs\controllers\PhoneFunctionsController::validatePhoneNumber(request()->input('phone'), request()->input('phone_country_code'));
                    if (!$PhoneValidation['valid']) { $validator->errors()->add('phone', 'Please enter a valid phone number'); }

                    $check_user=\twa\ecomauth\models\EcomUsersModel::query()->where('cancelled',0)
                        ->where('phone',request()->full_number)
                        ->where('mobile_verification' , 1)
                        ->where('guest_user' , 0)
                        ->first();

                    if($check_user){ $validator->errors()->add('phone', 'Phone number is already taken'); }

                })->validate();


                $user->phone = $PhoneValidation['phone'];
                $user->phone_country_code = request()->input('phone_country_code');
                $user->phone_original = request()->input('phone');
                $user->mobile_verification = 0;
                $user->save();

                session(['challenge' => $this->sendChallenge($user , 'sms')]);
                return redirect()->route('account-action',[ 'action' => 'login' ,'user_id'=>$user['id'] , 'login_type' => 'otp'  ,'type' =>  $type , 'token' => md5($user['id'])]);


            case 'email':

                $validator = Validator::make(request()->all(), [
                    'email' => 'required|email'
                ])->after(function($validator){

                    $check_user=\twa\ecomauth\models\EcomUsersModel::query()->where('cancelled',0)
                        ->where('email',request()->email)
                        ->where('verified' , 1)
                        ->where('guest_user' , 0)
                        ->first();

                    if($check_user){ $validator->errors()->add('phone', 'Email address is already taken'); }

                })->validate();

                $user->email = request()->input('email');
                $user->verified = 0;
                $user->save();

                session(['challenge' => $this->sendChallenge($user , 'email')]);
                return redirect()->route('account-action',[ 'action' => 'login' ,'user_id'=>$user['id'] , 'login_type' => 'otp'  ,'type' =>  $type , 'token' => md5($user['id'])]);

            default:
                dd("No other login type");

        }

        dd(request()->all());
    }

    public function login($store,$lang, $action ,$login_type , $type ,$user_id , $token){
        if(md5($user_id) != $token || !in_array($type , ['email' , 'phone']) ){ return abort("404"); }
        $config = config('ecom-auth');
        $verification_strict = $config['verification_strict'];
        $user = null;

        if($action == "reset"){

            $validator = Validator::make(request()->all(), [
                'code' => 'required',
                'challenge' => 'required',
                'user_id' => 'required'

            ])->after(function($validator) use($type , &$user) {
                $user_id = request()->input('user_id');
                $user = EcomUsersModel::find($user_id);

                $response =  (new EcomUsersRegistration())->verifyUserByPin([
                    "pin"=> implode('',request()->code),
                    "challenge"=>request()->challenge,
                    "type"=> $type,
                ]);

                if ($response->getStatusCode() != 200) {
                    $validator->errors()->add('code', 'You have entered an incorrect pin');
                }

            })->validate();

            return redirect()->route('account-reset-password' , [ 'type' => $type ,'user_id'=> $user_id , 'token' => $token ]);
        }


        switch($login_type){
            case "otp" :

                $validator = Validator::make(request()->all(), [
                    'code' => 'required',
                    'challenge' => 'required',
                    'user_id' => 'required'

                ])->after(function($validator) use($type , &$user) {
                    $user_id = request()->input('user_id');
                    $user = EcomUsersModel::find($user_id);

                    $response =  (new EcomUsersRegistration())->verifyUserByPin([
                        "pin"=> implode('',request()->code),
                        "challenge"=>request()->challenge,
                        "type"=> $type,
                    ]);


                    if ($response->getStatusCode() != 200) {
                        $validator->errors()->add('code', 'You have entered an incorrect pin');
                    }

                    session(["login" => $response->getOriginalContent()]);

                })->validate();

                break;

            case "password":

                $validator = Validator::make(request()->all(), [
                    'password' => 'required',
                    'user_id' => 'required'
                ])->after(function($validator) use($type , &$user , $verification_strict) {
                    $user_id = request()->input('user_id');
                    $user = EcomUsersModel::find($user_id);


                    if(!$verification_strict){
                        $response =  (new \twa\ecomauth\controllers\EcomUsersRegistration())->loginByUserId([
                            "user_id" => $user->id,
                            "password" => request()->input('password')
                        ]);
                    }else {
                        if ($type == "email") {
                            $response = (new \twa\ecomauth\controllers\EcomUsersRegistration())->login([
                                "email" => $user->email,
                                "password" => request()->input('password')
                            ]);

                        } elseif ($type == "phone") {
                            $response = (new \twa\ecomauth\controllers\EcomUsersRegistration())->loginByPhone([
                                "phone" => $user->phone,
                                "password" => request()->input('password')
                            ]);
                        }
                    }

                    $result = $response->getOriginalContent();

                    if ($response->getStatusCode() != 200) {
                        $validator->errors()->add('password', $result['error']['title']);
                    }
                    session(["login" => $result]);

                })->validate();

                break;

        }


        if(is_null($user->email) && in_array('email' , $config['auth_verifications']) && session('guest') != 1){
            return redirect()->route('account-add-identity' , ['user_id' => $user_id ,'type'=>'email' , 'token' => $token]);
        }

        if(is_null($user->phone) &&  in_array('phone' , $config['auth_verifications']) && session('guest') != 1){
            return redirect()->route('account-add-identity' , ['user_id' => $user_id , 'type' => 'phone' ,'token' => $token]);
        }

        $incomplete_fields = $this->checkProfileComplete($user);
        if(count($incomplete_fields)>0  && session('guest') != 1){
            return redirect()->route('complete-profile' , ['user_id' => $user_id ,'token' => $token ]);
        }

        if(session('guest') == 1) {
            $url = ecom('url')->prefix().'/checkout/delivery';
        }else{
            $url = ecom('url')->prefix().'/';
        }
        session([ 'guest' => false ]);

        \twa\ecomcart\controllers\EcomCartController::offlineToOnline($_COOKIE['offlineToken_v2'],session('login')['id']);
        return view('EcomAuthViews::redirection',[ 'url'=> $url ]);
    }

    public function register($store , $lang , $type){



        $required = [];
        $input_values = request()->all();

        $config = config('ecom-auth');
        $verification_strict = $config['verification_strict'];

        $required = $this->getValidations();

        $register_config = [
            'email' => [  'verifiy' => 'verified'],
            'phone' => [  'verifiy' => 'mobile_verification']
        ];

        $has_phone = isset($required['phone']);
        $has_email = isset($required['email']);

        if(!$has_phone && !$has_email){ dd("Please you need to have at least one of the following fields: email , phone"); }

        $validator = Validator::make(request()->all(), $required)->after(function ($validator) use ($verification_strict , $has_phone){

            $field_value = null;

            if($has_phone) {
                $PhoneValidation = \twa\apilibs\controllers\PhoneFunctionsController::validatePhoneNumber(request()->input('phone'), request()->input('phone_country_code'));
                if (!$PhoneValidation['valid']) {
                    $validator->errors()->add('phone', 'Please enter a valid phone number');
                }
                $unique_phone = $PhoneValidation['phone'];
                $verification_field =  "mobile_verification";
                $field_value= ["phone" ,$PhoneValidation['phone']];
            }else{
                $verification_field = "verified";
                $field_value= ["email" ,request()->email];
            }

            $user=\twa\ecomauth\models\EcomUsersModel::where('cancelled',0)
                ->where($field_value[0],$field_value[1])
                ->where('guest_user', 0);

            if($verification_strict){
                $user->where($verification_field , 1);
            }else{
                $user->where(function($q){
                    $q->orWhere('verified' , 1);
                    $q->orWhere('mobile_verification' , 1);
                });
            }

            $user = $user->first();

            if($user){ $validator->errors()->add($field_value[0], $field_value[0].'_already_exists'); }

        })->validate();

        if($has_phone && !$has_email){
            $response = (new EcomUsersRegistration)->createUserByMobile($input_values);
        }

        if($has_email && !$has_phone) {
            $response = (new EcomUsersRegistration)->createUserByEmail($input_values);
        }

        if($has_email && $has_phone) {
            $response = (new EcomUsersRegistration)->createUserByEmailAndMobile($input_values);
        }

        $result = $response->getOriginalContent();
        if($response->getStatusCode() != 200){
            dd("error creating user");
        }

        $verification_type = !in_array($type , $config["auth_verifications"]) ? $config["auth_verifications"][0] : $type;

        return redirect()->route('redirect-otp' , [
            'action' => 'login',
            'login_type' => 'otp',
            'type' => $verification_type,
            'user_id' => $result['user']['id'],
            'token' => $this->generateRouteToken($result['user']['id'])
        ]);

    }

    public function redirectToOTP($store,$lang, $action  ,$login_type ,$type ,$user_id , $token){



        if(md5($user_id) != $token || !in_array($type , ['email' , 'phone']) ){ return abort("404"); }

        $user = EcomUsersModel::find($user_id);

        if(!$user){ return abort("403" , "User not found"); }

        session(['challenge' => $this->sendChallenge($user , $type)]);

        return redirect()->route('account-action',[ 'action' => $action , 'user_id'=>$user['id'] , 'login_type' => $login_type  ,'type' =>  $type , 'token' => md5($user['id'])]);
    }

    public function resetPassword($store , $lang ,$type ,$user_id , $token){

        if (md5($user_id) != $token) { return abort("404"); }



        $user = EcomUsersModel::find($user_id);

        if(!$user){ return abort("403" , "User not found"); }


        $validator = Validator::make(request()->all(), [
            'password' => 'required',
            'confirm_password' => 'required|same:password'
        ])->validate();

        $user->password = md5(request()->password);
        $user->save();

        $this->loginById($user->id);

        return view('EcomAuthViews::redirection',['url'=>ecom('url')->prefix().'/']);
    }


    // Helper functions

    public function sendChallenge($user, $type){
        $ecomUsersRegistration = (new EcomUsersRegistration);
        $challenge = $ecomUsersRegistration->createChallenge($user);
        if(!$challenge){ return false; }

        if($type == "sms"){
            $ecomUsersRegistration->sendVerification($user , $challenge , $type=="sms" ? 'mobile_pin' : 'email verification');
        }

        return $challenge;
    }


    public function loginById($user_id){
        $response =  (new EcomUsersRegistration())->forceLoginByUserId([ "user_id"=> $user_id ]);
        if ($response->getStatusCode() != 200) { dd($response->getOriginalContent()); }
        session(["login" => $response->getOriginalContent()]);
    }

    public function getRegisterFields(){
        $config= config('ecom-auth');

        $fields = [
            ['label' => 'authentication.first_name' , 'name' => 'first_name' , 'type' => 'text' , 'size' => 'full' , 'required' => false , 'options' => []],
            ['label' => 'authentication.last_name' , 'name' => 'last_name' , 'type' => 'text' , 'size' => 'full' , 'required' => false , 'options' => []],
            ['label' => 'authentication.email' , 'name' => 'email' , 'type' => 'text' , 'size' => 'full' , 'required' => false, 'options' => []],
            ['label' => 'authentication.phone_number' , 'name' => 'phone' , 'type' => 'phone' , 'size' => 'full' , 'required' => false, 'options' => []],
            ['label' => 'authentication.password' , 'name' => 'password' , 'type' => 'password' , 'size' => 'full' , 'required' => false, 'options' => []],
            ['label' => 'authentication.confirm_password' , 'name' => 'confirm_password' , 'type' => 'password' , 'size' => 'full' , 'required' => false, 'options' => []]
        ];

        $fields_options = $config["fields_options"];
        $fields_orders = $config['field_orders'];
        $additional_fields = $config["additional_fields"];

        foreach($additional_fields as $additional_field){
            if(!isset($fields_options[$additional_field['name']])){
                $fields_options[$additional_field['name']] = [ 'display' => true, 'required' => $additional_field['required']];
            }
        }

        return collect($fields)->merge($additional_fields)->map(function($field) use ($fields_options , $fields_orders){

            if(!isset($fields_options[$field['name']]['display']) || isset($fields_options[$field['name']]['display']) && !$fields_options[$field['name']]['display']){
                return null;
            }

            if(isset($fields_options[$field['name']]['required']) && $fields_options[$field['name']]['required']){
                $field['required'] = true;
            }

            $field['orders'] = in_array($field['name'] , $fields_orders) ? array_search($field['name'], $fields_orders) : 999;

            return $field;
        })->filter()->values()->sortBy('orders')->values();
    }

    public function getValidations(){
       $required_fields =  $this->getRegisterFields()->where('required' , true)->pluck('name');

       $validations = [];
       foreach($required_fields as $required_field){
            $validations[$required_field] = "required";

            if($required_field == "email"){
                $validations[$required_field] .= "|email";
            }

            if($required_field == "confirm_password"){
               $validations[$required_field] .= "|same:password";
            }

           if($required_field == "phone"){
               $validations["phone_country_code"] = "required";
               $validations["full_number"] = "required";
           }
       }

       return $validations;
    }

    public function passwordEnabled(){
        $config= config('ecom-auth');
        return isset($config["fields_options"]["password"]["display"]) && $config["fields_options"]["password"]["display"];
    }


    public function checkProfileComplete($user){
        $fields = $this->getRegisterFields();

        $required_fields = $fields->where('required' , true)->values();

        $incomplete_fields = [];

        foreach ($required_fields as $required_field){
            if(empty($user->{$required_field['name']}) || is_null($user->{$required_field['name']})){
                $incomplete_fields [] = $required_field;
            }
        }

        if(count($incomplete_fields) == 1 && $incomplete_fields[0]['name'] == 'confirm_password'){
            return [];
        }

        return $incomplete_fields;
    }

    public function getLoginAction($user , $type){

        $config= config('ecom-auth');

        $verify_atribute = $type == "email" ? "verified" : "mobile_verification";

        $actions = ['otp_login' => false, 'password_login' => false];
        $action = $config["otp_primary"] == true ? 'otp_login' : 'password_login';


        if (!$config['verification_strict'] && $user[$verify_atribute] != 1 || in_array($type, $config["auth_verifications"])) {
            $actions["otp_login"] = true;
        }


        $password_exist = $this->passwordEnabled();
        $user_has_password = !is_null($user->password);

        if ($password_exist && $user_has_password) { $actions["password_login"] = true; }

        if ((!$config["otp_primary"] || !$actions['otp_login']) && ($password_exist && $user_has_password)) {
            $action = "password_login";
        }

        if($action == "password_login" && (!$password_exist || !$user_has_password) ){

            if($actions["otp_login"]){
                $action = "otp_login";
            }else {
                dd("OTP method not available for login, in your configuration");
            }

        }

        return $action;
    }

    public function generateRouteToken($id){
        return md5($id);
    }



}
