<?php

namespace twa\ecomauth\controllers\v1;

use App\Http\Controllers\Controller;
use Carbon\Carbon;
use twa\apilibs\traits\APITrait;
use twa\ecomauth\controllers\EcomUsersRegistration;
use twa\ecomauth\models\EcomUsersVerificationChallengesModel;

use twa\ecomauth\repositories\AuthenticateRepository;
use twa\ecomauth\repositories\CommonRepository;
use twa\ecomauth\repositories\OTPRepository;

use twa\ecomgeneral\models\EcomUsersModel;
use Validator;

class ProfileController extends Controller
{
    use APITrait;

    public function __construct()
    {
        $this->AuthenticateRepository = new AuthenticateRepository();
        $this->CommonRepository = new CommonRepository();
        $this->OTPRepository = new OTPRepository();
    }


    public function renderCompleteProfile($store, $lang ){
        $user = session('login');
        if (!$user) { return abort("404"); }
        $user = EcomUsersModel::find($user["id"]);
        if (!$user) { return abort("404"); }

        $all_fields = $this->CommonRepository->checkProfileComplete($user);

        $fields = [];
        foreach($all_fields as $field){
            $field['value'] = $user[$field["name"]] ? $user[$field["name"]] : "";
            $fields [] = $field;
        }


        if($user["phone_country_code"]){
            $country_code = $user["phone_country_code"];
        }else{
            $country_code = $this->CommonRepository->getCountryCode();
        }


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


    public function redirectCompleteProfile($store , $lang){

        if(!request()->user){
          return abort(404);
        }
        $completeProfile = $this->requiresCompleteProfile();

        if($completeProfile){
            return view('pages.auth.login' , ['forceCompleteProfile'=> true]);
        }

        return redirect('/'.$store.'/'.$lang);
    }


    public function completeProfile($store , $lang )
    {


        $user = session('login');
        if (!$user) { return abort("404"); }

        $user = $this->AuthenticateRepository->getUserById($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->CommonRepository->getValidations();
        $complete_profile = collect($this->CommonRepository->checkProfileComplete($user))->pluck('name');

        $required = [];

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

        $register_config = [
            'email' => ['verifiy' => 'email_verified'],
            'phone' => ['verifiy' => 'phone_verified']
        ];

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


        $validator = Validator::make(request()->all(), $required , [
                'password.regex' => ___('authentication.password_minimum_capital_letter'),
        ])->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', ___('authentication.valid_phone'));
                }
                $unique_phone = $PhoneValidation['phone'];
                $verification_field = "phone_verified";
                $field_value = ["phone", $PhoneValidation['phone']];
            } elseif ($has_email) {
                $verification_field = "email_verified";
                $field_value = ["email", request()->email];
            }

            if ($field_value) {
                if($field_value[0] == "email"){
                    $user = $this->AuthenticateRepository->getVerifiedUserByEmail($field_value[1]);
                }elseif($field_value[0] == "phone"){
                    $user = $this->AuthenticateRepository->getVerifiedUserByPhone($field_value[1]);
                }

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



        $user = $this->AuthenticateRepository->updateUser($user , request()->all());
// dd(!$verification_strict || $user->verified == 1);


        if($user->verified == 1){
            return $this->CommonRepository->redirectAsLoggedIn();
        }

        $type = null;
        $challenge = null;


        if (request()->has('email')){
            $type = "email";
        }elseif(request()->has('phone')){
            $type = "phone";
        }

        if(!in_array($type , $config['auth_verifications'])){
            return $this->CommonRepository->redirectAsLoggedIn();
        }

        $challenge = $this->OTPRepository->sendChallenge($user, $type);

        if(!$challenge && !is_null($type)){
            return $this->CommonRepository->redirectAsError('limit-exceeded-verifications');
        }

        if($challenge) {
            session(['challenge' => $challenge]);
            return redirect()->route('account-login', ['login_type' => 'otp', 'token' => md5($user['id'] ), "type_slug" => $type]);
        }

       return redirect()->route('redirect-login');
    }


    public function requiresCompleteProfile(){
        $user = session('login');
        if (!$user) { return false; }

        $user = $this->AuthenticateRepository->getUserById($user["id"]);

        if (!$user) { return false; }

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

        if(count($fields) > 0){
            return true;
        }

        return false;

    }




}
