
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();
}

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

    var email = $('#email').val();
    var password = $('#password').val();
    axios.post(`/admin/validate_login`, { email, password })
        .then((res) => {
            console.log(res)
            if (res.data.type === 'success') {
                setTimeout(() => {
                    window.location.href = `/admin/`;
                }, 500);
            }
            show_Toaster(res.data.message, res.data.type);
            $(this).find("button[type='submit']").prop('disabled', false).html('Login');
        }).catch(err => {
            Object.values(err.response.data.errors).map(item => {
                show_Toaster(item[0], 'error');
            })
            $(this).find("button[type='submit']").prop('disabled', false).html('Login');
        })
});

$('#managevendor').on('submit', function (e) {
    e.preventDefault();
    axios.post(`${url}/admin/EditVendors`, new FormData(this))
        .then((res) => {
            if (res.data.type === 'success') {
                setTimeout(() => {
                    window.location.href = `${url}/admin/list-vendors`;
                }, 500);
            }
            show_Toaster(res.data.message, res.data.type);
        }).catch(err => {
            Object.values(err.response.data.errors).map(item => {
                show_Toaster(item[0], 'error');
            })
        })
});

// forgot password

$('#forgot-password').on('submit', function (e) {
    e.preventDefault();
    $(this).find("button[type='submit']").prop('disabled', true);
    axios.post(`${url}/admin/password`, new FormData(this)).then(res => {
        $(this).find("button[type='submit']").attr('disabled', false);
        if (res.data.type === 'success') {
            $(this).find("button[type='submit']").attr('disabled', true);
            $(this).find("button[type='text']").attr('disabled', true);
            $('#alert').removeClass('d-none').html('Kindly check your email');
        }
        show_Toaster(res.data.message, res.data.type);
    }).catch(err => {
        if (err.response.data.errors) {
            Object.values(err.response.data.errors).map(item => {
                show_Toaster(item[0], 'error');
            })
        }
        $(this).find("button[type='submit']").prop('disabled', false);
    })
});

// reset password

$('#resetPasswordForm').on('submit', function (e) {
    e.preventDefault();
    $(this).find("button[type='submit']").prop('disabled', true);

    const formData = new FormData();
    formData.append('email', $("#email").attr('data-email'));
    formData.append('password', $("#password").val());
    formData.append('password_confirmation', $("#password-confirm").val());
    formData.append('reset_pass', $("#email").attr('data-key'));

    axios.post(`${url}/admin/change_password`, formData).then(res => {
        if (res.data.type === 'success') {
            setTimeout(() => {
                window.location.href = `${url}/admin`;
            }, 1500);
        }
        show_Toaster(res.data.message, res.data.type);
    }).catch(err => {
        if (err.response.data.errors) {
            Object.values(err.response.data.errors).map(item => {
                show_Toaster(item[0], 'error');
            })
        }
        $(this).find("button[type='submit']").prop('disabled', false);
    })
});

$(".editVendor").on('click', function () {
    let data = JSON.parse($(this).attr('data-data'));
    $('#id').val(data.id);
    $('#name').val(data.name);
    $('#email').val(data.email);
    $('#mobile').val(data.mobile);
    $('#address').val(data.address);
    $('#state').val(data.state);
    $('#city').val(data.city);
})
$(".editAdmin").on('click', function () {
    let data = JSON.parse($(this).attr('data-data'));
    $('#id').val(data.id);
    $('#name').val(data.name);
    $('#email').val(data.email);
    $('#mobile').val(data.mobile);

    if (JSON.parse(data.permission).write.length > 0) {
        $('.write_permission').each(function (index, value) {
            if (JSON.parse(data.permission).write.includes($(value).attr('data-title')))
                $(this).prop('checked', true);
            else
                $(this).prop('checked', false);
        });
    }
    if (JSON.parse(data.permission).read.length > 0) {
        $('.read_permission').each(function (index, value) {
            if (JSON.parse(data.permission).read.includes($(value).attr('data-title')))
                $(this).prop('checked', true);
            else
                $(this).prop('checked', false);
        });
    }

})

