
/**
 * ajax requests handler
 *
 * object of options contains the url, data to send, headers
 */
const ajax= async (options) => {
    // console.log('options',options)
    try{
        let data=options.data,
            method=options.method?options.method:'post',
            config={
                method: method,
                url: options.url,
                onUploadProgress: function (progressEvent) {

                },
                onDownloadProgress: function (progressEvent) {

                },
            }

        if(options.dataType == 'json'){
            config.headers= {
                accept: 'application/json',
            }
        }

        if(options.method=='get'){
            config.params=data
        }else{
            config.data=data
        }

        if(options.showLoading){
            $('.loading').show();
        }

        $('.loading').removeClass('d-none');

        // console.log('config',config)
        const response= await axios(config);
        if(options.showLoading){
            $('.loading').hide();
        }

        if(response.status==200){
            $('.loading').addClass('d-none');
            return response.data;
        }

        let message=response.data && response.data.message ? response.data.message : 'internetConnectionProblem'
        // alert(message)
        return false;
    } catch ({response: {data}}) {

        // $('.loading').hide();

        console.log('error ',{data})

        toasterError(data.message || 'Request Error');

        $('.loading').addClass('d-none');

        return false;
    }
};


// API
function toasterError(error){
    // alert(error)
    toastr.options.closeButton = true;
    toastr.options.showMethod = 'slideDown';
    toastr.options.hideMethod = 'slideUp';
    toastr.options.closeMethod = 'slideUp';
    toastr.options.closeDuration = 200;
    toastr.options.showDuration = 200;
    toastr.options.preventDuplicates = true;
    toastr.options.progressBar = true;
    toastr.options.positionClass = "toast-top-right";
    toastr.options.newestOnTop = true;
    toastr.options.showEasing = 'swing';
    toastr.options.hideEasing = 'linear';
    toastr.error(error);
}
function toasterSuccess(success){
    toastr.options.closeButton = true;
    toastr.options.showMethod = 'slideDown';
    toastr.options.hideMethod = 'slideUp';
    toastr.options.closeMethod = 'slideUp';
    toastr.options.closeDuration = 200;
    toastr.options.showDuration = 200;
    toastr.options.preventDuplicates = true;
    toastr.options.progressBar = true;
    toastr.options.positionClass = "toast-top-right";
    toastr.options.newestOnTop = true;
    toastr.options.showEasing = 'swing';
    toastr.options.hideEasing = 'linear';
    toastr.success(success);
}

$(document).ready(function() {

    $('.contact_us_button').click(async function (e) {
        e.preventDefault();

        let form = $('.contact_us_form'),
            data = new FormData(form[0]),
            url = form.attr('action'),
            method = form.attr('method');

        const response=await ajax({
            url,
            data,
            dataType: 'json',
            method
        });

        if (response.errors) {
            toasterError(response.errors);
        }
        if (response.message) {
            toasterSuccess(response.message);
            $('.contact_us_form input, textarea').val('');
        }
    });

    /**
     * News Letter Module subscrubtion
     */
    $('.newsletter_form').submit(function(e){
        e.preventDefault();
        $('.newsletter_button').trigger('click')
        return false;
    });

    $('.newsletter_button').click(async function (e) {
        e.preventDefault();

        $(this).prop('disabled', true);

        let interval = setInterval(function () {
            $('.newsletterAjaxError, .newsletterAjaxSuccess').slideUp(400);
            clearInterval(interval)
        }, 3000);

        const  email = $('.newsletter_email');
        if (!email.val()) {
            setTimeout(function(){
                $('.newsletter_button').prop('disabled', false)
            });
            return;
        }
        const data = {email: email.val()},
            form = $('.newsletter_form'),
            url = form.attr('action'),
            method = form.attr('method');

        //
        const response=await ajax({
            url,
            data: data,
            dataType: 'json',
            method
        });
        $(this).prop('disabled', false);

        if (response.errors) {
            toasterError(response.errors);
        }
        if (response.message) {
            toasterSuccess(response.message);
            email.val('');
        }
    });


    /**
     * Book New Package Module subscrubtion
     */
    $('.order_form').submit(function(e){
        e.preventDefault();
        $('.order_button').trigger('click')
        return false;
    })

    $('.order_button').click(async function (e) {
        e.preventDefault();
        //
        $(this).prop('disabled', true)

        const form = $('.order_form'),
            data= form.serialize(),
            url = form.attr('action'),
            method = form.attr('method');
        // console.log({data});
        if (!form.find('[name=title]').val()
            || !form.find('[name=name]').val()
            || !form.find('[name=email]').val()
            || !form.find('[name=phone]').val()
        ) {
            toasterError('!')
            setTimeout(function(){
                $('.order_button').prop('disabled', false)
            }, 500)
            return;
        }
        //
        // console.log({
        //     url,
        //     data: data,
        //     dataType: 'json',
        //     method
        // });
        const response=await ajax({
            url,
            data: data,
            dataType: 'json',
            method
        });
        $(this).prop('disabled', false)

        if (response.message) {
            toasterSuccess(response.message);
            $('.order_form')[0].reset();
            setTimeout(function(){
                $('#book_modal').modal('hide')
            }, 1000);
        }
    });

});
