/**
 *
 * You can write your JS code here, DO NOT touch the default style file
 * because it will make it harder for you to update.
 *
 */

"use strict";

// Login

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();
    $(this).find("button[type='submit']").prop('disabled', true);
    axios.post(`${url}/vendors/validate_login`, new FormData(this)).then(res => {
        if (res.data.type === 'success') {
            setTimeout(() => {
                window.location.href = `${url}/vendors`;
            }, 500);
        }
        show_Toaster(res.data.message, res.data.type);
        $(this).find("button[type='submit']").prop('disabled', false);
    }).catch(err => {
        Object.values(err.response.data.errors).map(item => {
            show_Toaster(item[0], 'error');
        })
        $(this).find("button[type='submit']").prop('disabled', false);
    })
});

// forgot password

$('#forgot-password').on('submit', function (e) {
    e.preventDefault();
    $(this).find("button[type='submit']").prop('disabled', true);
    axios.post(`${url}/vendors/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}/vendors/change_password`, formData).then(res => {
        if (res.data.type === 'success') {
            setTimeout(() => {
                window.location.href = `${url}/vendors`;
            }, 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);
    })
});

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

$('#profile').on('submit', function (e) {
    e.preventDefault();
    $(this).find("button[type='submit']").prop('disabled', true);
    axios.post(`${url}/vendors/update_profile`, new FormData(this)).then(res => {
        show_Toaster(res.data.message, res.data.type);
        $(this).find("button[type='submit']").removeAttr('disabled');
    }).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']").removeAttr('disabled');
    })
});


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

    $(this).html('Please Wait...');
    const formData = new FormData();
    var id  = $(this).attr('data-id');
    formData.append('id', id);
    axios.post(`${url}/vendors/request_review_for_delete`,formData).then(res => {

        show_Toaster(res.data.message, res.data.type);
        if(res.data.type == 'success'){
            // change label
            $(`#span-${id}`).html('Under Review');
            $(`#span-${id}`).removeClass('badge-success');
            $(`#span-${id}`).addClass('badge-warning');

            // remove button
            $(this).remove();
        }

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

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

$("#addProduct").on('submit', function (e) {
    e.preventDefault();
    $('.submit').prop('disabled', true).html('Please Wait');
    axios.post(`/vendors/insertProduct`, new FormData(this)).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 (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}/vendors/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}/vendors/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}/vendors/updateProduct`, new FormData(this)).then(res => {
        if (res.data.status == 'success') {
            setTimeout(() => {
                window.location.href = `${url}/vendors/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}/vendors/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');
            })
        }
    })
}