$(".editVendor").on('click', function () {
    let data = JSON.parse($(this).attr('data-data'));
    $('#id').val(data.id);
    $('#name').val(data.name);
    $('#email').val(data.email);
    $('#mobile').val(data.mobile);
    $('#address').val(data.address);
    $('#state').val(data.state);
    $('#city').val(data.city);
})
$(".editAdmin").on('click', function () {
    let data = JSON.parse($(this).attr('data-data'));
    $('#id').val(data.id);
    $('#name').val(data.name);
    $('#email').val(data.email);
    $('#mobile').val(data.mobile);

    if (JSON.parse(data.permission).write.length > 0) {
        $('.write_permission').each(function (index, value) {
            if (JSON.parse(data.permission).write.includes($(value).attr('data-title')))
                $(this).prop('checked', true);
            else
                $(this).prop('checked', false);
        });
    }
    if (JSON.parse(data.permission).read.length > 0) {
        $('.read_permission').each(function (index, value) {
            if (JSON.parse(data.permission).read.includes($(value).attr('data-title')))
                $(this).prop('checked', true);
            else
                $(this).prop('checked', false);
        });
    }

})

$("#addCategory").on('submit', function (e) {
    e.preventDefault();
    $(this).find("button[type='submit']").prop('disabled', true).html('Please Wait');
    axios.post(`${url}/admin/addCategory`, new FormData(this))
        .then((res) => {
            if (res.data.type === 'success') $(this).trigger('reset');
            show_Toaster(res.data.message, res.data.type);
            $(this).find("button[type='submit']").prop('disabled', false).html('Submit');
        }).catch(err => {
            console.log(err);
            if (err.response.data.errors) {
                Object.values(err.response.data.errors).map(item => {
                    show_Toaster(item[0], 'error');
                })
            }
            $(this).find("button[type='submit']").prop('disabled', false).html('Submit');
        })
});

$("#addSubCategory").on('submit', function (e) {
    e.preventDefault();
    $(this).find("button[type='submit']").prop('disabled', true).html('Please Wait');
    axios.post(`${url}/admin/addSubCategory`, new FormData(this))
        .then((res) => {
            if (res.data.type === 'success') $(this).trigger('reset');
            show_Toaster(res.data.message, res.data.type);
            $(this).find("button[type='submit']").prop('disabled', false).html('Submit');
        }).catch(err => {
            if (err.response.data.errors) {
                Object.values(err.response.data.errors).map(item => {
                    show_Toaster(item[0], 'error');
                })
            }
            $(this).find("button[type='submit']").prop('disabled', false).html('Submit');
        })
});


$("#parent").on('change', function () {
    $('#code').val($($('option:selected', this)).attr('data-attr'));
});

$(".category_active").on('click', function () {
    const formData = new FormData();
    formData.append('id', $(this).attr('data-id'));
    formData.append('status', $(this).is(':checked') ? 1 : 0);
    axios.post(`${url}/admin/categoryStatus`, formData).then(res => {
        if (res.data.type === 'success') window.location.reload();
    }).catch(err => {
        if (err.response.data.errors) {
            Object.values(err.response.data.errors).map(item => {
                show_Toaster(item[0], 'error');
            })
        }
    })
});

$('.edit').on('click', function () {
    var id = $(this).attr('data-id');
    var title = $(this).attr('data-title');
    $('#editTitle').val(title).attr('data-id', id);
});

