/**
* 2007-2024 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 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:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author    PrestaShop SA <contact@prestashop.com>
*  @copyright 2007-2024 PrestaShop SA
*  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*
* Don't forget to prefix your containers with your own identifier
* to avoid any conflicts with others containers.
*/
var fees_is_hide = false;
$(document).ready(function(){

    if (typeof editCarrier !== 'undefined' && editCarrier == true) {
        carriersRangeInputs.watchCarriersRangeInputChange();
        bind_inputs();
        displayRangeType();
    }

    $('body').on('click', '.js-activate-carrier', async function (event){
        event.preventDefault();

        var requestData = {};

        requestData.active = $(this).data('setctiveto');
        requestData.idCarrierReference = $(this).data('idreference');
        requestData.idSellerInfo = idSellerInfo;

        var result = await request('SetSellerCarrier', requestData);

        if (result.success == true) {
            if (requestData.active == 1) {
                $(this).html('<i class="material-icons btn-outline-success" aria-hidden="true">done</i>');
                $(this).data('setctiveto', 0);
            } else {
                $(this).html('<i class="material-icons btn-outline-danger" aria-hidden="true">close</i>');
                $(this).data('setctiveto', 1);
            }
        } else {
            alert(result.message);
        }
    });

    $('body').on('change', '#field-id_country', shouldDisplayStates);
    shouldDisplayStates();
    $('#field-id_state').closest('.row').hide();
});


async function request(ajaxMethodName, requestData = null) {
    return new Promise(function(resolve, reject) {
        $.ajax({
            type: "POST",
            url: ajaxSellerShippingUrl,
            data: {
                action: ajaxMethodName,
                requestData: requestData,
            },
            dataType: "json",
            crossDomain: true,
            async: true,
            success: function (response) {
                resolve(response);
            },
            error: function (xhr, status, error) {
                if (error) {
                    alert(error);
                } else {
                    alert('Server Error: ' + xhr.status);
                }

                reject(error);
            },
        });
    });
}

function displayRangeType()
{
    if ($('input[name="shipping_method"]:checked').val() == 1)
    {
        string = string_weight;
        $('.weight_unit').show();
        $('.price_unit').hide();
    }
    else
    {
        string = string_price;
        $('.price_unit').show();
        $('.weight_unit').hide();
    }
    is_freeClick($('input[name="is_free"]:checked'));
    $('.range_type').html(string);
}

function add_new_range()
{
    if (!$('tr.fees_all td:last').hasClass('validated'))
    {
        alert(need_to_validate);
        return false;
    }

    last_sup_val = $('tr.range_sup td:last input').val();
    //add new rand sup input
    $('tr.range_sup td:last').after('<td class="range_data"><div class="input-group fixed-width-md"><span class="input-group-addon weight_unit" style="">'+PS_WEIGHT_UNIT+'</span><span class="input-group-addon price_unit" style="">'+currency_sign+'</span><input class="form-control" name="range_sup[]" type="text" autocomplete="off" /></div></td>');
    //add new rand inf input
    $('tr.range_inf td:last').after('<td class="border_bottom"><div class="input-group fixed-width-md"><span class="input-group-addon weight_unit" style="">'+PS_WEIGHT_UNIT+'</span><span class="input-group-addon price_unit" style="">'+currency_sign+'</span><input class="form-control" name="range_inf[]" type="text" value="'+last_sup_val+'" autocomplete="off" /></div></td>');
    $('tr.fees_all td:last').after('<td class="border_top border_bottom"><div class="input-group fixed-width-md"><span class="input-group-addon currency_sign" style="" >'+currency_sign+'</span><input class="form-control" style="" type="text" /></div></td>');

    $('tr.fees').each(function () {
        $(this).find('td:last').after('<td><div class="input-group fixed-width-md"><span class="input-group-addon currency_sign">'+currency_sign+'</span><input class="form-control" disabled="disabled" name="fees['+$(this).data('zoneid')+'][]" type="text" /></div></td>');
    });
    $('tr.delete_range td:last').after('<td><button class="btn btn-default">'+labelDelete+'</button</td>');

    bind_inputs();
    rebuildTabindex();
    displayRangeType();
    return false;
}

function is_freeClick(elt)
{
    var is_free = $(elt);
    if (parseInt(is_free.val()))
        hideFees();
    else if (fees_is_hide)
        showFees();
}

function hideFees()
{
    $('tr.range_inf td, tr.range_sup td, tr.fees_all td, tr.fees td').each(function () {
        if ($(this).index() >= 2)
        {
            $(this).find('input:text, button, .input-group-addon').prop('disabled', true).css('background-color', '#999999').css('border-color', '#999999');
            $(this).css('background-color', '#999999');
        }
    });
    fees_is_hide = true;
}

