const priceSelector = document.getElementById('price');
const discountRateSelector = document.getElementById('discount_rate');
const discountedPriceSelector = document.getElementById('discounted_price');
const stockTrackingSelector = document.getElementById('stock_tracking');
const newImageForm = document.getElementById('new-image-form');

const cartDiscountRateSelector = document.getElementById('cart_discount_rate');
const cartDiscountedPriceSelector = document.getElementById('cart_discounted_price');

priceSelector.addEventListener('change', () => {
    var price = priceSelector.value;
    var discount_rate = discountRateSelector.value;
    var discounted_price = discountedPriceSelector.value;
    if(parseFloat(discount_rate) != 0){
        discounted_price = parseFloat(price)*parseFloat(1-discount_rate/100);
        discountedPriceSelector.value = formatter.format(discounted_price);
    }
});

discountedPriceSelector.addEventListener('change', () => {
    var price = parseFloat(priceSelector.value);
    var discounted_price = parseFloat(discountedPriceSelector.value);
    if(discounted_price >= price){
        discountRateSelector.value = 0;
        discountedPriceSelector.value = 0;
    }else{
        var discount_rate = 100-(parseFloat(discounted_price)/parseFloat(price))*100;
        discountRateSelector.value = formatter.format(discount_rate);
    }
});

discountRateSelector.addEventListener('change', () => {
    var price = priceSelector.value;
    var discount_rate = discountRateSelector.value;
    if(isNaN(parseFloat(discount_rate)) || parseFloat(discount_rate) == 0){
        discountedPriceSelector.value = price;
    }else{
        var discounted_price = parseFloat(price)*parseFloat((100-discount_rate)/100);
        discountedPriceSelector.value = formatter.format(discounted_price);
    }
});



cartDiscountedPriceSelector.addEventListener('change', () => {
    var price = parseFloat(priceSelector.value);
    var discounted_price = parseFloat(cartDiscountedPriceSelector.value);
    if(discounted_price >= price){
        cartDiscountRateSelector.value = 0;
        cartDiscountedPriceSelector.value = 0;
    }else{
        if(isNaN(parseFloat(discounted_price)) || parseFloat(discounted_price) == 0) {
            cartDiscountRateSelector.value = 0;
            cartDiscountedPriceSelector.value = 0;
        }else{
            var discount_rate = 100-(parseFloat(discounted_price)/parseFloat(price))*100;
            cartDiscountRateSelector.value = formatter.format(discount_rate);
        }
    }
});

cartDiscountRateSelector.addEventListener('change', () => {
    var price = priceSelector.value;
    var discount_rate = cartDiscountRateSelector.value;
    if(isNaN(parseFloat(discount_rate)) || parseFloat(discount_rate) == 0){
        cartDiscountedPriceSelector.value = 0;
    }else{
        var discounted_price = parseFloat(price)*parseFloat((100-discount_rate)/100);
        cartDiscountedPriceSelector.value = formatter.format(discounted_price);
    }
});


const formatter = new Intl.NumberFormat('en-US', {
    minimumFractionDigits: 2,      
    maximumFractionDigits: 2,
    useGrouping: false
});


stockTrackingSelector.addEventListener('change', () => {
    var selected = stockTrackingSelector.value;
    if(selected == 0){
        document.getElementById('stock_level').readOnly = true;
        document.getElementById('stock_critical_level').readOnly = true;
        document.getElementById('stock_level').setAttribute("required", false);
        document.getElementById('stock_critical_level').setAttribute("required", false);
    }else{
        document.getElementById('stock_level').readOnly = false;
        document.getElementById('stock_critical_level').readOnly = false;
        document.getElementById('stock_level').setAttribute("required", true);
        document.getElementById('stock_critical_level').setAttribute("required", true);
    }
});

//stockTrackingSelector.dispatchEvent(new Event('change'));