$('#editForm').on('submit', function (e) {
    e.preventDefault();
    var title = $(this).find("input[name='title']").val();
    var id = $(this).find("input[name='title']").attr('data-id');
    const formData = new FormData();
    formData.append('id', id);
    formData.append('title', title);
    $(this).find("button[type='submit']").prop('disabled', true).html('Please Wait');
    axios.post(`${url}/admin/categoryUpdate`, formData)
        .then((res) => {
            if (res.data.type === 'success') {
                $(this).trigger('reset');
                $('#staticBackdrop').modal('hide');
                window.location.reload();
            }
            show_Toaster(res.data.message, res.data.type);
            $(this).find("button[type='submit']").prop('disabled', false).html('Update');
        }).catch(err => {
            if (err.response.data.errors) {
                Object.values(err.response.data.errors).map(item => {
                    show_Toaster(item[0], 'error');
                })
            }
            $(this).find("button[type='submit']").prop('disabled', false).html('Update');
        })
});

$(".delete").on('click', function () {
    if (!confirm('Are You Sure?')) return;

    var id = $(this).attr('data-id');
    axios.post(`${url}/admin/categoryDelete`, { id })
        .then((res) => {
            if (res.data.type === 'success') window.location.reload();
            show_Toaster(res.data.message, res.data.type);
        }).catch(err => {
            if (err.response.data.errors) {
                Object.values(err.response.data.errors).map(item => {
                    show_Toaster(item[0], 'error');
                })
            }
        })
});

$("#editBanner").on('click', function () {
    document.getElementById('bannerInput').click()
});

$("#bannerInput").on('change', function () {
    var id = $('#category_image').attr('data-id');
    var banner = document.querySelector('#bannerInput').files[0];
    const formData = new FormData();
    formData.append('id', id);
    formData.append('banner', banner);
    axios.post(`${url}/admin/updateCategoryBanner`, formData)
        .then((res) => {
            if (res.data.type === 'success') {
                var reader = new FileReader();
                var imgtag = document.getElementById("category_image");
                imgtag.title = banner.name;
                reader.onload = function (event) {
                    imgtag.src = event.target.result;
                };
                reader.readAsDataURL(banner);
            }
            show_Toaster(res.data.message, res.data.type);
        }).catch(err => {
            if (err.response.data.errors) {
                Object.values(err.response.data.errors).map(item => {
                    show_Toaster(item[0], 'error');
                })
            }
        })
});

$("#category_banner_select").on('change', function () {
    var id = $(this).val();
    if (id != '') {
        axios.post(`${url}/admin/getCategoryByID`, { id })
            .then((res) => {
                $("#category_image").removeClass('d-none');
                $(".editBanner").removeClass('d-none');
                if (res.data.type === 'success') {
                    $("#category_image").attr('src', res.data.data.banner).attr('data-id', res.data.data.id)
                } else {
                    $(".editBanner").addClass('d-none');
                    $("#category_image").addClass('d-none');
                    show_Toaster(res.data.message, res.data.type);
                }
            }).catch(err => {
                if (err.response.data.errors) {
                    Object.values(err.response.data.errors).map(item => {
                        show_Toaster(item[0], 'error');
                    })
                }
            })
    }
});

$("#deleteBanner").on('click', function () {
    var id = $('#category_image').attr('data-id');
    axios.post(`${url}/admin/deleteCategoryBanner`, { id })
        .then((res) => {
            if (res.data.type === 'success') {
                $("#category_image").attr('src', '');
            }
            show_Toaster(res.data.message, res.data.type);
        }).catch(err => {
            if (err.response.data.errors) {
                Object.values(err.response.data.errors).map(item => {
                    show_Toaster(item[0], 'error');
                })
            }
        })
});

$("#editVariant").on('submit', function (e) {
    e.preventDefault();
    var id = $('#code').attr('data-id');
    var variantInput = $('#variantInput').val();
    const formData = new FormData();
    formData.append('id', id);
    formData.append('variant', variantInput);
    $(this).find("button[type='submit']").prop('disabled', true).html('Please Wait');
    axios.post(`${url}/admin/updateVariant`, formData)
        .then((res) => {
            if (res.data.type === 'success') {
                setTimeout(() => {
                    return window.location.href = `${url}/admin/variant`;
                }, 500);
            }
            show_Toaster(res.data.message, res.data.type);
            $(this).find("button[type='submit']").prop('disabled', false).html('Update');
        }).catch(err => {
            if (err.response.data.errors) {
                Object.values(err.response.data.errors).map(item => {
                    show_Toaster(item[0], 'error');
                })
            } else {
                show_Toaster('Something Went Wrong', 'error');
            }
            $(this).find("button[type='submit']").prop('disabled', false).html('Update');
        })
});

