{% extends "@UVDeskSupportCenter/Templates/layout.html.twig" %}

{% block title %}{{ 'Customer Login'|trans }}{% endblock %}
{% block ogtitle %}{{ 'Customer Login'|trans }}{% endblock %}
{% block twtitle %}{{ 'Customer Login'|trans }}{% endblock %}
{% block metaDescription %}{% trans %}customer.login.metaDescription{% endtrans %}{% endblock %}
{% block metaKeywords %}{% trans %}customer.login.metaKeywords{% endtrans %}{% endblock %}

{% set recaptchaDetail = recaptcha_service.getRecaptchaDetails() %}

{% block body %}
    <style>
        .uv-login-form-actions, .uv-login-form-inline-actions {
            list-style: none;
        }
        .uv-paper-article .uv-paper-section ul {
            padding: unset !important;
        }
    </style>
    <div class="uv-paper-article uv-paper-form">
        <div class="uv-paper-section">
            <section>
                <h1>{{ 'Sign In to %websitename%'|trans({ '%websitename%': '<span class="uv-brand">' ~ websiteDetails.name|e ~ '</span>' })|raw }}</h1>
                <div class="uv-element-block">
                    <p>{{ 'If you have ever contacted our support previously, your account would have already been created.'|trans }}</p>
                </div>


                <div id="login-form-container" class="login-form-container">
                    <form action="{{ path('helpdesk_customer_login')}}" method="post" id="login-form" class="login-form"></form>
                </div>

                <div style="margin-top:20px">
                    {% if recaptchaDetail and recaptchaDetail.isActive == true %}
                        <div class="clearfix"></div>
                        <div class="g-recaptcha" data-sitekey="{{ recaptchaDetail.siteKey }}"></div>
                        <div class="clearfix"></div>
                    {% else %}
                            <!-- Recaptcha will not support -->
                    {% endif %}
                </div>
            </section>
        </div>
    </div>
{% endblock %}

