// -----------> ajax jQuery
$(function() {

// flexslider
if ($('.flexslider-thumbnails').length) {
    $('.flexslider-thumbnails').flexslider({
        animation: "slide",
        controlNav: "thumbnails",
        autoplay: false,
    });
}

var form = $('#contact-form'),
    message = $('.contact__msg'),
    form_data; // Success function

var form_s = $('#subscribe-form'),
    message = $('.contact__msg'),
    form_data; // Success function

function done_func() {

    let lang = $('html').attr('lang');
    if(lang == 'hy')
    { message = 'Հաղորդագրությունը հաջողությամբ ուղարկվել է', info = 'Շնորհակալություն', button = 'Փակել'}
    else if(lang == 'ru')
    { message = 'Сообщение было успешно отправлено', info = 'Спасибо',  button = 'Закрыть' }
    else if(lang == 'en')
    { message = 'The message was sent successfully', info = 'Thanks', button = 'Close' }

Swal.fire({
    icon: 'success',
    title: info,
    text: message,
    confirmButtonText: button,
    })
form.find('button:not([type="submit"]), textarea').val('');
$("#contact-form")[0].reset();
} // fail function

function done_func_subscribe() {
    let lang = $('html').attr('lang');
    if(lang == 'hy')
    { message = 'Դուք հաջողությամբ բաժանորդագրվել եք', info = 'Շնորհակալություն', button = 'Փակել'}
    else if(lang == 'ru')
    { message = 'Вы успешно подписались', info = 'Спасибо',  button = 'Закрыть' }
    else if(lang == 'en')
    { message = 'You have successfully subscribed', info = 'Thanks', button = 'Close' }
    Swal.fire({
        icon: 'success',
        title: info,
        text: message,
        confirmButtonText: button,
        })
    $("#subscribe-form")[0].reset();
} // fail function

function fail_func() {
let lang = $('html').attr('lang');
if(lang == 'hy')
{ message = 'Լրացրեք պարտադիր լրացման դաշտերը', info = 'Ուշադրություն' , button = 'Փակել'}
else if(lang == 'ru')
{ message = 'Пожалуйста, заполните обязательные поля', info = 'Внимание', button = 'Закрыть'}
else if(lang == 'en')
{ message = 'Please fill in the required fields', info = 'Oops', button = 'Close' }
Swal.fire({
    icon: 'error',
    title: info,
    text: message,
    confirmButtonText: button,
    })
}

form.submit(function (e) {
    e.preventDefault();
    form_data = $(this).serialize();
    $.ajax({
      type: 'POST',
      url: form.attr('action'),
      data: form_data
    }).done(done_func).fail(fail_func);
  });

  form_s.submit(function (e) {
    e.preventDefault();
    form_data = $(this).serialize();
    $.ajax({
      type: 'POST',
      url: form_s.attr('action'),
      data: form_data
    }).done(done_func_subscribe).fail(fail_func);
  });

});


//filters

// Filter Project
function getIds(checkboxName) {
    let checkBoxes = document.getElementsByName(checkboxName);
    let ids = Array.prototype.slice
        .call(checkBoxes)
        .filter(ch => ch.checked == true)
        .map(ch => ch.value);
    return ids;
}

$(function () {

    let minprice = parseFloat($('#min-price-filter').val());
    let maxprice = $('#max-price-filter').val();
    let filtermaxprice = $('#filter-max-price').val();
    let maxcurrency = $('#currency-price-filter').val();
     $('#slider-container').slider({

             range: true,
             min: 0,
             max: maxprice,
             step: 5,
             values: [minprice, filtermaxprice],
             create: function() {
                 $("#amount").val(minprice + maxcurrency + '- ' + filtermaxprice + maxcurrency);
             },
             slide: function (event, ui) {
                 $("#amount").val(ui.values[0] + maxcurrency + "- " + ui.values[1] + maxcurrency);
             },
             change: function (event, ui) {
                 var mi = ui.values[0];
                 var mx = ui.values[1];
                 filterResults(mi, mx);
             }
         })
     });

     $('.products-sort').click(function () {
        if($(this).hasClass('active')) {
            $(this).removeClass("active");
            $('.products-sort').removeClass("active");
        } else {
            $('.products-sort').removeClass("active");
            $(this).addClass("active");
        }
    });