function showHideDiv(name, type) {
    var element = document.querySelector(name);
    if (type == 'show') {
        if (element.classList.contains('d-none')) return element.classList.remove('d-none');
    } else if (type == 'hide') {
        if (!element.classList.contains('d-none')) return element.classList.add('d-none');
    }

}

let count = 0;

function generateHtml(data, variant = 0) {
    var html = '';
    if (variant) html += '<div class="d-flex float-right" onclick="deleteVariantHtml(this)"><i class="fas fa-trash text-danger"></i></div>';
    html += '<div class="row">';
    data.forEach(element => {
        html += `<div class="col-6"><div class="form-group"><label>${element}</label><input type="text" id="${element.toLowerCase()}" name="${element.toLowerCase()}" class="form-control" /></div></div>`;
    });
    count++;
    return html;
}

$("#addProductCategory").on('change', function () {
    var value = $(this).val();
    if (value == '') {
        $('.variant').html('');
        return showHideDiv('.variant', 'hide');
    }
    showHideDiv('.variant', 'show');
    var variant = JSON.parse($('option:selected', this).attr('data-data')).variant;
    var html = generateHtml(variant.split(","))
    $('.variant').html(html);
});

$(".addmore").on('click', function () {
    var value = $("#addProductCategory").val();
    if (value == '') {
        $('.variant').html('');
        return showHideDiv('.variant', 'hide');
    }
    var variant = JSON.parse($("#addProductCategory option:selected").attr('data-data')).variant;
    var html = generateHtml(variant.split(","), 1)
    $('.variant').append(html);
});

function deleteVariantHtml(e) {
    e.nextSibling.remove();
    e.remove();
}

$("#on_sale").on('change', function () {
    if ($(this).is(":checked")) {
        $(this).removeAttr('checked')
    } else {
        $(this).attr('checked')
    }
});

$('#customFile').on('change', function (evt) {
    var files = evt.target.files;
    document.getElementById('gallery-thumbnail').innerHTML = '';
    for (var i = 0, f; f = files[i]; i++) {
        if (!f.type.match('image.*')) {
            continue;
        }
        var reader = new FileReader();
        reader.onload = (function (theFile) {
            return function (e) {
                var span = document.createElement('span');
                span.innerHTML = [`<div class="gallery-item" data-image="${e.target.result}" href="${e.target.result}" data-title="${escape(theFile.name)}" style="background-image:url('${e.target.result}')" </div>`].join('');
                document.getElementById('gallery-thumbnail').insertBefore(span, null);
            };
        })(f);
        reader.readAsDataURL(f);
    }
})

$('#multipleImage').on('change', function (evt) {
    var files = evt.target.files;
    document.getElementById('gallery-multithumbnail').innerHTML = '';
    for (var i = 0, f; f = files[i]; i++) {
        if (!f.type.match('image.*')) {
            continue;
        }
        var reader = new FileReader();
        reader.onload = (function (theFile) {
            return function (e) {
                var span = document.createElement('span');
                span.innerHTML = [`<div class="gallery-item" data-image="${e.target.result}" href="${e.target.result}" data-title="${escape(theFile.name)}" style="background-image:url('${e.target.result}')" </div>`].join('');
                document.getElementById('gallery-multithumbnail').insertBefore(span, null);
            };
        })(f);
        reader.readAsDataURL(f);
    }
})