function showFees()
{
    $('tr.range_inf td, tr.range_sup td, tr.fees_all td, tr.fees td').each(function () {
        if ($(this).index() >= 2)
        {
            //enable only if zone is active
            tr = $(this).closest('tr');
            validate = $('tr.fees_all td:eq('+$(this).index()+')').hasClass('validated');
            if ($(tr).index() > 2 && $(tr).find('td:eq(1) input').prop('checked') && validate || !$(tr).hasClass('range_sup') || !$(tr).hasClass('range_inf')) {
                if($('#is_free_off').prop('checked') === true)
                    $(this).find('div.input-group input:text').prop('disabled', false);
            }
            $(this).find('input:text, button, .input-group-addon').css('background-color', '').css('border-color', '');
            $(this).find('button').css('background-color', '').css('border-color', '').prop('disabled', false);
            $(this).css('background-color', '');
        }
    });
}

function bind_inputs()
{
    $('input').focus(function () {
        $(this).closest('div.input-group').removeClass('has-error');
        $('.form-control-submit').removeAttr('disabled');
        $('.wizard_error').fadeOut('fast', function () { $(this).remove()});
    });

    $('tr.delete_range td button').off('click').on('click', function () {
        if (confirm(delete_range_confirm))
        {
            index = $(this).closest('td').index();
            $('tr.range_sup td:eq('+index+'), tr.range_inf td:eq('+index+'), tr.fees_all td:eq('+index+'), tr.delete_range td:eq('+index+')').remove();
            $('tr.fees').each(function () {
                $(this).find('td:eq('+index+')').remove();
            });
            rebuildTabindex();
        }
        return false;
    });

    $('tr.fees td input:checkbox').off('change').on('change', function ()
    {
        if($(this).is(':checked'))
        {
            $(this).closest('tr').find('td').each(function () {
                index = $(this).index();
                if ($('tr.fees_all td:eq('+index+')').hasClass('validated'))
                {
                    if($('#is_free_off').prop('checked') === true) {
                        enableGlobalFees(index);
                        $(this).find('div.input-group input:text').prop('disabled', false);
                    }
                }
                else
                    disabledGlobalFees(index);
            });
        }
        else
            $(this).closest('tr').find('td').find('div.input-group input:text').prop('disabled', true);

        return false;
    });

    $('tr.range_sup td input:text, tr.range_inf td input:text').keypress(function (evn) {
        index = $(this).closest('td').index();
        if (evn.keyCode == 13)
        {
            if (validateRange(index))
                enableRange(index);
            else
                disableRange(index);
            return false;
        }
    });

    $('tr.fees_all td input:text').keypress(function (evn) {
        index = $(this).parent('td').index();
        if (evn.keyCode == 13)
            return false;
    });

    $(document.body).off('change', 'tr.fees_all td input').on('change', 'tr.fees_all td input', function() {
        index = $(this).closest('td').index();
        val = $(this).val();
        $(this).val('');
        $('tr.fees').each(function () {
            $(this).find('td:eq('+index+') input:text:enabled').val(val);
        });

        return false;
    });

    $('input[name="is_free"]').off('click').on('click', function() {
        is_freeClick(this);
    });

    $('input[name="shipping_method"]').off('click').on('click', async function() {
        var requestData = {};
        requestData.idCarrierReference = idCarrierReference;
        requestData.shipping_method = parseInt($(this).val());
        var result = await request('GetTableRanges', requestData);

        if (result.success == true) {
            $('#zone_ranges').replaceWith(result.data);
            displayRangeType();
            bind_inputs();
        } else {
            alert(result.message);
        }
    });

    $('#zones_table td input[type=text]').off('change').on('change', function () {
        checkAllFieldIsNumeric();
    });
}

function rebuildTabindex()
{
    i = 1;
    $('#zones_table tr').each(function ()
    {
        j = i;
        $(this).find('td').each(function ()
        {
            j = zones_nbr + j;
            if ($(this).index() >= 2 && $(this).find('div.input-group input'))
                $(this).find('div.input-group input').attr('tabindex', j);
        });
        i++;
    });
}

function checkAllZones(elt)
{
    if($(elt).is(':checked'))
    {
        $('.input_zone').prop('checked', true);
        $('.fees div.input-group input:text').each(function () {
            index = $(this).closest('td').index();
            enableGlobalFees(index);
            if ($('tr.fees_all td:eq('+index+')').hasClass('validated') && $('#is_free_off').prop('checked') === true)
            {
                $(this).prop('disabled', false);
                $('.fees_all td:eq('+index+') div.input-group input:text').prop('disabled', false);
            }
        });
    }
    else
    {
        $('.input_zone').prop('checked', false);
        $('.fees div.input-group input:text, .fees_all div.input-group input:text').prop('disabled', true);
    }

}