/*if(updateSectionContentModal != null) {
    updateSectionContentModal.addEventListener('show.bs.modal', function (event) {
        var button = event.relatedTarget;
        var id = button.getAttribute('data-id');
        videoChoices.destroy();
        var formData = new FormData();
        formData.append("id", id);

        request('/admin/common/api/course/content-info.php', formData, function (data) {
            try {
                data = JSON.parse(data);
                if (!(data instanceof Object)) {
                    new Toast({
                        type: "danger",
                        title: 'Hata!',
                        message: 'Bir hata oluştu. Lütfen tüm alanları kontrol ediniz',
                        duration: 10000,
                    });
                } else {
                    if (data['status']) {
                        document.getElementById('update-section-content-title').value = data['content']['title'];
                        document.getElementById('update-section-content-description').value = data['content']['description'];
                        document.getElementById('update-section-content-sort-order').value = data['content']['sort_order'];
                        document.getElementById('update-section-content-type').value = data['content']['type'];
                        //document.getElementById('update-section-content-video').value = data['content']['link'];
                        document.getElementById('update-section-content-section-id').value = data['content']['section_id'];
                        document.getElementById('update-section-content-id').value = data['content']['id'];

                        if(data['content']['download'] == 1) {
                            document.getElementById('update-section-content-download').checked = true;
                        }else{
                            document.getElementById('update-section-content-download').checked = false;
                        }

                        if(data['content']['type'] == "file" || data['content']['type'] == "image") {
                            document.getElementById('update-video-selector').classList.add('d-none');
                            document.getElementById('update-file-selector').classList.remove('d-none');
                            document.getElementById('update-section-content-file').value = data['content']['link'];
                        }else{
                            document.getElementById('update-video-selector').classList.remove('d-none');
                            document.getElementById('update-file-selector').classList.add('d-none');
                            document.querySelector("#update-section-content-video option[value='"+data['content']['link']+"']").selected = true;
                        }
                        
                        videoChoices = new Choices(document.getElementById('update-section-content-video'), {removeItems: true, removeItemButton: true, allowHTML: false});
                    }else{
                        new Toast({
                            type: "danger",
                            title: 'Hata!',
                            message: data['message'],
                            duration: 10000,
                        });
                    }
                }
            } catch (e) {
                new Toast({
                    type: "danger",
                    title: 'Hata!',
                    message: 'Bir hata oluştu. Lütfen daha sonra tekrar deneyiniz'+e,
                    duration: 10000,
                });
            }
        });
    });
}*/

function deleteImage(btn, id) {
    CustomAlert({
        title: "Görsel Sil",
        message: "Bu görseli silmek istediğinizden emin misiniz?",
        type: "question",
        close: true,
        showCancelButton: true,
        showCloseButton: true,
        showConfirmButton: true,
        cancelButtonText: 'Vazgeç',
        confirmButtonText: 'Sil',
        static: false
    }).then((result) => {
        if (result.value === true) {
            var formData = new FormData();
            formData.append("action", "delete-image");
            formData.append("id", id);
            request('/admin/common/api/product/delete-image', formData, function (data) {
                try {
                    data = JSON.parse(data);
                    if (!(data instanceof Object)) {
                        new Toast({
                            type: "danger",
                            title: 'Hata!',
                            message: 'Bir hata oluştu. Lütfen tekrar deneyiniz',
                            duration: 5000,
                        });
                    } else {
                        if (data['status']) {
                            var row = btn.parentNode.parentNode;
                            row.parentNode.removeChild(row);
                            new Toast({
                                type: "success",
                                title: '',
                                message: "Görsel başarıyla silindi",
                                duration: 5000,
                            });
                        }else{
                            new Toast({
                                type: "danger",
                                title: 'Hata!',
                                message: data['message'],
                                duration: 5000,
                            });
                        }
                    }
                } catch (e) {
                    new Toast({
                        type: "danger",
                        title: 'Hata!',
                        message: 'Bir hata oluştu. Lütfen daha sonra tekrar deneyiniz',
                        duration: 5000,
                    });
                }
            });
        }
    });
}

newImageForm.addEventListener('submit', (e) => {
    e.preventDefault();
    request('/admin/common/api/product/upload-image', '#new-image-form', function (data) {
        try {
            data = JSON.parse(data);
            if (!(data instanceof Object)) {
                new Toast({
                    type: "danger",
                    title: 'Hata!',
                    message: 'Bir hata oluştu. Lütfen tekrar deneyiniz',
                    duration: 5000,
                });
            } else {
                if (data['status']) {
                    new Toast({
                        type: "success",
                        title: '',
                        message: "Görsel başarıyla yüklendi",
                        duration: 5000,
                    });
                    location.reload();
                }else{
                    new Toast({
                        type: "danger",
                        title: 'Hata!',
                        message: data['message'],
                        duration: 5000,
                    });
                }
            }
        } catch (e) {
            new Toast({
                type: "danger",
                title: 'Hata!',
                message: 'Bir hata oluştu. Lütfen daha sonra tekrar deneyiniz',
                duration: 5000,
            });
        }
    });
});