$('#variant_id').on('change', function (e) {
    var id = e.target.value;
    if (!id) return
    axios.post(`${url}/admin/getProductByVariant`, { id })
        .then((res) => {
            if (res.data.type === 'success') {
                $('#title').val(res.data.data.product.title);
                $("#description").summernote('code', res.data.data.product.description);
                res.data.data.product.is_featured ? document.getElementById("is_featured").checked = true : '';
                res.data.data.product.on_sale ? document.getElementById("on_sale").checked = true : '';
                $('#display_price').val(res.data.data.product.display_price);
                $('#selling_price').val(res.data.data.product.selling_price);
                $('#gst').val(res.data.data.product.gst);
                $('#shipping_charges').val(res.data.data.product.shipping_charges);
                $('#total_qty').val(res.data.data.product.total_qty);
                $('#discount').val(res.data.data.product.discount);
                $('#addProductCategory').val(res.data.data.product.category_id);
                showHideDiv('.variant', 'show');
                var variant = res.data.data.variant.variant;
                var html = generateHtml(variant.split(","))
                $('.variant').html(html);
                var product = JSON.parse(res.data.data.product.details);
                variant.split(",").forEach(element => {
                    var vari = element.toLowerCase();
                    document.getElementById(element.toLowerCase()).value = product[vari];
                });
            }
        }).catch(err => {
            if (err.response.data.errors) {
                Object.values(err.response.data.errors).map(item => {
                    show_Toaster(item[0], 'error');
                })
            }
        })
});

function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

function generateHtmlWithValue(data) {
    var html = '';
    html += '<div class="row">';
    Object.keys(data).forEach(function (key) {
        html += `<div class="col-6"><div class="form-group"><label>${capitalizeFirstLetter(key)}</label><input type="text" id="${key}" name="${key}" value="${data[key]}" class="form-control" /></div></div>`;
    });
    count++;
    return html;
}

function deleteImage(product_id, image_key) {
    if (!confirm('Are you sure?')) return
    if (!image_key) return
    axios.post(`${url}/admin/deleteImageProduct`, { product_id, image_key }).then(res => {
        if (res.data.type === 'success') {
            window.location.reload();
        }
        show_Toaster(res.data.message, res.data.type);
    }).catch(err => {
        if (err.response.data.errors) {
            Object.values(err.response.data.errors).map(item => {
                show_Toaster(item[0], 'error');
            })
        }
    })
}

$('#editProduct').on('submit', function (e) {
    e.preventDefault();
    $(this).find("button[type='submit']").prop('disabled', true).html('Please Wait');
    axios.post(`${url}/admin/updateProduct`, new FormData(this)).then(res => {
        if (res.data.status == 'success') {
            setTimeout(() => {
                window.location.href = `${url}/admin/products`;
            }, 500);
        }
        $(this).find("button[type='submit']").prop('disabled', false).html('Update Product');
    }).catch(err => {
        if (err.response.data.errors) {
            Object.values(err.response.data.errors).map(item => {
                show_Toaster(item[0], 'error');
            })
        }
        $(this).find("button[type='submit']").prop('disabled', false).html('Update Product');
    })
});


$('.requestDelete').on('click', function () {

    const formData = new FormData();
    var id = $(this).attr('data-id');
    var status = $(this).attr('data-value');
    var newStatus = status == 1 ? 0 : 1;


    $(`#span-${id}`).html('Please Wait...');


    formData.append('id', id);
    formData.append('status', status);
    axios.post(`${url}/admin/updateReviewStatus`, formData).then(res => {

        show_Toaster(res.data.message, res.data.type);
        if (res.data.type == 'success') {
            // change label
            $(`#span-${id}`).html(status == 1 ? 'Active' : 'Deactivated');


            $(`#span-${id}`).removeClass(status == 1 ? 'badge-danger' : 'badge-success');
            $(`#span-${id}`).addClass(status == 1 ? 'badge-success' : 'badge-danger');

            // remove button
            $(this).attr('data-value', newStatus)

        }

    }).catch(err => {
        console.log(res);
    });

});


