function show_Toaster(message, type) {
    var success = "#00b09b, #96c93d";
    var error = "#a7202d, #ff4044";
    var ColorCode = type == "success" ? success : error;

    Toastify({
        text: message,
        duration: 3000,
        close: true,
        gravity: "bottom", // top or bottom
        position: "center", // left, center or right
        stopOnFocus: true, // Prevents dismissing of toast on hover
        style: {
            background: `linear-gradient(to right, ${ColorCode})`,
        },
    }).showToast();
}

$('#loginForm').on('submit', function (e) {
    e.preventDefault();
    var submitBtn = $(this).find("button[type='submit']");
    var btnTitle = submitBtn.html();
    submitBtn.prop('disabled', true).html('Please Wait');
    $.ajax({
        url: "/login",
        method: "POST",
        data: $(this).serialize(),
        datatype: 'json',
        processData: false,
        success: function (response) {
            if (response.error) {
                response.error.map((item) => {
                    show_Toaster(item.msg, 'error');
                })
            }
            if (response.success) {
                response.success.map((item) => {
                    show_Toaster(item.msg, 'success');
                })
                document.getElementById("loginForm").reset();
                setTimeout(() => {
                    window.location.href = "/";
                }, 500);
            }
            submitBtn.prop('disabled', false).html(btnTitle);
        },
    });
});

$('#registerForm').on('submit', function (e) {
    e.preventDefault();
    var submitBtn = $(this).find("button[type='submit']");
    var btnTitle = submitBtn.html();
    submitBtn.prop('disabled', true).html('Please Wait');
    $.ajax({
        url: "/register",
        method: "POST",
        data: $(this).serialize(),
        datatype: 'json',
        processData: false,
        success: function (response) {
            if (response.error) {
                response.error.map((item) => {
                    show_Toaster(item.msg, 'error');
                })
            }
            if (response.success) {
                response.success.map((item) => {
                    show_Toaster(item.msg, 'success');
                })
                document.getElementById("registerForm").reset();
            }
            submitBtn.prop('disabled', false).html(btnTitle);
        },
    });
});

$('#contactForm').on('submit', function (e) {
    e.preventDefault();
    var submitBtn = $(this).find("button[type='submit']");
    var btnTitle = submitBtn.html();
    submitBtn.prop('disabled', true).html('Please Wait');
    $.ajax({
        url: "/contact",
        method: "POST",
        data: $(this).serialize(),
        datatype: 'json',
        processData: false,
        success: function (response) {
            if (response.error) {
                response.error.map((item) => {
                    show_Toaster(item.msg, 'error');
                })
            }
            if (response.success) {
                response.success.map((item) => {
                    show_Toaster(item.msg, 'success');
                })
                $('#contactForm').trigger('reset');
                $('#product').val('').selectpicker("refresh");
            }
            submitBtn.prop('disabled', false).html(btnTitle);
        },
    });
});

function openTab(tabName) {
    window.location.href = `/${tabName}`;
}

$('#profileForm').on('submit', function (e) {
    e.preventDefault();
    var submitBtn = $(this).find("button[type='submit']");
    var btnTitle = submitBtn.html();
    submitBtn.prop('disabled', true).html('Please Wait');
    $.ajax({
        url: "/updateProfile",
        method: "POST",
        data: $(this).serialize(),
        datatype: 'json',
        processData: false,
        success: function (response) {
            if (response.error) {
                response.error.map((item) => {
                    show_Toaster(item.msg, 'error');
                })
            }
            if (response.success) {
                var fullname = $("#fullname").val()
                $("#navName").html(`Welcome ${fullname}`)
                response.success.map((item) => {
                    show_Toaster(item.msg, 'success');
                })
            }
            submitBtn.prop('disabled', false).html(btnTitle);
        },
    });
});

