/**
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.txt
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this module to a newer
* versions in the future. If you wish to customize this module for your needs
* please refer to CustomizationPolicy.txt file inside our module for more information.
*
* @author Webkul IN
* @copyright Since 2010 Webkul
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/

$(document).ready(function() {
    if (prestashop.page.page_name == 'product') {
        if (typeof wkPayPalInstalled != 'undefined' && wkPayPalInstalled) {
            if ($('.wk-subscription-block').length) {
                let ppblock = $('.wk-subscription-block').siblings('.wkstripe_subscribe');
                ppblock.prev('.alert').remove();
                ppblock.remove();
            }
        }
    }
    if (prestashop.page.page_name == 'product') {
        if (typeof wkWepayInstalled != 'undefined' && wkWepayInstalled) {
            if ($('.wk-subscription-block').length) {
                let wepayAlert = $('.wk-subscription-block').siblings('.alert');
                wepayAlert.remove();
            }
        }
    }
    prestashop.on(
        'updateCart',
        function(event) {
            if (typeof event.resp != 'undefined') {
                var response = event.resp;
                if (response.success && $('#wk_subscription_subscribe').is(':checked')) {
                    var subFreq = $('#wkSubscriptionFrequency').find(':selected').val();
                    var subFirstDel = $('#wkFirstDeliveryDate').val();
                    var idSubTemp = $('#id_sub_temp').val();
                    $.ajax({
                        url : wkProdSubsAjaxLink,
                        cache : false,
                        async: false,
                        type: 'POST',
                        dataType: 'json',
                        data : {
                            ajax: true,
                            action: 'addSubscribe',
                            wkSubToken: wkProdSubToken,
                            id_product : response.id_product,
                            id_product_attribute : response.id_product_attribute,
                            id_customization: response.id_customization,
                            frequency: subFreq,
                            delivery_date: subFirstDel,
                            id_sub_temp: idSubTemp,
                            is_subscribe : $('input[name=subscription_plan]:checked').val()
                        },
                        success : function (data) {
                            if (data) {
                                console.log(data);
                            }
                        }
                    });
                }
            }
        }
    );

    prestashop.on(
        'updatedProduct',
        function () {
            $('.wkdatepicker').datepicker({
                minDate: "+"+wkOrderDays+"d",
                maxDate: "+"+parseInt(wkOrderDays + 6)+"d",
                dateFormat: 'yy-mm-dd'
            });
       }
    );

    prestashop.on(
        'clickQuickView',
        function(event) {
            // Check if Ajax completed
            $(document).ajaxStop(function() {
                // Remove subscription button from quick view popup
                setTimeout(() => {
                    if ((wk_subscribe_show_modal_btn == 0)) {
                        $('div.quickview').find('.wk-subscription-block').remove();
                    }
                    $('.wkdatepicker').datepicker({
                        minDate: "+"+wkOrderDays+"d",
                        maxDate: "+"+parseInt(wkOrderDays + 6)+"d",
                        dateFormat: 'yy-mm-dd'
                    });
                }, 100);
            });
        }
    );

    // Date picker
    $('.wkdatepicker').datepicker({
        minDate: "+"+wkOrderDays+"d",
        maxDate: "+"+parseInt(wkOrderDays + 6)+"d",
        dateFormat: 'yy-mm-dd'
    });

    $(document).on('change', '#wk_subscription_subscribe', function() {
        if ($(this).is(':checked')) {
            $('.wksubscription-options').slideDown();
            if ($('#id_sub_temp').val()) {
                var subFreq = $('#wkSubscriptionFrequency').find(':selected').val();
                var subFirstDel = $('#wkFirstDeliveryDate').val();
                var idSubTemp = $('#id_sub_temp').val();
                updateSubsTempCart(idSubTemp, subFreq, subFirstDel, 1);
            }
        }
    });

    $(document).on('change', '#wk_subscription_one_time', function() {
        if ($(this).is(':checked')) {
            $('.wksubscription-options').slideUp();
            if ($('#id_sub_temp').val()) {
                var subFreq = $('#wkSubscriptionFrequency').find(':selected').val();
                var subFirstDel = $('#wkFirstDeliveryDate').val();
                var idSubTemp = $('#id_sub_temp').val();
                updateSubsTempCart(idSubTemp, subFreq, subFirstDel, 0);
            }
        }
    });

    $(document).on('change', '.wkUpdateTempCart', function() {
        $('.wk-subs-error-msg').html('');
        $('.wk-subs-success-msg').html('');
        var subFreq = $('#wkSubscriptionFrequency').find(':selected').val();
        var subFirstDel = $('#wkFirstDeliveryDate').val();
        var idSubTemp = $('#id_sub_temp').val();

        if (idSubTemp && subFreq && subFirstDel && $('#wk_subscription_subscribe').is(':checked')) {
            updateSubsTempCart(idSubTemp, subFreq, subFirstDel, 1);
        }
    });

    $(document).on('click', '[data-link-action="wk-subscribe-remove-from-cart"]', function(e) {
        e.preventDefault();
        if (confirm(wkSubCartConf)) {
            $.ajax({
                url : wkProdSubsAjaxLink,
                cache : false,
                async: false,
                type: 'POST',
                data : {
                    ajax: true,
                    action: 'removeSubscribe',
                    wkSubToken: wkProdSubToken,
                    id_product : $(this).attr('data-id-product'),
                    id_product_attribute : $(this).attr('data-id-product-attribute'),
                },
                success : function (data) {
                    window.location.reload(true);
                }
            });
        } else {
            return false;
        }
    });

    $(document).on('click', '[data-link-action="wk-subscribe-update-cart"]', function(e) {
        e.preventDefault();
        $('body').find('#wkSubscriptionModal').remove();
        $.ajax({
            url : wkProdSubsAjaxLink,
            cache : false,
            async: false,
            dataType: 'json',
            type: 'POST',
            data : {
                ajax: true,
                action: 'getSubscribe',
                wkSubToken: wkProdSubToken,
                id_product : $(this).attr('data-id-product'),
                id_product_attribute : $(this).attr('data-id-product-attribute'),
            },
            success : function (result) {
                if (result.success == 1) {
                    $('body').append(result.popup);
                    $('#wkSubscriptionModal').modal('show');
                    setTimeout(() => {
                        $('.wkdatepicker').datepicker({
                            minDate: "+"+wkOrderDays+"d",
                            maxDate: "+"+parseInt(wkOrderDays + 6)+"d",
                            dateFormat: 'yy-mm-dd'
                        });
                    }, 100);
                }
            }
        });
    });
});

function updateSubsTempCart(idSubTemp, subFreq, subFirstDel, is_subscribe) {
    if (idSubTemp > 0) {
        $.ajax({
            url : wkProdSubsAjaxLink,
            cache : false,
            async: false,
            type: 'POST',
            data : {
                ajax: true,
                action: 'updateSubscribe',
                wkSubToken: wkProdSubToken,
                frequency: subFreq,
                delivery_date: subFirstDel,
                id_sub_temp: idSubTemp,
                is_subscribe : is_subscribe
            },
            success : function (data) {
                if (data > 0) {
                    $('.wk-subs-success-msg').html(wkSubCartUpdate).show();
                    setTimeout(() => {
                        window.location.reload();
                    }, 1000);
                }
            }
        });
    }
}

function wkTriggerUpdate() {
    var subFreq = $('#wkSubscriptionFrequency').find(':selected').val();
    var subFirstDel = $('#wkFirstDeliveryDate').val();
    var idSubTemp = $('#id_sub_temp').val();

    if (idSubTemp && subFreq && subFirstDel) {
        updateSubsTempCart(idSubTemp, subFreq, subFirstDel, 1);
    }
}