$('#addReviewForm').on('submit', function (e) {
    $('.insertReview').html('Please Wait...')
    e.preventDefault();
    const formData = new FormData();

    formData.append('fullname', $('#fullname').val());
    formData.append('mobile', $('#mobile').val());
    formData.append('email', $('#email').val());
    formData.append('p_code', $('#p_code').val());
    formData.append('reviews', $('#review').val());
    formData.append('ratings', $('#rating').val());


    axios.post(`${url}/admin/insertReview`, formData).then(res => {

        $('.insertReview').html('Submit Review')
        show_Toaster(res.data.message, res.data.type);
        if (res.data.type == 'success') {
            $('#addReviewForm').reset();
        }

    }).catch(err => {
        console.log(res);
    });

});

$(".addmore").on('click', function () {
    var value = $("#addProductCategory").val();
    if (value == '') {
        $('.variant').html('');
        return showHideDiv('.variant', 'hide');
    }
    var variant = JSON.parse($("#addProductCategory option:selected").attr('data-data')).variant;
    var html = generateHtml(variant.split(","), 1)
    $('.variant').append(html);
});

function deleteVariantHtml(e) {
    e.nextSibling.remove();
    e.remove();
}

$("#on_sale").on('change', function () {
    if ($(this).is(":checked")) {
        $(this).removeAttr('checked')
    } else {
        $(this).attr('checked')
    }
});

$("#addProduct").on('submit', function (e) {
    console.log(e)
    e.preventDefault();

    $('#submitBtn').prop("disabled", true).html('Please Wait');

    axios.post(`/admin/insertProduct`, new FormData(this), { headers: { "Content-Type": "multipart/form-data", } })
        .then(res => {
            if (res.data.type === 'success') {
                console.log('success');
            }
            show_Toaster(res.data.message, res.data.type);
            $('#submitBtn').prop('disabled', false).html('Add Product')
        })
        .catch(err => {

            show_Toaster(err.response.data.message);
            $('#submitBtn').prop('disabled', false).html('Add Product')
        });
});

// $("#addProduct").on('submit', function (e) {
//     e.preventDefault();
//     $('.submit').prop('disabled', true).html('Please Wait');
//     var data = $(this).serialize()
//     axios.post(`/admin/insertProduct`, data).then(res => {
//         if (res.data.type === 'success') {
//             console.log('success');
//         }
//         show_Toaster(res.data.message, res.data.type);
//         $('.submit').prop('disabled', false).html('Add Product');
//     }).catch(err => {
//         if (err.response.data.errors) {
//             Object.values(err.response.data.errors).map(item => {
//                 show_Toaster(item[0], 'error');
//             })
//         }
//         $('.submit').prop('disabled', false).html('Add Product');
//     });
// });

$('#customFile').on('change', function (evt) {
    var files = evt.target.files;
    document.getElementById('gallery-thumbnail').innerHTML = '';
    for (var i = 0, f; f = files[i]; i++) {
        if (!f.type.match('image.*')) {
            continue;
        }
        var reader = new FileReader();
        reader.onload = (function (theFile) {
            return function (e) {
                var span = document.createElement('span');
                span.innerHTML = [`<div class="gallery-item" data-image="${e.target.result}" href="${e.target.result}" data-title="${escape(theFile.name)}" style="background-image:url('${e.target.result}')" </div>`].join('');
                document.getElementById('gallery-thumbnail').insertBefore(span, null);
            };
        })(f);
        reader.readAsDataURL(f);
    }
})

$('#multipleImage').on('change', function (evt) {
    var files = evt.target.files;
    document.getElementById('gallery-multithumbnail').innerHTML = '';
    for (let i = 0; f = files[i]; i++) {
        if (!f.type.match('image.*')) {
            continue;
        }
        let reader = new FileReader();
        reader.onload = (function (theFile) {
            return function (e) {
                var span = document.createElement('span');
                span.innerHTML = [`<div class="gallery-item" data-image="${e.target.result}" href="${e.target.result}" data-title="${escape(theFile.name)}" style="background-image:url('${e.target.result}')" </div>`].join('');
                document.getElementById('gallery-multithumbnail').insertBefore(span, null);
            };
        })(f);
        
        reader.readAsDataURL(f);
    }
})