$('#changePasswordForm').on('submit', function (e) {
    e.preventDefault();
    var submitBtn = $(this).find("button[type='submit']");
    var btnTitle = submitBtn.html();
    submitBtn.prop('disabled', true).html('Please Wait');
    $.ajax({
        url: "/changePassword",
        method: "POST",
        data: $(this).serialize(),
        datatype: 'json',
        processData: false,
        success: function (response) {
            if (response.error) {
                response.error.map((item) => {
                    show_Toaster(item.msg, 'error');
                })
            }
            if (response.success) {
                response.success.map((item) => {
                    show_Toaster(item.msg, 'success');
                })
                $('#profileForm').trigger('reset');
                setTimeout(() => {
                    window.location.reload()
                }, 500);
            }
            submitBtn.prop('disabled', false).html(btnTitle);
        },
    });
});

$('#addressForm').on('submit', function (e) {
    e.preventDefault();
    var type = $("#addressSubmitBtn").attr("data-type");
    if (type == 'add') {
        var url = '/addAddress';
    } else if (type == 'update') {
        var url = '/updateAddress';
    }
    var submitBtn = $(this).find("button[type='submit']");
    var btnTitle = submitBtn.html();
    submitBtn.prop('disabled', true).html('Please Wait');
    $.ajax({
        url: url,
        method: "POST",
        data: $(this).serialize(),
        datatype: 'json',
        processData: false,
        success: function (response) {
            if (response.error) {
                response.error.map((item) => {
                    show_Toaster(item.msg, 'error');
                })
            }
            if (response.success) {
                response.success.map((item) => {
                    show_Toaster(item.msg, 'success');
                })
                $(this).trigger('reset');
                setTimeout(() => {
                    window.location.reload();
                }, 500);
            }
            submitBtn.prop('disabled', false).html(btnTitle);
        },
    });
});

function editAddress(address) {
    let add = JSON.parse(address);
    $("#addressID").val(add.id);
    $("#name").val(add.name);
    $("#mobile").val(add.mobile);
    $("#address").val(add.address);
    $("#city").val(add.city);
    $("#state").val(add.state);
    $("#pincode").val(add.pincode);
    console.log(add.type);
    $("#type").val(add.type);
    $("#addressSubmitBtn").attr("data-type", "update");
    $('#staticBackdrop').modal('show')
}

$(".closeModal").on('click', function () {
    $("#addressSubmitBtn").attr("data-type", "add");
})

function deleteAddress(id) {
    $.ajax({
        url: '/deleteAddress',
        method: "POST",
        data: "id=" + id,
        processData: false,
        success: function (response) {
            if (response.error) {
                response.error.map((item) => {
                    show_Toaster(item.msg, 'error');
                })
            }
            if (response.success) {
                response.success.map((item) => {
                    show_Toaster(item.msg, 'success');
                })
                $(`#row-${id}`).remove();
            }
        },
    });
}

$("#forgotPasswordForm").on('submit', function (e) {
    e.preventDefault();
    var submitBtn = $(this).find("button[type='submit']");
    var btnTitle = submitBtn.html();
    submitBtn.prop('disabled', true).html('Please Wait');

    let url = ''

    if (submitBtn.attr("data-type") == 'forgot')
        url = "/forgotPassword"
    else if (submitBtn.attr("data-type") == 'verification')
        url = "/forgotPasswordVerification"
    else if (submitBtn.attr("data-type") == 'changepassword')
        url = "/updatePassword"

    $.ajax({
        url,
        method: "POST",
        data: $(this).serialize(),
        datatype: 'json',
        processData: false,
        success: function (response) {
            if (response.error) {
                response.error.map((item) => {
                    show_Toaster(item.msg, 'error');
                })
                submitBtn.prop('disabled', false).html(btnTitle);
            }
            if (response.success) {
                response.success.map((item) => {
                    show_Toaster(item.msg, 'success');
                })
                if (submitBtn.attr("data-type") == 'forgot') {
                    $("#mobilenumber").attr('disabled');
                    $(".verification").removeClass("d-none");
                    submitBtn.attr('data-type', 'verification').html("Verify");
                } else if (submitBtn.attr("data-type") == 'verification') {
                    $("#verification").attr('disabled');
                    $(".forgot-password").removeClass("d-none");
                    submitBtn.attr('data-type', 'changepassword').html("Change Password");
                } else if (submitBtn.attr("data-type") == 'changepassword') {
                    // setTimeout(() => {
                    //     window.location.href = 'auth'
                    // }, 500);
                }
            }
            submitBtn.prop('disabled', false);
        },
    });
});