function enableGlobalFees(index)
{
    if($('#is_free_off').prop('checked') === true) {
        $('span.fees_all').show();
        $('tr.fees_all td:eq('+index+')').find('div.input-group input').show().prop('disabled', false);
        $('tr.fees_all td:eq('+index+')').find('div.input-group .currency_sign').show();
    }
}

function checkAllFieldIsNumeric()
{
    $('.form-control-submit').removeAttr('disabled');
    $('#zones_table td input[type=text]').each(function () {
        if (!$.isNumeric($(this).val()) && $(this).val() != '') {
            $('.form-control-submit').attr("disabled", "disabled");
            $(this).closest('div.input-group').addClass('has-error');
        }

    });
}

var carriersRangeInputs = {
    /** Check the carriers range inputs after each change */
    watchCarriersRangeInputChange: function() {
        var $document = $(document);
        var inputs = 'tr.range_sup td input:text, tr.range_inf td input:text';

        $document.on('focus', inputs, function() {
            $(this).closest('div.input-group').removeClass('has-error');
            $(this).typeWatch({
                captureLength: 0,
                highlight: false,
                wait: 1000,
                callback: function() {
                    var index = $(this.el).closest('td').index();
                    var rangeSup = $('tr.range_sup td:eq(' + index + ')').find('div.input-group input:text').val().trim();
                    var rangeInf = $('tr.range_inf td:eq(' + index + ')').find('div.input-group input:text').val().trim();
                    if (rangeSup !== '' && rangeInf !== '') {
                        carriersRangeInputs.checkCarriersRangeValidation(index);
                    }
                }
            });
        });

        $document.on('blur', inputs, function() {
            var $this = $(this);
            $this.off();
            var index = $this.closest('td').index();
            var hasError = $('tr.range_sup td:eq(' + index + ') .has-error, tr.range_inf td:eq(' + index + ') .has-error');

            if ($('.wizard_error').length === 0 || hasError.length !== 0) {
                carriersRangeInputs.checkCarriersRangeValidation(index);
            }
        });
    },
    /**
     * Check range validation
     * @param {number} index
     */
    checkCarriersRangeValidation: function(index) {
        if (validateRange(index)) {
            enableRange(index);
        } else {
            disableRange(index);
        }
    }
};

function validateRange(index)
{
    $('.form-control-submit').removeAttr('disabled');
    $('.wizard_error').remove();

    var isValid = true;
    var $currentRangeSup = $('tr.range_sup td:eq(' + index + ')').find('div.input-group input:text');
    var $currentRangeInf = $('tr.range_inf td:eq(' + index + ')').find('div.input-group input:text');
    var rangeSup = parseFloat($currentRangeSup.val().trim());
    var rangeInf = parseFloat($currentRangeInf.val().trim());

    //reset css error
    $currentRangeSup.closest('div.input-group').removeClass('has-error');
    $currentRangeInf.closest('div.input-group').removeClass('has-error');

    if (isNaN(rangeSup) || rangeSup.length === 0) {
        $currentRangeSup.closest('div.input-group').addClass('has-error');
        isValid = false;
        //displayError([invalid_range], $("#carrier_wizard").smartWizard('currentStep'));
        displayError([invalid_range], undefined);
    } else if (isValid && (isNaN(rangeInf) || rangeInf.length === 0)) {
        $currentRangeInf.closest('div.input-group').addClass('has-error');
        isValid = false;
        //displayError([invalid_range], $("#carrier_wizard").smartWizard('currentStep'));
        displayError([invalid_range], undefined);
    } else if (isValid && rangeInf >= rangeSup) {
        $currentRangeSup.closest('div.input-group').addClass('has-error');
        $currentRangeInf.closest('div.input-group').addClass('has-error');
        isValid = false;
        //displayError([invalid_range], $("#carrier_wizard").smartWizard('currentStep'));
        displayError([invalid_range], undefined);
    } else if (isValid && (index > 2 || $('tr.range_sup td').not('.range_type, .range_sign').length > 1)) { //check range only if it's not the first range
        isValid = !isOverlapping();

        if (!isValid) {
            $currentRangeSup.closest('div.input-group').addClass('has-error');
            $currentRangeInf.closest('div.input-group').addClass('has-error');
            //displayError([range_is_overlapping], $("#carrier_wizard").smartWizard('currentStep'));
            displayError([range_is_overlapping], undefined);
        }
    }

    if (isValid) {
        $('tr.range_sup td').not('.range_type, .range_sign').each( function () {
            var $this = $(this);
            var currentIndex = $this.index();
            if ($this.find('.has-error').length > 0 && currentIndex !== index) {
                isValid = validateRange(currentIndex);
                if (isValid) {
                    enableRange(currentIndex);
                }
            }
        });
    }

    isValid = !$currentRangeSup.closest('div.input-group').hasClass('has-error');

    return isValid;
}