$('#variant_id').on('change', function (e) {
    var id = e.target.value;
    if (!id) return
    axios.post(`${url}/admin/getProductByVariant`, { id })
        .then((res) => {
            if (res.data.type === 'success') {
                $('#title').val(res.data.data.product.title);
                $("#description").summernote('code', res.data.data.product.description);
                res.data.data.product.is_featured ? document.getElementById("is_featured").checked = true : '';
                res.data.data.product.on_sale ? document.getElementById("on_sale").checked = true : '';
                $('#display_price').val(res.data.data.product.display_price);
                $('#selling_price').val(res.data.data.product.selling_price);
                $('#gst').val(res.data.data.product.gst);
                $('#shipping_charges').val(res.data.data.product.shipping_charges);
                $('#total_qty').val(res.data.data.product.total_qty);
                $('#discount').val(res.data.data.product.discount);
                $('#addProductCategory').val(res.data.data.product.category_id);
                showHideDiv('.variant', 'show');
                var variant = res.data.data.variant.variant;
                var html = generateHtml(variant.split(","))
                $('.variant').html(html);
                var product = JSON.parse(res.data.data.product.details);
                variant.split(",").forEach(element => {
                    var vari = element.toLowerCase();
                    document.getElementById(element.toLowerCase()).value = product[vari];
                });
            }
        }).catch(err => {
            if (err.response.data.errors) {
                Object.values(err.response.data.errors).map(item => {
                    show_Toaster(item[0], 'error');
                })
            }
        })
});

function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

function generateHtmlWithValue(data) {
    var html = '';
    html += '<div class="row">';
    Object.keys(data).forEach(function (key) {
        html += `<div class="col-6"><div class="form-group"><label>${capitalizeFirstLetter(key)}</label><input type="text" id="${key}" name="${key}" value="${data[key]}" class="form-control" /></div></div>`;
    });
    count++;
    return html;
}

function deleteImage(product_id, image_key) {
    if (!confirm('Are you sure?')) return
    if (!image_key) return
    axios.post(`${url}/admin/deleteImageProduct`, { product_id, image_key }).then(res => {
        if (res.data.type === 'success') {
            window.location.reload();
        }
        show_Toaster(res.data.message, res.data.type);
    }).catch(err => {
        if (err.response.data.errors) {
            Object.values(err.response.data.errors).map(item => {
                show_Toaster(item[0], 'error');
            })
        }
    })
}

$('#editProduct').on('submit', function (e) {
    e.preventDefault();
    $(this).find("button[type='submit']").prop('disabled', true).html('Please Wait');
    axios.post(`${url}/admin/updateProduct`, new FormData(this)).then(res => {
        if (res.data.status == 'success') {
            setTimeout(() => {
                window.location.href = `${url}/admin/products`;
            }, 500);
        }
        $(this).find("button[type='submit']").prop('disabled', false).html('Update Product');
    }).catch(err => {
        if (err.response.data.errors) {
            Object.values(err.response.data.errors).map(item => {
                show_Toaster(item[0], 'error');
            })
        }
        $(this).find("button[type='submit']").prop('disabled', false).html('Update Product');
    })
});

function deletePro(e) {
    var id = e.getAttribute('data-id')
    var conf = confirm('Are you Sure?');
    if (!id || !conf) return
    axios.post(`${url}/admin/deleteProduct`, { id }).then(res => {
        if (res.data.status == 'success') {
            window.location.reload()
        }
        show_Toaster(res.data.message, res.data.type);
    }).catch(err => {
        if (err.response.data.errors) {
            Object.values(err.response.data.errors).map(item => {
                show_Toaster(item[0], 'error');
            })
        }
    })
}
