<?php

namespace twa\ecomauth\repositories;


use Illuminate\Support\Facades\DB;

class CommonRepository
{

    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 == "password"){
                $validations[$required_field] .= "|min:8|regex:/[A-Z]/";
            }

            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 = collect([]);

        $config = config('ecom-auth');
        $phone_field_required = false;
        $email_field_required = false;

        $already_passed = [];

        $auth_verifications = $config['auth_verifications'];

        if(!is_array($auth_verifications)){ $auth_verification = []; }

        foreach($auth_verifications as $auth_verification){
            switch($auth_verification){
                case "email" :
                    $email_field_required = $user->email_verified != 1;
                    break;

                case "phone" :
                    $phone_field_required = $user->phone_verified != 1;
                    break;
            }
        }

        foreach ($required_fields as $required_field){

            if($required_field['name'] == "confirm_password"){

                if(($incomplete_fields)->where('name' , 'password')->first()) {

                    if(!in_array('confirm_password' , $already_passed)){
                        $already_passed [] = 'confirm_password';
                        $incomplete_fields->push($required_field);
                    }


                }

                continue;
            }

            if(($required_field['name'] == "email" && $email_field_required) || ($required_field['name'] == "phone" && $phone_field_required)){

                if(!in_array($required_field['name'] , $already_passed)) {
                    $already_passed [] = $required_field['name'];
                    $incomplete_fields->push($required_field);
                }
            }


            if(empty($user->{$required_field['name']}) || is_null($user->{$required_field['name']})){

                if(!in_array($required_field['name'] , $already_passed)) {
                    $already_passed [] = $required_field['name'];
                    $incomplete_fields->push($required_field);
                }

            }elseif($user->{$required_field['name']}){

            }
        }

        return $incomplete_fields;
    }

    public function getLoginAction($user , $type){

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

        $verify_atribute = $type == "email" ? "email_verified" : "phone_verified";

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



        if (!$config["otp_primary"] && $password_exist && $user_has_password && $user->{$verify_atribute} == 1) {
            return "password_login";
        }

        if(!in_array($type , $config['auth_verifications']) && !$config["otp_primary"] && $password_exist && $user_has_password){
            return "password_login";
        }

        if(config('ecom-auth.bypass_verification')){
            return "render_profile";
        }
        return "otp_login";
    }

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

    public function getNotificationBySlug($slug){
        $lang = app()->getLocale();
        return DB::table('notifications')->select('id' , 'label_'.$lang.' AS label' , 'text_'.$lang.' AS text')->where('slug' , $slug)->where('cancelled' , 0)->first();
    }
    public function getErrorRoute($slug){
        $url = session('auth_redirect_current');
        $url = $url ? $url : "/";

        $url = $url.'?notification='. $slug;

        return $url;
    }

    public function redirectAsError($slug){
        $url = $this->getErrorRoute($slug);

        return view('EcomAuthViews::redirection',[ 'url'=> $url ]);
    }

    public function redirectAsLoggedIn($iframe = true){



        if(session('guest') == 1) {
            $url = ecom('url')->prefix().'/checkout/delivery';
        }else{
            $auth_redirect_url = session("auth_redirect_url");
            session(['auth_redirect_url' => null  , 'disable_auth_redirect_overwrite' => 0]);
            $url = !$auth_redirect_url ? ecom('url')->prefix().'/' : $auth_redirect_url;
        }


//        if(session('guest') != 1) {
        if(isset($_COOKIE['offlineToken_v2'])){
            \twa\ecomcart\controllers\EcomCartController::offlineToOnline($_COOKIE['offlineToken_v2'], session('login')['id']);
        }
//        }

        session([ 'guest' => false ]);
        if(!$iframe) {
            return redirect($url);
        }
        return view('EcomAuthViews::redirection',[ 'url'=> $url ]);
    }

    public function getChallengeSentTo($challenge , $user){

        $sent_to = [];

        if($challenge->email_sent) { $sent_to [] =  ['icon' => 'envelope' , 'value' => $user->email ]; }
        if($challenge->sms_sent) { $sent_to [] =  ['icon' => 'phone' , 'value' => $user->phone ]; }
        if($challenge->whatsapp_sent) { $sent_to [] =  ['icon' => 'whatsapp' , 'value' => $user->phone ]; }

        return $sent_to;
    }

    public function getCountryCode(){
        $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 $country_code;
    }

    public function checkRecaptcha(){

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

        if(isset($config['force_enable_recaptcha']) && filter_var($config['force_enable_recaptcha'],FILTER_VALIDATE_BOOLEAN )){
            return true;
        }

        $CHALLENGE_SECURITY = fallback(cache('CHALLENGE_SECURITY') , null);
        $CHALLENGE_SECURITY = json_decode($CHALLENGE_SECURITY ,1);
        $min_security_score = isset($config['min_security_score']) ? $config['min_security_score'] : 2;

        if(is_array($CHALLENGE_SECURITY) && isset($CHALLENGE_SECURITY['security_score']) && $CHALLENGE_SECURITY['security_score'] == $min_security_score){
            return true;
        }

        return false;
    }

}