$(".buyPro").on('click', function () {
    var type = $(this).attr("data-type");
    var element = JSON.parse($(this).attr("data-id"));
    var id = element.id
    var price = element.selling_price ? element.selling_price : element.price
    var title = element.title
    var quantity = 1
    var currentQty = $(`.qty-${id}`).html()
    var image = element.thumbnail ? element.thumbnail : element.image
    var data = {
        id, title, price, quantity, image, type
    }
    if (type == 'add' || type == 'buynow')
        var url = '/addToCart'
    else if (type == 'remove')
        var url = '/removeFromCart'
    else if (type == 'minus')
        var url = '/removeCartQuantity'

    fetch(url, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data),
    }).then((res) => res.json()).then((response) => {
        if (response.error) {
            response.error.map((item) => {
                show_Toaster(item.msg, 'error');
            })
        }
        if (response.success) {
            response.success.map((item) => {
                if (type !== 'buynow' && currentQty !== 0)
                    show_Toaster(item.msg, 'success');

                $('#cartLength').html(response.success[0].data)

                if (location.pathname == '/cart')
                    getCartTotal()

                if (type != 'buynow') {
                    if (type == 'add') {
                        if (location.pathname == '/cart') {
                            $(`.qty-${id}`).html(parseInt(currentQty) + 1)
                            $(`#perTotal-${id}`).html(`₹${(parseInt(currentQty) + 1) * price}`)
                        } else {
                            $(`.showQty-${id}`).removeClass('d-none')
                            $(`.hideQty-${id}`).addClass('d-none')
                            $(`.showQty-${id}`).addClass('d-inline')
                            $(`.qty-${id}`).html(parseInt(currentQty) + 1)
                        }
                    } else if (type == 'minus' && currentQty > 1) {
                        $(`.qty-${id}`).html(parseInt(currentQty) - 1)
                        $(`#perTotal-${id}`).html(`₹${(parseInt(currentQty) - 1) * price}`)
                    }
                    else {
                        if (location.pathname == '/cart') {
                            $(`#row-${id}`).remove();
                        } else {
                            $(`.showQty-${id}`).addClass('d-none')
                            $(`.showQty-${id}`).removeClass('d-inline')
                            $(`.hideQty-${id}`).removeClass('d-none')
                            $(`.qty-${id}`).html(0)
                        }
                    }
                } else {
                    setTimeout(() => {
                        window.location.href = '/checkout'
                    }, 500)
                }
            })
        }
    }).catch(err => {
        show_Toaster('Something went wrong', 'error')
    })
});

function getCartTotal() {
    fetch('/getCartTotal', {
        method: 'GET',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json'
        }
    }).then((res) => res.json()).then((response) => {
        if (response.total == 0) return window.location.href = '/'
        $('#total').html(`₹ ${response.total}`)
    }).catch(err => {
        show_Toaster('Can not get total', 'error')
    })
}

$(".clearCart").on('click', function () {
    $.ajax({
        url: "/clearCart",
        method: "GET",
        success: function (response) {
            if (response.error) {
                response.error.map((item) => {
                    show_Toaster(item.msg, 'error');
                })
            }
            if (response.success) {
                response.success.map((item) => {
                    show_Toaster(item.msg, 'success');
                    setTimeout(() => {
                        var path = location.pathname
                        location.replace(path)
                    }, 500);
                })
            }
        },
    });
});

$(".detailsLink").on('click', function (e) {
    console.log('onm');
    if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
    var p_code = $(this).attr('data-pcode');
    window.location.href = `/details/${p_code}`
});

$(".invoice").on('click', function () {
    var order_id = $(this).attr('data-order')
    window.open(`/invoice/${order_id}`, '_blank')
})