function isOverlapping()
{
    var isValid = false;
    $('.form-control-submit').removeAttr('disabled');
    $('tr.range_sup td').not('.range_type, .range_sign').each(function() {
        var index = $(this).index();
        var currentInf = parseFloat($('.range_inf td:eq(' + index + ') input').val());
        var currentSup = parseFloat($('.range_sup td:eq(' + index + ') input').val());

        $('tr.range_sup td').not('.range_type, .range_sign').each(function() {
            var testingIndex = $(this).index();

            if (testingIndex !== index && testingIndex >= (index - 1)) { //do not test himself
                var testingInf = parseFloat($('.range_inf td:eq(' + testingIndex + ') input').val());
                var testingSup = parseFloat($('.range_sup td:eq(' + testingIndex + ') input').val());
                var checkOverLapping = (index < testingIndex) ?
                    (currentInf >= testingInf || currentInf >= testingSup || currentSup > testingInf || currentSup >= testingSup)
                    : (currentInf <= testingInf || currentInf < testingSup || currentSup <= testingInf || currentSup <= testingSup);

                if (checkOverLapping) {
                    $('tr.range_sup td:eq(' + testingIndex + ') div.input-group, tr.range_inf td:eq(' + testingIndex + ') div.input-group').addClass('has-error');
                    disableRange(testingIndex);
                    //displayError([overlapping_range], $("#carrier_wizard").smartWizard('currentStep'));
                    displayError([overlapping_range], undefined);
                    isValid = true;
                }
            }
        });
    });

    return isValid;
}

function enableRange(index)
{
    $('tr.fees').each(function () {
        //only enable fees for enabled zones
        if ($(this).find('td').find('input:checkbox').prop('checked') && $('#is_free_off').prop('checked') === true)
            enableZone(index);
    });
    $('tr.fees_all td:eq('+index+')').addClass('validated').removeClass('not_validated');

    enableGlobalFees(index);
    bind_inputs();
}

function enableZone(index)
{
    if($('#is_free_off').prop('checked') === true) {
        $('tr.fees').each(function () {
            if ($(this).find('td:eq(1)').find('input[type=checkbox]:checked').length)
                $(this).find('td:eq('+index+')').find('div.input-group input').prop('disabled', false);
        });
    }
}

function displayError(errors, step_number)
{
    $('.form-control-submit').removeAttr('disabled');
    $('.wizard_error').remove();
    str_error = '<div class="alert alert-danger wizard_error mb-0" style="display:none"><ul class="mb-0">';
    for (var error in errors)
    {
        $('.form-control-submit').attr("disabled", "disabled");
        $('input[name="'+error+'"]').closest('div.input-group').addClass('has-error');
        str_error += '<li>'+errors[error]+'</li>';
    }
    $('#alert-container').prepend(str_error+'</ul></div>');
    $('.wizard_error').fadeIn('fast');
    bind_inputs();
}

function disableRange(index)
{
    $('tr.fees').each(function () {
        //only enable fees for enabled zones
        if ($(this).find('td').find('input:checkbox').prop('checked'))
            disableZone(index);
    });
    $('tr.fees_all td:eq('+index+')').find('div.input-group input').prop('disabled', true);
    $('tr.fees_all td:eq('+index+')').removeClass('validated').addClass('not_validated');
}

function disableZone(index)
{
    $('tr.fees').each(function () {
        $(this).find('td:eq(' + index + ')').find('div.input-group input').prop('disabled', true);
    });
}

function disabledGlobalFees(index)
{
    $('span.fees_all').hide();
    $('tr.fees_all td:eq('+index+')').find('div.input-group input').hide().prop('disabled', true);
    $('tr.fees_all td:eq('+index+')').find('div.input-group .currency_sign').hide();
}

function deleteLocation(href) {
    if (confirm(delete_location)) {
        location.href = href;
    } else {
        event.stopPropagation();
        event.preventDefault();
    }
}

async function shouldDisplayStates(){

    if ($('#field-id_country').length == 0 || $('#field-id_country').val() == null) {
        return;
    }

    var requestData = {};
    requestData.id_country = $('#field-id_country').val();

    var result = await request('GetLocationStates', requestData);

    if (result.success) {
        if (result.displayState) {
            $('#field-id_state').closest('.row').show();
            $('#field-id_state').find('options').remove();
            $.each(result.states, function () {
                if (idSelectedCountry == requestData.id_country && this.id_state == idSelectedState) {
                    $('#field-id_state').append($("<option />").val(this.id_state).text(this.name).attr('selected', true));
                }else{
                    $('#field-id_state').append($("<option />").val(this.id_state).text(this.name));
                }
            });

        }else{
            $('#field-id_state').closest('.row').hide();
            $('#field-id_state').val(0);
        }
    }else{
        $('#field-id_state').closest('.row').hide();
        alert(result.message);
    }

}