function filterResults(minPrice, maxPrice) {
    let filterlanguage = $('#filterlanguage').val();
    let catsSlug = $('#catsSlug').val();
    let subcatSlug = $('#subcatSlug').val();
    // let minprice = minPrice;
    // let maxprice = maxPrice;
    let minprice = parseFloat($('#min-price-filter').val());
    let maxprice = parseFloat($('#max-price-filter').val());
    let orderprice = $('.products-sort.active').data('name');
    console.log(orderprice);

        let categoryIds = getIds("category");
        let stoneIds = getIds("stone");
        let metalIds = getIds("metal");
        let whomIds = getIds("whom");
        let standardIds = getIds("standard");
        let foodIds = getIds("food");
        let otherIds = getIds("other");

        let filterurlloc = window.location.pathname
        let filterurlorigin= window.location.origin

        if(subcatSlug != null) {
            var href = filterurlorigin+'/'+filterlanguage+'/'+catsSlug+'/'+subcatSlug+'?';
        } else {
            if(catsSlug != null) {
                var href = filterurlorigin+'/'+filterlanguage+'/'+catsSlug+'?';
            } else {
                var href = filterurlorigin+'/'+filterlanguage+'/shop?';
            }
        }

        if (categoryIds.length) {
            href += "filter[category]=" + categoryIds;
        }
        if (stoneIds.length) {
            href += "&filter[stone]=" + stoneIds;
        }
        if (metalIds.length) {
            href += "&filter[metal]=" + metalIds;
        }
        if (whomIds.length) {
            href += "&filter[whom]=" + whomIds;
        }
        if (standardIds.length) {
            href += "&filterstandard]=" + standardIds;
        }
        if (foodIds.length) {
            href += "&filter[food]=" + foodIds;
        }
        if (otherIds.length) {
            href += "&filter[other]=" + otherIds;
        }
        if(typeof minprice == "number") {
            href += "&filter[min-price]=" + minprice;
        }
        if(typeof maxprice == "number") {
            href += "&filter[max-price]=" + maxprice;
        }
        if(orderprice != undefined) {
            if (orderprice.length) {
                href += "&sort=" + orderprice;
            }
        }

        document.location.href = href;
    }

    $("#filter").on("click", filterResults);

    // $(".chk-filter").on("change", function() {
    //     if (this.checked) {
    //         $('#filter').click();
    //     } else {
    //         $('#filter').click();
    //     }
    // });

    // $(".category").on("change", function() {
    //     if (this.checked) {
    //         $('#filter').click();
    //     } else {
    //         $('#filter').click();
    //     }
    // });

    // $("select[name='productprice']").on('change', function() {
    //     let productId =  $(this).data("id");
    //     let productPrice =  this.value;
    //     alert( productPrice);
    // });
    const filterBtn = document.querySelector('button.filter');
    if (filterBtn) {
      filterBtn.addEventListener('click', () => {
        let shopSidebar = document.querySelector('.shop__sidebar');
        let body = document.querySelector('body');
        shopSidebar.classList.toggle('active');
        body.classList.toggle('overlay');
      });
    }

    function loginFunction() {
        var x = document.getElementById("password");
            if (x.type === "password") {
                x.type = "text";
            } else {
                x.type = "password";
            }
        }


    function registerFunction() {
        var x = document.getElementById("password-confirm");
            if (x.type === "password") {
                x.type = "text";
            } else {
                x.type = "password";
            }
        }


    $('select').on('change', function() {
        var info = $(this).data("info");
        if(info == 'color') {
            var product_color = $(this).find(":selected").val();
            var product_id = $(this).data("id");
            $.ajax({
                type: "POST",
                url: "/order_settings",
                data: {
                    product_id: product_id,
                    product_color: product_color
                },
                error: function (data) {
                    var errors = data.responseJSON;
                    console.log(errors);
                },
                success: function (resp) {

                },
            });

        } else if(info == 'size') {
            var product_size = $(this).find(":selected").val();
            var product_id = $(this).data("id");
            $.ajax({
                type: "POST",
                url: "/order_settings",
                data: {
                    product_id: product_id,
                    product_size: product_size
                },
                error: function (data) {
                    var errors = data.responseJSON;
                    console.log(errors);
                },
                success: function (resp) {

                },
            });
        }
    });


    $(".sizes-list__button").click(function () {
        if($(this).hasClass('disabled')) {} else {
            var size_value = $(this).data('id');
            $(".sizes-list__button").removeClass("active");
            $(this).addClass("active");
        }
    });

    $('input[type=radio][name=pay]').change(function() {
        if (this.value == 'cash') {
            $('.non-cash-display').addClass("d-none");
            $('.cash-display').removeClass("d-none");
        }
        else if (this.value == 'non_cash') {
            $('.non-cash-display').removeClass("d-none");
            $('.cash-display').addClass("d-none");
        }
    });

    
    $('#telcell_form').on('submit', function(e) {
        e.preventDefault();

        var form = $(this);
        var formData = form.serialize();

        $.ajax({
            url: form.attr('action'),
            type: 'POST',
            data: formData,
            success: function(response) {
                console.log('Success:', response);
                let lang = $('html').attr('lang');
                if(lang == 'hy')
                { message = 'Ձեր հավելվածին ուղարկվել է վճարման ծանուցում', info = 'Ուշադրություն', button = 'Փակել'}
                else if(lang == 'ru')
                { message = 'В ваше приложение было отправлено уведомление об оплате', info = 'Внимание',  button = 'Закрыть' }
                else if(lang == 'en')
                { message = 'A payment notification has been sent to your app', info = 'Attention', button = 'Close' }
                Swal.fire({
                    icon: 'success',
                    title: info,
                    text: message,
                    confirmButtonText: button,
                    });
                if(response != null) {
                    checkStatusInterval = setInterval(checkPaymentStatus, 20000);
                }
            },
            error: function(xhr, status, error) {
                console.log('Error:', error);
            }
        });
    });

    var checkStatusInterval;
    function checkPaymentStatus() {
        order_id = $('#order_id').val();
        $.ajax({
            url: '/telcell-status',
            type: 'POST',
            data: {
                order_id: order_id 
            },
            success: function(response) {
                if(response.status != 'loading') {
                    if (response.status === 'success') {
                        
                        clearInterval(checkStatusInterval);
                        window.location.href = response.redirect;
                    } else {
                        console.log(response);
                    
                        window.location.href = response.redirect;
                    }
                }
                if(response.status == 'error') {
                    window.location.href = response.redirect;
                }
            },
            error: function(xhr, status, error) {
                console.log('Ошибка:', error);
                clearInterval(checkStatusInterval);
                window.location.href = 'https://haki.am/nosuccess';
            }
        });
    }
    