a = false;

$(document).ready(function () {
    $("#btn_savee").click(function () {
        if (a == false) {
            saveperform();
        }
    });

    // GST preview
    function calcGST() {
        var sale = parseFloat($('#sale_rate').val()) || 0;
        var gst = parseFloat($('#gst_pct').val()) || 0;
        var total = sale + (sale * gst / 100);
        $('#sale_incl_gst').text('₹ ' + total.toFixed(2));
    }
    $('#sale_rate, #gst_pct').on('input', calcGST);
    calcGST();
});

function saveperform() {
    var product_name = $('#product_name').val();
    var category_id  = $('#category_id').val();
    var unit_id      = $('#unit_id').val();
    var purchase_rate = $('#purchase_rate').val();
    var sale_rate    = $('#sale_rate').val();
    var id           = $('#id').val();

    if (product_name == "" || category_id == "" || unit_id == "" || purchase_rate == "" || sale_rate == "") {
        showProAlert('error', 'Error', 'Please Enter Required Fields');
        return;
    }

    if (id > 0) {
        a = true;
        var formData = new FormData($("#Form")[0]);
        $.ajax({
            url: base_path + "product/updatedata",
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
            beforeSend: function () {
                $('#btn_savee').prop('disabled', true).html('<i class="fa fa-spinner"></i> Loading');
            },
            success: function () {
                $('#btn_savee').html('<i class="fa fa-check-circle"></i> Save').prop('disabled', false);
                showProAlert('success', 'Success', 'Data Updated Successfully').then(function () {
                    window.location.href = base_path + "product/index";
                });
            }
        });
    } else {
        var formData = new FormData($("#Form")[0]);
        $.ajax({
            url: base_path + "product/insert",
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
            beforeSend: function () {
                $('#btn_savee').prop('disabled', true).html('<i class="fa fa-spinner"></i> Loading');
            },
            success: function () {
                $("#Form")[0].reset();
                $('#btn_savee').html('<i class="fa fa-check-circle"></i> Save').prop('disabled', false);
                showProAlert('success', 'Success', 'Data Submitted Successfully').then(function () {
                    window.location.href = base_path + "product/index";
                });
                a = false;
            }
        });
    }
}
