<script type="text/x-template" id="recovery-form-template">
    <div class="reset-password">
        <div v-show="recovery" class="login-form password-recovery-nr">
            <div class="sign-up-title">
                <span>{{ __('shop::app.customer.forgot-password.title') }}</span>
                <div class="sign-up-exit-img">
                    <img src="{{ bagisto_asset('icons/cancel.svg') }}" alt="exit">
                </div>
            </div>
            <form class="sign-up-content" method="post" @submit.prevent="validateRecoveryForm('recovery')" data-vv-scope="recovery">
                <span class="control-error" v-if="errors.has('recovery.recovery')">@{{ errors.first('recovery.recovery') }}</span>
                <div class="sign-up-input">
                    <span>{{ ucfirst(__('shop::app.customer.account.address.create.phone')) }}</span>
                    <div class="dif-input">
                        <span class="pointer-ev-none">+993</span>
                        <input class="abs-input" type="text" v-model="phone" name="phone" v-validate="'required|numeric|digits:8'"
                               autocomplete="on"
                               data-vv-as="&quot;{{ ucfirst(__('shop::app.customer.account.address.create.phone')) }}&quot;">
                        <span class="control-error" v-if="errors.has('register.phone')">@{{ errors.first('register.phone') }}</span>
                    </div>
                </div> 
                <button type="submit" class="log-in topped sms-trigger" :disabled="disable_button">{{ __('shop::app.customer.forgot-password.submit') }}</button>
            </form>
        </div>
        <div v-show="!recovery" class="login-form password-recovery-sms">
            <div class="sign-up-title">
                <span>{{ __('shop::app.customer.reset-password.title') }}</span>
                <div class="sign-up-exit-img">
                    <img src="{{ bagisto_asset('icons/cancel.svg') }}" alt="exit">
                </div>
            </div>
            <form class="sign-up-content" method="post" @submit.prevent="resetPassword('reset')" data-vv-scope="reset" autocomplete="on">
                <span class="control-error" v-if="errors.has('reset.reset')">@{{ errors.first('reset.reset') }}</span>
                <div class="sign-up-input">
                    <span>{{ __('shop::app.customer.reset-password.token') }}</span>
                    <div class="dif-input">
                        <input type="text" name="token" v-model="code" v-validate="'required|numeric|min:4'">
                        <span class="control-error" v-if="errors.has('reset.token')">@{{ errors.first('reset.token') }}</span>
                    </div>
                </div>
                <div class="sign-up-input">
                    <span>{{ __('shop::app.customer.reset-password.password') }}</span>
                    <div class="dif-input">
                        <input type="password" v-model="password" autocomplete="off" name="password" v-validate="'required|min:6'" ref="password">
                        <span class="control-error" v-if="errors.has('reset.password')">@{{ errors.first('reset.password') }}</span>
                    </div>
                </div>
                <button type="submit" class="log-in topped">{{ __('shop::app.customer.reset-password.submit-btn-title') }}</button>
                <div class="sign-up-footer">
                    <span>{{ __('shop::app.customer.reset-password.no-message') }}</span>
                    <span class="sign-up-btn resend-sms" @click="recovery=true">{{ __('shop::app.customer.reset-password.resend-sms') }}</span>
                </div>
            </form>
        </div>
    </div>

</script>
<script>
    Vue.component('recovery-form-component', {
        template: '#recovery-form-template',

        inject: ['$validator'],

        data: function() {
            return {
                phone: '',
                password: "",
                message: null,
                disable_button: false,
                recovery: true,
                code:'',
                reset_password: true,
            }
        },
        methods: {
            validateRecoveryForm(scope){
                let self = this;

                self.message = null;

                self.disable_button = true;
                this.$validator.validateAll(scope).then(result => {
                    if (result) {
                        axios.post('{{ route('customer.register.recovery') }}', {phone: self.phone})
                            .then(function(response) {
                                // console.log(response.data);
                                self.message = response.data.message;
                                if (response.data.success) {

                                    self.recovery = false;
                                }

                                self.disable_button = false;
                            })
                            .catch(function(error) {
                                self.error_message = error.response.data.message;
                                // self.$setErrorsFromResponse(error.response.data);
                                self.disable_button = false;
                                let errorFields = Object.keys(error.response.data.errors);
                                errorFields.map(field => {
                                    let errorString = error.response.data.errors[field].join(', ');
                                    self.$validator.errors.add({
                                        field:field,
                                        msg: errorString,
                                        scope:scope
                                    });
                                });
                            });
                    } else {
                        self.disable_button = false;
                        eventBus.$emit('onFormError')
                    }
                });
            },
            resetPassword(scope) {
                let self = this;

                self.message = null;
                self.error_message = null;


                self.disable_button = true;

                // Validate the form fields
                this.$validator.validateAll(scope).then(result => {
                    if (result) {
                        // Validation successful, send the request
                        axios.post('{{ route('customer.register.reset_password') }}', {
                            phone: self.phone,
                            token: self.code,
                            password: self.password
                        })
                        .then(function(response) {
                            window.flashMessages = [{'type': 'alert-success', 'message': response.data.message}];
                            self.$root.addFlashMessages();

                            setTimeout(function() {
                                let loginForm = document.querySelector('.login-form');
                                let resetForm = document.querySelector('.reset-password');
                                loginForm.style.display = 'block';
                                resetForm.style.display = 'none';
                                self.reset_password = false;
                            }, 1500);

                            self.disable_button = false;
                        })
                        .catch(function(error) {
                            console.error('Error received:', error.response.data);

                            self.error_message = error.response.data.message;
                            self.disable_button = false;

                            if (error.response.data.errors) {
                                let errorFields = Object.keys(error.response.data.errors);
                                errorFields.map(field => {
                                    let errorString = error.response.data.errors[field].join(', ');
                                    self.$validator.errors.add({
                                        field: field,
                                        msg: errorString,
                                        scope: scope
                                    });
                                });
                            }
                        });
                    } else {
                        // Validation failed
                        self.disable_button = false;

                        // Display validation errors
                        let validationErrors = this.$validator.errors.items.filter(e => e.scope === scope);
                        self.error_message = validationErrors.map(e => e.msg).join(', ');

                        eventBus.$emit('onFormError');
                    }
                }).catch(err => {
                    console.error('Validation error:', err);
                });
            }


        }
    });
</script>