{% block footer %}
    {{ parent() }}
    {% if recaptchaDetail and recaptchaDetail.isActive == true %}
        <script src='https://www.google.com/recaptcha/api.js'></script>
    {% endif %}

    <script id="customer-login-form-base-credentials-template" type="text/template">
        {{ include('@UVDeskSupportCenter/CustomerLogin/customer-login-form-base-credentials-template.html.twig') }}
    </script>

    <script id="customer-login-form-otp-credentials-template" type="text/template">
        {{ include('@UVDeskSupportCenter/CustomerLogin/customer-login-form-otp-credentials-template.html.twig') }}
    </script>

    <script id="customer-login-form-original-credentials-template" type="text/template">
        {{ include('@UVDeskSupportCenter/CustomerLogin/customer-login-form-original-credentials-template.html.twig') }}
    </script>

    <script type="text/javascript">
        _.extend(Backbone.Model.prototype, Backbone.Validation.mixin);
        
        $(function () {
            let BaseCredentialsModel = Backbone.Model.extend({
                defaults: {
                    _username: null, 
                }, 
                validation: {
                    _username: [{
                        required: true, 
                        msg: 'Please enter a valid email address'
                    }, {
                        pattern: 'email', 
                        msg: 'Please enter a valid email address'
                    }]
                },
            });

            let OtpCredentialsModel = Backbone.Model.extend({
                defaults: { 
                    _username: null, 
                    otp: null, 
                }, 
                validation: {
                    _username: [{
                        required: true, 
                        msg: 'Please enter a valid email address'
                    }, {
                        pattern: 'email', 
                        msg: 'Please enter a valid email address'
                    }], 
                    otp: [{
                        required: true,
                        msg: '{{ "This field is mandatory"|trans }}'
                    }]
                }
            });

            let OriginalCredentialsModel = Backbone.Model.extend({
                defaults: { 
                    _username: null, 
                    _password: null, 
                }, 
                validation: {
                    _username: [{
                        required: true, 
                        msg: 'Please enter a valid email address'
                    }, {
                        pattern: 'email', 
                        msg: 'Please enter a valid email address'
                    }], 
                    _password: [{
                        required: true,
                        msg: '{{ "This field is mandatory"|trans }}'
                    }, {
                        minLength: 8,
                        msg: '{{ "Password must contains 8 Characters"|trans }}'
                    }]
                }
            });

            let LoginForm = Backbone.View.extend({
                baseLoginFormTemplate: _.template($('#customer-login-form-base-credentials-template').html()), 
                otpLoginFormTemplate: _.template($('#customer-login-form-otp-credentials-template').html()), 
                originalLoginFormTemplate: _.template($('#customer-login-form-original-credentials-template').html()), 
                events: {
                    'submit .login-form': 'submitForm', 
                    'click .uv-continue-with-pass': 'switchToOriginalCredentialsForm',
                    'blur input': 'formChanged',
                    'click #uv-resend-otp': 'resendOTP'
                },
                initialize: function () {
                    Backbone.Validation.bind(this);
                    
                    this.formEl = $('#login-form');
                    this.render();
                },
                formChanged: function(e) {
                    this.model.set(Backbone.$(e.currentTarget).attr('name'), Backbone.$(e.currentTarget).val())
                    this.model.isValid([Backbone.$(e.currentTarget).attr('name')])
                },
                render: function() {
                    if (typeof(this.model) != undefined && this.model != null) {
                        if (this.model instanceof BaseCredentialsModel) {
                            this.formEl.html(this.baseLoginFormTemplate(this.model.attributes));
                        } else if (this.model instanceof OtpCredentialsModel) {
                            this.formEl.html(this.otpLoginFormTemplate(this.model.attributes));
                        } else if (this.model instanceof OriginalCredentialsModel) {
                            this.formEl.html(this.originalLoginFormTemplate(this.model.attributes));
                        }
                    }
                }, 
                submitForm: function(e) {
                    let _this = this;
                    let formData = this.formEl.serializeArray();

                    formData.forEach(function (element) {
                        _this.model.set(element.name, element.value);
                    });

                    if (this.model.isValid(true)) {
                        if (this.model instanceof BaseCredentialsModel) {
                            e.preventDefault();
                            
                            $('#email-submit').attr('disabled', 'disabled');
                            
                            $.ajax({
                                url: "{{ path('helpdesk_member_knowledgebase_front_customer_login_otp_generate') }}",
                                type: 'POST',
                                data: this.model.attributes,
                                dataType: 'json',
                                success: function(response) {
                                    app.appView.renderResponseAlert({
                                        alertClass: response.success ? 'success' : 'danger',
                                        alertMessage: response.message
                                    });
                                
                                    _this.model = new OtpCredentialsModel(_this.model.attributes);

                                    Backbone.Validation.bind(_this);

                                    _this.render();
                                },
                                error: function (xhr) {
                                    $('#email-submit').removeAttr('disabled', 'disabled');
                                    
                                    let errorMessage = typeof(xhr.responseJSON.message) != undefined && xhr.responseJSON.message != null ? xhr.responseJSON.message : 'An unexpected error occurred. Please try again later.';
                                    
                                    app.appView.renderResponseAlert({
                                        alertClass: 'danger',
                                        alertMessage: errorMessage
                                    });
                                }
                            });
                        } else if (this.model instanceof OtpCredentialsModel) {
                            e.preventDefault();

                            $('#uv-resend-otp').removeAttr("disabled");

                            let formData = this.formEl.serializeObject();

                            $.ajax({
                                url: "{{ path('helpdesk_member_knowledgebase_front_customer_verify_otp_login') }}",
                                type: 'POST',
                                data: formData,
                                dataType: 'json',
                                success: function(response) {
                                    console.log(response);
                                    if (response.success) {
                                        window.location.href = "{{ path('helpdesk_customer_ticket_collection') }}";
                                    } else {
                                        app.appView.renderResponseAlert({
                                            alertClass: 'danger',
                                            alertMessage: response.message
                                        });
                                    }
                                },
                                error: function (xhr) {
                                    let errorMessage = typeof(xhr.responseJSON.message) != undefined && xhr.responseJSON.message != null ? xhr.responseJSON.message : 'An unexpected error occurred while verify credentials. Please try again later.';

                                    app.appView.renderResponseAlert({
                                        alertClass: 'danger',
                                        alertMessage: errorMessage
                                    });
                                }
                            });
                        }
                    } else {
                        e.preventDefault();
                    }
                }, 
                resendOTP: function(e){
                    e.preventDefault();
                   
                    let formData = this.formEl.serializeObject();
                    formData.resendKey = 'resendOtp';
                    var self = this;

                    $.ajax({
                        url: "{{ path('helpdesk_member_knowledgebase_front_customer_login_otp_generate') }}",
                        type: 'POST',
                        data: formData,
                        dataType: 'json',
                        success: function(response) {
                            app.appView.renderResponseAlert({
                                alertClass: response.success ? 'success' : 'danger',
                                alertMessage: response.message
                            });
                        },
                        error: function (xhr) {
                            let errorMessage = typeof(xhr.responseJSON.message) != undefined && xhr.responseJSON.message != null ? xhr.responseJSON.message : 'An unexpected error occurred while processing this request. Please try again later.';

                            app.appView.renderResponseAlert({
                                alertClass: 'danger',
                                alertMessage: errorMessage
                            });
                        }
                    });
                },
                switchToOriginalCredentialsForm: function(e) {
                    e.preventDefault();
                    
                    this.model = new OriginalCredentialsModel(this.model.attributes);
                    Backbone.Validation.bind(this);
                    
                    this.render();
                }
            });

            let loginForm = new LoginForm({
                el: $('#login-form-container'), 
                model: new BaseCredentialsModel()
            });
        });
    </script>
{% endblock %}