const zoom = () => $(".pan").pan();

const customRound = v => {
    let dec = (v % 1) * 100;   // decimal in 0–99 range
    return dec >= 50 ? Math.ceil(v) : v.toFixed(2);
};

(function () {
    $("#sale_invoice_date, #sale_entry_date").datepicker({
        format: 'dd-mm-yyyy',
        todayHighlight: true,
    });
    disable_enable_background(false)
    calculateTotals();
    calculate_final_total_for_trans();
}());

$(document).ready(function() {
    const urlParams = new URLSearchParams(window.location.search);
    const action = urlParams.get('action');

    if (action === 'add') {
        // show Import button completely
        $("a.btn[onclick='import_diamond_stock()']").show();

        // enable Add customer button
        $(".add-diamond-btn").prop('disabled', false).css('pointer-events', 'auto').show();
    }else if (action === 'edit') {
        // hide or disable Add customer button
        $(".add-diamond-btn").not(".hsn-code-btn, .stock-btn")
            .prop('disabled', true)
            .css({
                'pointer-events': 'none',
                'opacity': '0.5',
                'cursor': 'not-allowed'
            })
            .attr('title', 'Disabled in edit mode');
    }

    $("#cust_id").on("change", function () {
        let selectedCustomer = $(this).val();

        // Set same value in shipping dropdown
        $("#shipping_id").val(selectedCustomer);

        // If flexselect or any custom dropdown UI is used, trigger change for UI refresh
        $("#shipping_id").trigger("change");

        if (action === 'add') {
            if (selectedCustomer != '') {
                $.ajax({
                    url: base_url + 'sales/salesctrl/get_account_days',
                    type: "POST",
                    data: { account_id: selectedCustomer },
                    dataType: "json",
                    success: function (response) {
                        if (response.status == true) {
                            $("#sale_terms_of_delivery").val(response.acc_days);
                        }
                    }
                });
            }
        }
    });
});


    function calculateTotals() {
        let totalRate = 0, totalDollarAmt = 0, totalQty = 0, totalCGST = 0, totalSGST = 0, totalIGST = 0, totalAmount = 0;

        $('input[name="st_pc_amt[]"]').each(function(){
            totalRate += parseFloat($(this).val()) || 0;
        });

        $('input[name="st_dollar_amt[]"]').each(function(){
            totalDollarAmt += parseFloat($(this).val()) || 0;
        });

        $('input[name="st_carat[]"]').each(function(){
            totalQty += parseFloat($(this).val()) || 0;
        });

        $('input[name="st_cgst_total[]"]').each(function(){
            totalCGST += parseFloat($(this).val()) || 0;
        });

        $('input[name="st_sgst_total[]"]').each(function(){
            totalSGST += parseFloat($(this).val()) || 0;
        });

        $('input[name="st_igst_total[]"]').each(function(){
            totalIGST += parseFloat($(this).val()) || 0;
        });

        $('input[name="st_total[]"]').each(function(){
            totalAmount += parseFloat($(this).val()) || 0;
        });

        let totalPriceCt = totalRate / totalQty;
        if(isNaN(totalPriceCt)) totalPriceCt = 0;

        let totalDollarCt = totalDollarAmt / totalQty;
        if(isNaN(totalDollarCt)) totalDollarCt = 0;

        $('#total_price_ct').val(totalPriceCt.toFixed(2));
        $('#total_rate_price').val(totalRate.toFixed(2));
        $('#total_dollar_ct').val(totalDollarCt.toFixed(2));
        $('#total_dollar_amt').val(totalDollarAmt.toFixed(2));
        $('#total_qty_pcs').val(totalQty.toFixed(2));
        $('#total_cgst').val(totalCGST.toFixed(2));
        $('#total_sgst').val(totalSGST.toFixed(2));
        $('#total_igst').val(totalIGST.toFixed(2));
        $('#total_amount').val(totalAmount.toFixed(2));
    }



var l = window.location;
var base_url = l.protocol + "//" + l.host + "/" + l.pathname.split('/')[1];
base_url += '/';

// var duplicate    = [];
var st_cnt      = 1;

function get_diamond_data(dm_id) {
    let cust_id = $("#cust_id").val();
    if (cust_id == 0) {
        $("#dm_id").val(0);
        $("#dm_id_flexselect").val("PLEASE SELECT");
        $("#cust_id").css({'border-color':'red'});
        display_alert('err','Please select customer name first!!!');
        $("body, html").animate({'scrollTop':0},1000);
        return false;
    } else {
        $("#cust_id").css({'border-color':'#000'});
    }

    let current_dollar_rate = $("#sale_current_dollar_rate").val();
    if (current_dollar_rate == 0) {
        $("#dm_id").val(0);
        $("#sale_current_dollar_rate").css({'border-color':'red'});
        display_alert('err','Please enter current dollar rate!!!');
        $("body, html").animate({'scrollTop':0},1000);
        return false;
    } else {
        $("#sale_current_dollar_rate").css({'border-color':'#000'});
    }

    if (dm_id != 0) {
        var path = base_url+"sales/salesctrl/get_diamond_data/"+dm_id+'/'+cust_id;
        ajaxCall('POST', path, '', 'JSON', resp => {
            
            let pending_stock = resp['dm_stock_in'] - resp['dm_stock_out'];
            
            // --- Diamond Details ---
            $("#dm_id").val(resp['dm_id']);
            $("#dm_sh").val(resp['dm_sh']);
            $("#dm_wt").val(resp['dm_wt']);
            $("#dm_col").val(resp['dm_col']);
            $("#dm_cla").val(resp['dm_cla']);
            $("#dm_cut").val(resp['dm_cut']);
            $("#dm_pol").val(resp['dm_pol']);
            $("#dm_sym").val(resp['dm_sym']);
            $("#dm_fl").val(resp['dm_fl']);
            $("#dm_lab").val(resp['dm_lab']);
            $("#dm_disc").val(resp['dm_disc']).removeAttr('readonly');
            $("#dm_rap").val(resp['dm_rap'] || 0);
            $("#dm_dollar").val(resp['dm_dollar']);
            $("#dm_cert_no").val(resp['dm_cert_no']);
            // $("#dm_carat").val(resp['dm_carat']);
            $("#carat_bal").html(pending_stock);

            // Certificate dropdown
            if(resp['dm_lab']=='NON'){
                $("#dm_cert").html('<option value="0">NO</option>');
                $("#dm_cert").val(0);
                $("#dm_cert_flexselect").val('NO');
            } else {
                $("#dm_cert").html('<option value="0">NO</option><option value="1">YES</option>');
                $("#dm_cert").val(0);
                $("#dm_cert_flexselect").val('NO');
            }

            // Notes based on lab
            if(resp['dm_lab']=='IGI') $("#cm_notes").val('FIX PRICE BILL ONLY');
            else if(resp['dm_lab']=='GIA') $("#cm_notes").val('FIX PRICE NET BILL ONLY');
            else $("#cm_notes").val('');

            // --- sales Fields ---
            // $("#pro_rate").val(parseFloat(resp['dm_pc_amt'] || 0));
            $("#pro_qty").val(resp['dm_pcs'] || 1);
            // $("#pro_qty").val(1);
            // $("#pro_cgst_total").val(resp['amt_cgst'] || 0);
            // $("#pro_sgst_total").val(resp['amt_sgst'] || 0);
            // $("#pro_igst_total").val(resp['amt_igst'] || 0);
            // $("#pro_cgst").val(resp['per_cgst'] || 0);
            // $("#pro_sgst").val(resp['per_sgst'] || 0);
            // $("#pro_igst").val(resp['per_igst'] || 0);
            // $("#pro_final_total").val(resp['total_amt'] || resp['dm_pc_amt']);

            // --- Other Table Columns ---
            var pcs = resp['dm_carat'] || '';
            pcs = pcs.replace(/[^0-9.]/g, ''); // numeric only

            let current_dollar_rate = $("#sale_current_dollar_rate").val();
            let st_dollar_ct = resp['dm_price_ct'] / current_dollar_rate;
            let st_dollar_amt = st_dollar_ct * pcs;

            // $("#pro_price_ct").val(customRound(parseFloat(resp['dm_price_ct'] || 0)));
            // $("#pro_dollar_ct").val(resp['dm_dollar']);
            // $("#pro_dollar_ct").val(customRound(parseFloat(st_dollar_ct || 0)));
            // $("#pro_dollar_amt").val(customRound(parseFloat(st_dollar_amt || 0)));
            $("#pro_size").val(resp['dm_size']);
            $("#pro_cpd").val(resp['dm_cpd']);
            $("#pro_video").val(resp['dm_video_link']);
            $("#pro_no_of_days").val(resp['dm_no_of_days']);
            $("#pro_rapnet").val(resp['dm_rapnet']);
            $("#pro_suspense_stock").val(resp['dm_suspense']);
            $("#pro_length").val(resp['dm_len']);
            $("#pro_width").val(resp['dm_wid']);
            $("#pro_height").val(resp['dm_hei']);
            $("#pro_dm_lab_grown").val(resp['dm_nat_lab_grown']);
            $("#acc_type").val(resp['acc_type']);
            $("#user_id").val(resp['user_id']);

            // Trigger calculation for totals
            calculate_sub_total_amt();
            
        }, errmsg => {});
    }
}


function calculate_sub_total_amt()
{
    rate =  $("#pro_rate").val();
    qty = $("#dm_carat").val();

    var sgst = 0;
    var cgst = 0;
    var igst = 0;

    var sub_total = parseFloat(rate);
    if(isNaN(sub_total)) sub_total = 0;

    let pur_with_registered = $("#pur_with_registered_hidden").val();
    if(pur_with_registered == 0){
        if($("#acc_type").val() == 1) // within MH
        {
            sgst = $("#pro_sgst").val();
            cgst = $("#pro_cgst").val();
            igst = 0;
        }
        else if($("#acc_type").val() == 2) // outside MH
        {
            sgst = 0;
            cgst = 0;
            igst = $("#pro_igst").val();
        }
        else
        {
            sgst = 0;
            cgst = 0;
            igst = 0;
        }
    }

    var sgst_amt = (parseFloat(sub_total) * parseFloat(sgst)) / 100;
    if(isNaN(sgst_amt)) sgst_amt = 0;
    $("#pro_sgst_total").val(sgst_amt.toFixed(2));

    var cgst_amt = (parseFloat(sub_total) * parseFloat(cgst)) / 100;
    if(isNaN(cgst_amt)) cgst_amt = 0;
    $("#pro_cgst_total").val(cgst_amt.toFixed(2));

    var igst_amt = (parseFloat(sub_total) * parseFloat(igst)) / 100;
    if(isNaN(igst_amt)) igst_amt = 0;
    $("#pro_igst_total").val(igst_amt.toFixed(2));

    var total_amt = parseFloat(sub_total) + parseFloat(sgst_amt) + parseFloat(cgst_amt) + parseFloat(igst_amt);
    if(isNaN(total_amt)) total_amt = 0;

    $("#pro_sub_total").val(customRound(sub_total));
    $("#pro_final_total").val(customRound(total_amt));
}

function calculate_final_total_for_trans() {

    var total_qty = 0,
        total_rate = 0,
        total_sgst_amt = 0,
        total_cgst_amt = 0,
        total_igst_amt = 0,
        total_sub_amt = 0,
        total_final = 0;

    $("#sales_wrapper tbody tr").each(function() {

        let row = $(this);
        
        // ----------------------
        // GET VALUES
        // ----------------------
        let qty  = parseFloat(row.find('input[name="st_carat[]"]').val()) || 0;
        let rate = parseFloat(row.find('input[name="st_pc_amt[]"]').val()) || 0;

        var sub_total = parseFloat(rate);
        if(isNaN(sub_total)) sub_total = 0;

        let st_cgst = parseFloat(row.find('input[name="st_cgst[]"]').val()) || 0;
        let st_sgst = parseFloat(row.find('input[name="st_sgst[]"]').val()) || 0;
        let st_igst = parseFloat(row.find('input[name="st_igst[]"]').val()) || 0;

        // ----------------------
        // CALCULATE GST AMOUNTS
        // ----------------------
        let sgst_amt = 0, cgst_amt = 0, igst_amt = 0;

        let pur_with_registered = $("#pur_with_registered_hidden").val();

        if (pur_with_registered == 0) { // REGISTERED

            if ($("#acc_type").val() == 1) { // WITHIN MH
                sgst_amt = sub_total * st_sgst / 100;
                cgst_amt = sub_total * st_cgst / 100;
                igst_amt = 0;
            }
            else if ($("#acc_type").val() == 2) { // OUTSIDE MH
                sgst_amt = 0;
                cgst_amt = 0;
                igst_amt = sub_total * st_igst / 100;
            }
        }

        // SET ROW TOTALS
        row.find('input[name="st_sgst_total[]"]').val(sgst_amt.toFixed(2));
        row.find('input[name="st_cgst_total[]"]').val(cgst_amt.toFixed(2));
        row.find('input[name="st_igst_total[]"]').val(igst_amt.toFixed(2));

        let final = sub_total + sgst_amt + cgst_amt + igst_amt;

        row.find('input[name="st_total[]"]').val(customRound(final));

        // ----------------------
        // ADD TO TOTALS
        // ----------------------
        total_qty       += qty;
        total_rate      += rate;
        total_sgst_amt  += sgst_amt;
        total_cgst_amt  += cgst_amt;
        total_igst_amt  += igst_amt;
        total_sub_amt   += sub_total;
        total_final     += final;
    });

    // ----------------------
    // SET FOOTER TOTALS
    // ----------------------
    $("#total_qty").val(customRound(total_qty));
    $("#total_rate").val(customRound(total_rate));
    $("#total_per_sgst").val(total_sgst_amt.toFixed(2));
    $("#total_per_cgst").val(total_cgst_amt.toFixed(2));
    $("#total_per_igst").val(total_igst_amt.toFixed(2));
    $("#sub_total").val(customRound(total_sub_amt));
    $("#final_total").val(customRound(total_final));
}

function add_sales_trans_row(id)
{
    var check = 1;

    // var selectedDmCode = $("#dm_id option:selected").text().trim(); // or $("#dm_code").val().trim()
    // var duplicateFound = false;

    // Loop through all existing st_dm_code[] inputs
    // $("input[name='st_dm_code[]']").each(function() {
    //     if ($(this).val().trim().toUpperCase() === selectedDmCode.toUpperCase()) {
    //         duplicateFound = true;
    //         return false; // stop loop if found
    //     }
    // });

    // if (duplicateFound) {
    //     alert("This diamond code already exists in the list!");
    //     return; // stop row insertion
    // }

    if($("#dm_id").val() == 0)
    {
        $("#dm_id_flexselect").css({'border-color':'red'});
        $("#dm_id_flexselect").addClass('shake');
        $('#dm_id_flexselect').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e)
        {
            $('#dm_id_flexselect').delay(200).removeClass('shake');
        });
        check = 0;
    }
    else
    {
        $("#dm_id_flexselect").css({'border-color':'#757575'});
    }

    if($("#cust_id").val() == 0)
    {
        $("#cust_id").css({'border-color':'red'});
        check = 0;
    }
    else
    {
        $("#cust_id").css({'border-color':'#000'});
    }

    const caratBal   = $("#carat_bal").text();  // USE text()
    let dm_carat          = parseFloat($("#dm_carat").val()) || 0;
    
    if (dm_carat > caratBal) {
        $("#dm_carat").val(caratBal);
        $("#dm_carat").css({'border-color':'red'});
        display_alert('err','Cannot exceed the balance Carat!!!');
        $("body, html").animate({'scrollTop':0},1000);
        return false;
    } else {
        $("#dm_carat").css({'border-color':'#000'});
    }
    let carat_balance = caratBal;
    // let carat_balance = caratBal - dm_carat;

    // if($("#acc_type").val() == 1)//within MH
    // {
    //     if($("#pro_igst").val() > 0 || $("#pro_igst_total").val() > 0)
    //     {
    //         alert("Select customer again")
    //         $("#cust_id").css({'border-color':'red'});
    //         check = 0;
    //     }
    //     else
    //     {
    //         $("#cust_id").css({'border-color':'#000'});
    //     }
    // }

    // if($("#sm_acc_type").val() == 2)//outside MH
    // {
    //     if($("#pro_sgst").val() > 0 || $("#pro_sgst_total").val() > 0 || $("#pro_cgst").val() > 0 || $("#pro_cgst_total").val() > 0)
    //     {
    //         alert("Select customer again")
    //         $("#cust_id").css({'border-color':'red'});
    //         check = 0;
    //     }
    //     else
    //     {
    //         $("#cust_id").css({'border-color':'#000'});
    //     }
    // }

    if($("#pro_final_total").val() <= 0)
    {
        $("#pro_final_total").css({'border-color':'red'});
        check = 0;
    }
    else
    {
        $("#pro_final_total").css({'border-color':'#000'});
    }

    if(check == 0)
    {
        var msg = 'Oh snap ! You forgot to enter some information';
        display_alert('err',msg);
        $("body, html").animate({'scrollTop':0},1000);
    }
    else
    {
        // var check_dupli_item = 0;
        if (id != 0) {
    var total_tr = $('#sales_wrapper tr').length;

    for (var i = 2; i <= total_tr; i++) {
        let rowId = $('#sales_wrapper tr:nth-child(' + i + ')').attr('id');
        if (rowId && rowId.includes("_")) {
            let cnt = rowId.split("_").pop();
            let item_id = $("#st_dm_id_" + cnt).val();
            // if (item_id && duplicate.indexOf(item_id) < 0) {
            //     duplicate.push(item_id);
            // }
        }
    }
}

        var item_id      = $("#dm_id").val();
    //     for (var i = 0; i <= duplicate.length; i++)
    //     {
    //         if(duplicate.indexOf(item_id) > -1)
    //         {
    //             check_dupli_item = 1;
    //         }
    //     }

    //     if(check_dupli_item == 1)
    //     {
    //         alert("Duplicate Item Found");
    //     }
    //    else {
    // duplicate.push(item_id);

    var data = '<tr id="rowid_'+st_cnt+'">';

    // Hidden fields
    data += '<input type="hidden" name="st_id[]" value="0"/>'; 
    data += '<input type="hidden" name="st_user_id[]" value="'+$("#user_id").val()+'"/>'; // replace with actual user id input if available

    // Fetch all values from form
    let pur_with_registered = $("#pur_with_registered_hidden").val();
    if (pur_with_registered == 0) {
        var with_registered_sty = '';
    } else {
        var with_registered_sty = 'style="display:none;"';
    }

    var dm_code = $("#dm_id option:selected").text();
    var dm_id = item_id;
    var hsn_code = $("#hsn_id option:selected").text();
    var hsn_id = $("#hsn_id").val();
    var price_ct = $("#pro_price_ct").val();
    var dollar = $("#pro_dollar_ct").val();
    var dollar_amt = $("#pro_dollar_amt").val();
    var size = $("#pro_size").val();
    var cpd = $("#pro_cpd").val();
    var dm_sh = $("#dm_sh").val();
    var dm_lab = $("#dm_lab").val();
    var cert_no = $("#dm_cert_no").val();
    var carat = $("#dm_carat").val();
    var dm_col = $("#dm_col").val();
    var dm_cla = $("#dm_cla").val();
    var dm_cut = $("#dm_cut").val();
    var dm_pol = $("#dm_pol").val();
    var dm_sym = $("#dm_sym").val();
    var dm_fl = $("#dm_fl").val();
    var length = $("#pro_length").val();
    var width = $("#pro_width").val();
    var height = $("#pro_height").val();
    var lab_grown = $("#pro_dm_lab_grown").val();
    var disc = $("#dm_disc").val();
    var rap = $("#dm_rap").val();
    var video = $("#pro_video").val();
    var status = 0;
    var no_of_days = $("#pro_no_of_days").val();
    var rapnet = $("#pro_rapnet").val();
    var suspense_stock = $("#pro_suspense_stock").val();
    var pro_rate = $("#pro_rate").val();
    var pcs = $("#pro_qty").val();
    var cgst = $("#pro_cgst").val();
    var sgst = $("#pro_sgst").val();
    var igst = $("#pro_igst").val();
    var cgst_total = $("#pro_cgst_total").val();
    var sgst_total = $("#pro_sgst_total").val();
    var igst_total = $("#pro_igst_total").val();
    var sub_total = $("#pro_sub_total").val();
    var total_amt = $("#pro_final_total").val();
    var date = $("#current_date").val(); // add actual date field
    var user_id = $("#user_id").val();

    // Columns aligned as sale your snippet
    data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_date[]" value="'+date+'" readonly>';

    data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_balance_stock[]" value="'+carat_balance+'" readonly>';

    data += '<td><input class="form-control floating-input floating-input1" name="st_hsn_code[]" value="'+hsn_code+'" readonly></td>';
    data += '<input type="hidden" name="st_hsn_id[]" id="st_hsn_id" value="'+hsn_id+'"/>';

    data += '<td><input class="form-control floating-input floating-input1 text-Uppercase" name="st_dm_code[]" value="'+dm_code+'" readonly/>';
    data += '<input type="hidden" name="st_dm_id[]" value="'+dm_id+'"/></td>';

    data += '<td><input type="number" class="form-control floating-input floating-input1" name="st_carat[]" value="'+carat+'" oninput="calculatePriceFields('+st_cnt+', \'carat\')" readonly></td>';

    data += '<td><input type="number" class="form-control floating-input floating-input1" name="st_price_ct[]" value="'+price_ct+'" oninput="calculatePriceFields('+st_cnt+', \'price_ct\')" readonly></td>';

    // Rate
    data += '<td><input type="number" class="form-control no-edit floating-input floating-input1" name="st_pc_amt[]" value="'+pro_rate+'" oninput="calculatePriceFields('+st_cnt+', \'pc_amt\')" readonly></td>';

    data += '<td><input type="number" class="form-control floating-input floating-input1" name="st_dollar[]" value="'+dollar+'" oninput="calculatePriceFields('+st_cnt+', \'dollar_ct\')" readonly></td>';

    data += '<td><input type="number" class="form-control no-edit floating-input floating-input1" name="st_dollar_amt[]" value="'+dollar_amt+'" oninput="calculatePriceFields('+st_cnt+', \'dollar_amt\')" readonly></td>';

    data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_size[]" value="'+size+'" readonly></td>';

    data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_pcs[]" value="'+pcs+'" readonly></td>';

    data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_cpd[]" value="'+cpd+'" readonly></td>';
    data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_dm_sh[]" value="'+dm_sh+'" readonly></td>';
    data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_lab[]" value="'+dm_lab+'" readonly></td>';
    data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_cert_no[]" value="'+cert_no+'" readonly></td>';

    data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_dm_col[]" value="'+dm_col+'" readonly></td>';
    data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_dm_cla[]" value="'+dm_cla+'" readonly></td>';
    data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_dm_cut[]" value="'+dm_cut+'" readonly></td>';
    data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_dm_pol[]" value="'+dm_pol+'" readonly></td>';
    data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_dm_sym[]" value="'+dm_sym+'" readonly></td>';
    data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_dm_fl[]" value="'+dm_fl+'" readonly></td>';
    data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_length[]" value="'+length+'" readonly></td>';
    data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_width[]" value="'+width+'" readonly></td>';
    data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_height[]" value="'+height+'" readonly></td>';
    data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_dm_lab[]" value="'+lab_grown+'" readonly></td>';
    data += '<td><input type="number" class="form-control floating-input floating-input1" name="st_disc[]" value="'+disc+'" readonly></td>';
    data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_rap[]" value="'+rap+'" readonly></td>';
    data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_video[]" value="'+video+'" readonly></td>';
    data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_status[]" value="'+status+'" readonly>';
    data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_uploaded_date[]" value="'+date+'" readonly>';
    data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_no_of_days[]" value="'+no_of_days+'" readonly></td>';
    data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_rapnet[]" value="'+rapnet+'" readonly></td>';
    data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_suspense_stock[]" value="'+suspense_stock+'" readonly></td>';

    // GST & Total
    data += '<td class="gst_block" '+with_registered_sty+'><input class="form-control floating-input floating-input1" name="st_cgst_total[]" value="'+cgst_total+'" readonly>';
    data += '<input type="hidden" name="st_cgst[]" value="'+cgst+'"></td>';

    data += '<td class="gst_block" '+with_registered_sty+'><input class="form-control floating-input floating-input1" name="st_sgst_total[]" value="'+sgst_total+'" readonly>';
    data += '<input type="hidden" name="st_sgst[]" value="'+sgst+'"></td>';

    data += '<td class="gst_block" '+with_registered_sty+'><input class="form-control floating-input floating-input1" name="st_igst_total[]" value="'+igst_total+'" readonly>';
    data += '<input type="hidden" name="st_igst[]" value="'+igst+'"></td>';

    // data += '<input type="hidden" name="st_cgst_total[]" value="0">';
    // data += '<input type="hidden" name="st_cgst[]" value="0">';
    // data += '<input type="hidden" name="st_sgst_total[]" value="0">';
    // data += '<input type="hidden" name="st_sgst[]" value="0">';
    // data += '<input type="hidden" name="st_igst_total[]" value="0">';
    // data += '<input type="hidden" name="st_igst[]" value="0">';

    // Subtotal & Total
    data += '<td><input type="hidden" name="st_sub_total[]" value="'+sub_total+'">';
    data += '<input class="form-control floating-input floating-input1" name="st_total[]" value="'+total_amt+'" readonly></td>';

    // Delete

    data += '<td class="sticky-col sticky-edit">';
            data += '<button type="button" class="edit-btn-premium edit-row" onclick="toggleEditRow('+st_cnt+')">';
                data += '<i class="glyphicon glyphicon-pencil"></i>';
            data += '</button>';
        data += '</td>';

    data += '<td class="sticky-col sticky-remove"><a href="javascript:void(0)" class="remove-btn-premium" onclick="remove_sales_row('+st_cnt+')">';
    data += '<i class="glyphicon glyphicon-trash" style="margin-top:3px;"></i></a></td>';

    data += '</tr>';

    st_cnt++;
    $("#sales_wrapper").append(data);
    calculate_final_total_for_trans();
    updateGrandTotals();

    // Reset all sales form fields safely
    $("#pre_id, #dm_id, #hsn_id, #dm_sh, #dm_wt, #dm_col, #dm_cla, #dm_cut, #dm_pol, #dm_sym, #dm_fl, #dm_lab, #dm_code, #cert_no, #carat, #length, #width, #height, #video, #status, #uploaded_date, #no_of_days, #rapnet, #suspense_stock, #disc, #rap, #price_ct, #dm_rap, #dm_disc, #pro_dm_lab_grown, #pro_height, #pro_width, #pro_length, #dm_carat, #dm_cert_no, #pro_cpd, #pro_size, #pro_dollar_amt, #pro_dollar_ct, #pro_price_ct, #pro_video, #dollar, #pro_no_of_days, #pro_rapnet, #pro_suspense_stock, #dollar_amt, #size, #cpd, #pro_rate, #pro_qty, #pro_cgst, #pro_sgst, #pro_igst, #pro_cgst_total, #pro_sgst_total, #pro_igst_total, #pro_sub_total, #pro_final_total")
        .val("")                     // clear normal inputs
        .trigger("change");          // refresh UI for inputs

    $("#carat_bal").text('0');

    $("#hsn_id, #dm_id, #pre_id")
        .val("0")
        .trigger("change.select2");


    // HSN flexselect
    $("#hsn_id").val("0");                      // reset hidden select
    $("#hsn_id_flexselect").val("PLEASE SELECT"); // reset visible input
    $("#hsn_id_flexselect").trigger("change");

    // DM ID flexselect (same logic)
    $("#dm_id").val("0");
    $("#dm_id_flexselect").val("PLEASE SELECT");
    $("#dm_id_flexselect").trigger("change");

    // }

    }
}

function remove_sales_row(cnt)
{
    $("#rowid_"+cnt).detach();
   calculate_final_total_for_trans();
   updateGrandTotals();
}

function add_invoice(id)
{
    disable_enable_background(false);

    var check = 1;

    // List of required fields
    var fields = ['#sale_no', '#sale_entry_date', '#cust_id'];

    // Loop through and validate
    fields.forEach(function(field) {
        var $el = $(field);
        if ($el.val() == '' || $el.val() == '0') {
            $el.css({'border-color': 'red'});
            check = 0;
        } else {
            $el.css({'border-color': '#ccc'});
        }
    });


    // ---- STOCK VALIDATION FOR ALL ROWS ----
let exceededStocks = []; // store details of exceeded stocks

$("tr[id^='rowid_']").each(function () {

    let row = this;
    let caratInput = row.querySelector('input[name="st_carat[]"]');
    let dmCodeInput = row.querySelector('input[name="st_dm_code[]"]');

    if (!caratInput || !dmCodeInput) return;

    let dmCode = dmCodeInput.value.trim();
    let enteredCarat = parseFloat(caratInput.value) || 0;

    if (dmCode === "") return; // skip empty rows

    // get balance stock (SYNC AJAX)
    let balanceStock = 0;

    $.ajax({
        url: base_url + 'sales/salesctrl/get_balance_stock',
        type: 'POST',
        data: { dm_code: dmCode },
        dataType: 'json',
        async: false,
        success: function (res) {
            // use balance_list if your get_balance_stock returns all DM codes
            if(res['balance_list'] && res['balance_list'][dmCode] !== undefined){
                balanceStock = parseFloat(res['balance_list'][dmCode]) || 0;
            } else if(res['balance'] !== undefined){
                balanceStock = parseFloat(res['balance']) || 0;
            }
        }
    });

    // get total carat used by this DM code in all rows
    let totalUsed = getTotalUsedCarat(dmCode);

    // if exceeds
    if (totalUsed > balanceStock) {
        let allowed = balanceStock - (totalUsed - enteredCarat); // remaining possible
        if(allowed < 0) allowed = 0;

        caratInput.value = allowed;
        caratInput.style.borderColor = 'red';

        // save exceeded stock info
        exceededStocks.push({
            dm_code: dmCode,
            total_used: totalUsed.toFixed(2),
            balance: balanceStock.toFixed(2)
        });
    } 
    else {
        caratInput.style.borderColor = '#ccc';
    }
});

// if any stock exceeded, stop submit and display details
if (exceededStocks.length > 0) {
    let msg = '<b>Stock Exceeded!</b><br><br>';
    exceededStocks.forEach(item => {
        msg += 'DM Code: <b>' + item.dm_code + '</b><br>';
        msg += 'Total Used: <b>' + item.total_used + '</b><br>';
        msg += 'Balance Available: <b>' + item.balance + '</b><br><br>';
    });
    display_alert('err', msg);
    $("body, html").animate({ scrollTop: 0 }, 1000);
    return false;
}

// ---- END STOCK VALIDATION ----


    if (check == 0) {
        display_alert('err', 'Oh snap! You forgot to enter some information');
        $('html, body').animate({ scrollTop: 0 }, 1000);
        return false;
    } 
    else {

        var path = base_url+"sales/salesctrl/sales_insert/"+id;
        // var form_data = $("#sales_form").serialize();
        var form_data = new FormData($("#sales_form")[0]);

        $.ajax({
        type:'post',
        url:path,
        data:form_data,
        dataType:'json',
        contentType: false,   // required
        processData: false,   // required
        cache: false,
        success:function(resp)
                
        {
            console.log(resp);
            if(resp['flag'] == 1)
            {
                if(id == 0)
                {
                    var msg = 'sales created successfully!';
                    display_alert('succ',msg);
                    $("#sales_form")[0].reset();
                    $("body, html").animate({'scrollTop':0},2000);
                    window.location.reload();
                    // window.open(base_url+"sales/salesctrl/sales_master?action=print&id="+resp['last_id'],'_blank','width=1024, height=768');
                }
                else
                {
                    var msg = 'sales updated successfully!';
                    display_alert('succ',msg);
                    $("body, html").animate({'scrollTop':0},2000);
                    window.location.reload();
                }
            }
            else if(resp['flag'] == 2)
            {
                var msg = 'This sales already Exist!';
                display_alert('err',msg);
                $("body, html").animate({'scrollTop':0},1000);
            }
            else
            {
                var msg = 'Database Error ! Please try again letter';
                display_alert('warn',msg);
                $("body, html").animate({'scrollTop':0},1000);
            }
        },function(errmsg)
            {
                console.log(errmsg)
            }
        });
    }
}

function delete_sales(id)
{
    var ans = confirm("Are you sure? You want to delete item.");

        if(ans == true)
        {
            var update_path = base_url+"sales/salesctrl/delete_sales/"+id;

            ajaxCall('POST',update_path,'','',resp =>
            {
                if(resp == 2)
                    {
                        alert("You can not delete this item!");
                    }
                    else
                    {
                        window.location.reload();
                    }

            },
            errmsg =>
            {});
        }
}

// Open popup and load diamond data
function add_update_diamond_popup(dm_id) {

     let cust_id = $("#cust_id").val();
        if(cust_id == 0)
        {
            $("#dm_id").val(0);
    		$("#dm_id_flexselect").val("PLEASE SELECT");

            $("#cust_id").css({'border-color':'red'});
            var msg = 'Please select customer name first!!!';
            display_alert('err',msg);
            $("body, html").animate({'scrollTop':0},1000);
            return false;
        }
        else
        {
            $("#cust_id").css({'border-color':'#000'});
        }

        let current_dollar_rate = $("#sale_current_dollar_rate").val();
        if (current_dollar_rate == 0) {
            $("#dm_id").val(0);
            $("#sale_current_dollar_rate").css({'border-color':'red'});
            display_alert('err','Please enter current dollar rate!!!');
            $("body, html").animate({'scrollTop':0},1000);
            return false;
        } else {
            $("#sale_current_dollar_rate").css({'border-color':'#000'});
        }

        let data = `
         <!-- Diamond Alerts -->
        <div id="diamond_alert" style="display:none;"></div>

        <form class="form-horizontal" id="diamond_form" autocomplete="off">
            <div class="alert_msg_popup"></div>

            <div class="form-group floating-form row">
                <div class="col-md-6 floating-label">
                    <select id="rg_dm_category" name="rg_dm_category" class="form-control floating-select">
                        <option value="0">NON-CERTIFIED</option>
                        <option value="1">CERTIFIED</option>
                    </select>
                    <label>CATEGORY</label>
                </div>

                <input type="hidden" class="form-control floating-input" name="rg_dm_dollar_rate" id="rg_dm_dollar_rate" value="${current_dollar_rate}">
                
                <div class="col-md-6 floating-label">
                    <input type="date" class="form-control floating-input" name="rg_dm_date" id="rg_dm_date" value="">
                    <label for="rg_dm_date">Date</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_location" id="rg_dm_location" value="">
                    <label for="rg_dm_location">Location</label>
                </div>


                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_code" id="rg_dm_code" value="">
                    <label for="rg_dm_code">STOCK ID / CERTIFICATE ID <span style="color:red;">*</span></label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_dna" id="rg_dm_dna" value="">
                    <label for="rg_dm_dna">DNA</label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="number" step="0.01" class="form-control floating-input" name="rg_dm_carat" id="rg_dm_carat" onkeyup="calculate_diamond_popup_fields('carat')" value="">
                    <label>Carat <span style="color:red;">*</span></label>
                </div>
                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_ppc" id="rg_dm_ppc" onkeyup="calculate_diamond_popup_fields('price_ct')" value="">
                    <label>PRICE/CT</label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="number" step="0.01" class="form-control floating-input" name="rg_dm_pc_amt" id="rg_dm_pc_amt" onkeyup="calculate_diamond_popup_fields('pc_amt')" value="" readonly>
                    <label>PC Amt</label>
                </div>
                <div class="col-md-6 floating-label">
                    <input type="number" step="0.01" class="form-control floating-input" name="rg_dm_dollar" id="rg_dm_dollar" onkeyup="calculate_diamond_popup_fields('dollar_ct')" value="">
                    <label>DOLLAR/CT</label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="number" step="0.01" class="form-control floating-input" name="rg_dm_dollar_amt" id="rg_dm_dollar_amt" onkeyup="calculate_diamond_popup_fields('dollar_amt')" value="" readonly>
                    <label>Dollar Amt</label>
                </div>

                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_size" id="rg_dm_size" value="">
                    <label>Size</label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="number" class="form-control floating-input" name="rg_dm_pcs" id="rg_dm_pcs" value="">
                    <label>Pcs</label>
                </div>
                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_cpd" id="rg_dm_cpd" value="">
                    <label>CPD</label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_sh" id="rg_dm_sh" value="">
                    <label>Shape</label>
                </div>
                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_lab" id="rg_dm_lab" value="">
                    <label>Lab</label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_cert_no" id="rg_dm_cert_no" value="">
                    <label>Cert No</label>
                </div>
                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_col" id="rg_dm_col" value="">
                    <label>Col</label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_cla" id="rg_dm_cla" value="">
                    <label>Clar.</label>
                </div>
                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_cut" id="rg_dm_cut" value="">
                    <label>Cut</label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_pol" id="rg_dm_pol" value="">
                    <label>Pol</label>
                </div>
                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_sym" id="rg_dm_sym" value="">
                    <label>Sym</label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_fl" id="rg_dm_fl" value="">
                    <label>Flur.</label>
                </div>
                <div class="col-md-6 floating-label">
                    <input type="number" step="0.01" class="form-control floating-input" name="rg_dm_len" id="rg_dm_len" value="">
                    <label>Length</label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="number" step="0.01" class="form-control floating-input" name="rg_dm_wid" id="rg_dm_wid" value="">
                    <label>Width</label>
                </div>
                <div class="col-md-6 floating-label">
                    <input type="number" step="0.01" class="form-control floating-input" name="rg_dm_hei" id="rg_dm_hei" value="">
                    <label>Height</label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="number" step="0.01" class="form-control floating-input" name="rg_dm_nat_lab_grown" id="rg_dm_nat_lab_grown" value="">
                    <label>NAT/LAB GROWN</label>
                </div>
                <div class="col-md-6 floating-label">
                    <input type="number" step="0.01" class="form-control floating-input" name="rg_dm_disc" id="rg_dm_disc" value="">
                    <label>Disc</label>
                </div>
                
                <div class="col-md-6 floating-label">
                    <input type="number" step="0.01" class="form-control floating-input" name="rg_dm_rap" id="rg_dm_rap" value="">
                    <label>Rap</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="number" step="0.01" class="form-control floating-input" name="rg_dm_rap_dollar" id="rg_dm_rap_dollar" value="">
                    <label>Rap dollar</label>
                </div>



                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="number" class="form-control floating-input" name="rg_dm_tbl" id="rg_dm_tbl" value="">
                    <label for="rg_dm_tbl">Tbl</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="number" class="form-control floating-input" name="rg_dm_td_percentage" id="rg_dm_td_percentage" value="">
                    <label for="rg_dm_td_percentage">TD %</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_l_w" id="rg_dm_l_w" value="">
                    <label for="rg_dm_l_w">L:W</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_bic" id="rg_dm_bic" value="">
                    <label for="rg_dm_bic">BIC</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_bis" id="rg_dm_bis" value="">
                    <label for="rg_dm_bis">BIS</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_wic" id="rg_dm_wic" value="">
                    <label for="rg_dm_wic">WIC</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_col_tinge" id="rg_dm_col_tinge" value="">
                    <label for="rg_dm_col_tinge">Col Tinge</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_lus" id="rg_dm_lus" value="">
                    <label for="rg_dm_lus">Lus</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_remarks" id="rg_dm_remarks" value="">
                    <label for="rg_dm_remarks">Remarks</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_h_a" id="rg_dm_h_a" value="">
                    <label for="rg_dm_h_a">H&A</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_girdle" id="rg_dm_girdle" value="">
                    <label for="rg_dm_girdle">Girdle</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="number" class="form-control floating-input" name="rg_dm_girdle_percentage" id="rg_dm_girdle_percentage" value="">
                    <label for="rg_dm_girdle_percentage">Girdle %</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="number" class="form-control floating-input" name="rg_dm_girdle_cond" id="rg_dm_girdle_cond" value="">
                    <label for="rg_dm_girdle_cond">Girdle Cond</label>
                </div>

                 <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_ca" id="rg_dm_ca" value="">
                    <label for="rg_dm_ca">CA</label>
                </div>

                 <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_ch" id="rg_dm_ch" value="">
                    <label for="rg_dm_ch">CH</label>
                </div>

                 <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="number" class="form-control floating-input" name="rg_dm_pa" id="rg_dm_pa" value="">
                    <label for="rg_dm_pa">PA</label>
                </div>
                 <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="number" class="form-control floating-input" name="rg_dm_pd" id="rg_dm_pd" value="">
                    <label for="rg_dm_pd">PD</label>
                </div>
                 <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="number" class="form-control floating-input" name="rg_dm_str_ln" id="rg_dm_str_ln" value="">
                    <label for="rg_dm_str_ln">Str Ln</label>
                </div>
                 <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="number" class="form-control floating-input" name="rg_dm_lr_half" id="rg_dm_lr_half" value="">
                    <label for="rg_dm_lr_half">Lr Half</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_culet" id="rg_dm_culet" value="">
                    <label for="rg_dm_culet">CULET</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_kts" id="rg_dm_kts" value="">
                    <label for="rg_dm_kts">KTS</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_rep_com" id="rg_dm_rep_com" value="">
                    <label for="rg_dm_rep_com">Rep Com</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="date" class="form-control floating-input" name="rg_dm_cert_date" id="rg_dm_cert_date" value="">
                    <label for="rg_dm_cert_date">Cert Date</label>
                </div>



                <div class="col-md-6 floating-label">
                    <input type="text" class="form-control floating-input" name="rg_dm_video_link" id="rg_dm_video_link" value="">
                    <label>Video Link</label>
                </div>


                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_image_link" id="rg_dm_image_link" value="">
                    <label for="rg_dm_image_link">Image Link</label>
                </div>

                <div class="col-md-6 floating-label cert-field" style="display:none;">
                    <input type="text" class="form-control floating-input" name="rg_dm_certificate_link" id="rg_dm_certificate_link" value="">
                    <label for="rg_dm_certificate_link">Certificate Link</label>
                </div>


            </div>

            <input type="hidden" name="rg_dm_id" id="rg_dm_id" value="${dm_id}">
        </form>
        `;

        $(".modal-body").html(data);

        let sbt_btn = `
            <button type="button" form="diamond_form" class="btn btn-success" onclick="save_diamond(${dm_id})">Save</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        `;

        calculate_sub_total_amt();

        $(".modal-title").html(dm_id == 0 ? "Add Diamond" : "Update Diamond");
        $(".modal-footer").html(sbt_btn);
        $("#popup_modal_lg").modal("show");


        // On change, show/hide certified fields
        $(document).on("change", "#rg_dm_category", function () {
            let val = $(this).val();

            if (val == "1") {
                $(".cert-field").show();
            } else {
                $(".cert-field").hide();
            }
        });

}
 
// Save diamond AJAX
function save_diamond(dm_id, event) {
    if (event) event.preventDefault();

    const form = document.getElementById("diamond_form");
    const formData = new FormData(form);

    // ✅ Validate stock_id before saving
    const stock_id = $("#rg_dm_code").val().trim();
    if (stock_id === "") {
        diamond_alert("err", "Please enter Stock ID!");
        $("#rg_dm_code").css("border-color", "red").focus();
        return false;
    } else {
        $("#rg_dm_code").css("border-color", "#ccc");
    }

    const carat = $("#rg_dm_carat").val().trim();
    if (carat === "") {
        diamond_alert("err", "Please enter Carat!");
        $("#rg_dm_carat").css("border-color", "red").focus();
        return false;
    } else {
        $("#rg_dm_carat").css("border-color", "#ccc");
    }

    $.ajax({
        url: base_url + "sales/salesctrl/insert_diamond/" + dm_id,
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        dataType: "json",
        success: function(resp) {
            $("#popup_modal_lg").animate({'scrollTop': 0},1000);
            if (resp.status === "success") {
                // Show success message
                diamond_alert("succ", resp.message || "Diamond saved successfully!");

                // Close the popup
                $("#popup_modal_lg").modal("hide");

                if (resp.new_dm_id && resp.new_dm_code) {
                    const $dropdown = $("#dm_id");

                    // Append new option if it doesn't exist
                    if ($dropdown.find("option[value='" + resp.new_dm_id + "']").length === 0) {
                        $dropdown.append(
                            $('<option>', {
                                value: resp.new_dm_id,
                                text: resp.new_dm_code
                            })
                        );
                    }

                    // Select the new diamond
                    $dropdown.val(resp.new_dm_id);

                    // Trigger your existing change handler
                    $dropdown.trigger('change');   // This will call get_diamond_data automatically

                    // Reinitialize Flexselect if used
                    if ($.fn.flexselect) {
                        $dropdown.flexselect();
                    }
                }
            } else {
                diamond_alert("err", resp.message || "Something went wrong!");
            }
        },
        error: function(xhr, status, error) {
            console.error("AJAX Error:", status, error, xhr.responseText);
            diamond_alert("err", "Server error while saving diamond!");
        }
    });
}

function diamond_alert(type, msg) {
    const alertBox = document.getElementById("diamond_alert");

    let alertClass = (type === "succ") ? "alert-success" : "alert-danger";

    alertBox.innerHTML = `
        <div class="alert ${alertClass} alert-dismissible show" role="alert" style="padding:10px; margin-bottom:10px; font-size:14px;">
            ${msg}
        </div>
    `;
    alertBox.style.display = "block";

    // Auto-hide after 3 seconds
    setTimeout(() => {
        $(alertBox).fadeOut(500, function () {
            $(this).html("").show(); // clear message, keep ready for next
        });
    }, 3000);
}

/********************************* HSN Master *********************************/

// Open popup and load HSN data
function add_update_hsn_popup(hsn_id = 0) {

    let data = `
        <div id="hsn_alert" style="display:none;"></div>

        <form class="form-horizontal" id="hsn_form" autocomplete="off">
            <div class="alert_msg_popup"></div>

            <div class="form-group floating-form row">

                <div class="col-12 col-sm-12 col-md-4 col-lg-4 floating-label">
                        <input type="text" class="form-control floating-input" name="hsn_code" id="hsn_code" placeholder=" " /> 
                        <label class="text-Uppercase">HSN Code</label>
                        <small class="form-text text-muted helper-text" id="hsn_code_msg"></small>
                      </div>

                 <div class="col-12 col-sm-12 col-md-4 col-lg-4 floating-label">
                        <input 
                            type="number" 
                            class="form-control floating-input" 
                            id="hsn_sgst_per" 
                            name="hsn_sgst_per" 
                            value="0.00"
                            onkeyup="calculate_gst()" 
                            placeholder=" " 
                            autocomplete="off"  
                        />   
                        <label class="text-Uppercase">sgst per</label>
                        <small class="form-text text-muted helper-text" id="hsn_sgst_per_msg"></small>
                      </div>
                      <div class="col-12 col-sm-12 col-md-4 col-lg-4 floating-label">
                        <input 
                          type="number" 
                          class="form-control floating-input" 
                          id="hsn_cgst_per" 
                          name="hsn_cgst_per" 
                          value="0.00"
                          readonly
                        />   
                        <label class="text-Uppercase">cgst per</label>
                        <small class="form-text text-muted helper-text" id="hsn_cgst_per_msg"></small>
                      </div>
                      <div class="col-12 col-sm-12 col-md-4 col-lg-4 floating-label">
                        <input 
                          type="number" 
                          class="form-control floating-input" 
                          id="hsn_igst_per" 
                          name="hsn_igst_per" 
                          value="0.00"
                          readonly
                        />   
                        <label class="text-Uppercase">igst per</label>
                        <small class="form-text text-muted helper-text" id="hsn_igst_per_msg"></small>
                      </div>
            </div>
        </form>
    `;

    $(".modal-body-sm").html(data);

    let sbt_btn = `
        <button type="button" class="btn btn-success" onclick="add_hsn(${hsn_id}, event)">Save</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    `;

    $(".modal-title-sm").html(hsn_id == 0 ? "Add HSN" : "Update HSN");
    $(".modal-footer-sm").html(sbt_btn);
    $("#popup_modal_sm").modal("show");
}

// Save HSN
function add_hsn(hsn_id = 0, event) {
    if (event) event.preventDefault();

    const hsnCode = $("#hsn_code").val().trim();

    if (hsnCode === "") {
        hsn_alert("err", "Please enter HSN Code!");
        $("#hsn_code").css("border-color", "red").focus();
        return false;
    } else {
        $("#hsn_code").css("border-color", "#ccc");
    }

    const path = base_url + "master/masterctrl/hsn_insert/" + hsn_id;
    const form_data = $("#hsn_form").serialize();

    $.ajax({
        url: path,
        type: "POST",
        data: form_data,
        dataType: "json",
        success: function(resp) {
            if (resp.status === "success") {
                hsn_alert("succ", hsn_id == 0 ? "HSN successfully added!" : "HSN successfully updated!");

                // If new, reset and scroll top
                if (hsn_id == 0) {
                    $("#hsn_form")[0].reset();
                    $("#popup_modal_sm").animate({ scrollTop: 0 }, 800);
                }

                // Run only on sales_master page
                if (window.location.href.indexOf("sales/salesctrl/sales_master") !== -1) {
                    $("#popup_modal_sm").modal("hide");

                    if (resp.new_hsn_id && resp.new_hsn_code) {
                        const $dropdown = $("#hsn_id");

                        // Append new option if it doesn't exist
                        if ($dropdown.find("option[value='" + resp.new_hsn_id + "']").length === 0) {
                            $dropdown.append(
                                $("<option>", {
                                    value: resp.new_hsn_id,
                                    text: resp.new_hsn_code
                                })
                            );
                        }

                        // Select the new HSN
                        $dropdown.val(resp.new_hsn_id);
                        $dropdown.trigger("change");

                        // Reinitialize Flexselect if used
                        if ($.fn.flexselect) {
                            $dropdown.flexselect();
                        }
                    }
                }

            } else if (resp.status === "exists") {
                hsn_alert("err", "HSN Code already exists!");

            } else {
                hsn_alert("warn", "Database Error! Please try again later.");
            }
        },
        error: function(xhr, status, error) {
            console.error("AJAX Error:", status, error, xhr.responseText);
            hsn_alert("err", "Server error while saving HSN!");
        }
    });
}

// Reusable alert for HSN popup
function hsn_alert(type, msg) {
    const alertBox = document.getElementById("hsn_alert");

    let alertClass = (type === "succ") ? "alert-success" : (type === "warn") ? "alert-warning" : "alert-danger";

    alertBox.innerHTML = `
        <div class="alert ${alertClass} alert-dismissible show" role="alert" style="padding:10px; margin-bottom:10px; font-size:14px;">
            ${msg}
        </div>
    `;
    alertBox.style.display = "block";

    // Auto-hide after 3 seconds
    setTimeout(() => {
        $(alertBox).fadeOut(500, function () {
            $(this).html("").show();
        });
    }, 3000);
}

const calculate_gst = () => {
        let sgst_per = $("#hsn_sgst_per").val();
        let igst_per = parseFloat(sgst_per) * 2;
        if (isNaN(igst_per) || igst_per == "") igst_per = 0;
        $("#hsn_cgst_per").val(sgst_per);
        $("#hsn_igst_per").val(igst_per);
    };

/********************************* /HSN Master *********************************/

$('#hsn_id').on('change', function () {
    let hsn_id = $(this).val();

    if (hsn_id && hsn_id != '0') {
        $.ajax({
            url: base_url + 'sales/salesctrl/get_hsn_data/' + hsn_id,
            type: 'GET',
            dataType: 'json',
            success: function (resp) {
                if (resp.status === 'success' && resp.data) {
                    $('#pro_cgst').val(resp.data.cgst);
                    $('#pro_sgst').val(resp.data.sgst);
                    $('#pro_igst').val(resp.data.igst);
                } else {
                    $('#pro_cgst, #pro_sgst, #pro_igst').val('');
                }
            },
            error: function () {
                $('#pro_cgst, #pro_sgst, #pro_igst').val('');
            }
        });
    } else {
        $('#pro_cgst, #pro_sgst, #pro_igst').val('');
    }
});





 function import_diamond_stock()
    {
        let cust_id = $("#cust_id").val();
        if(cust_id == 0)
        {
            $("#cust_id").css({'border-color':'red'});
            var msg = 'Please select customer name first!!!';
            display_alert('err',msg);
            $("body, html").animate({'scrollTop':0},1000);
            return false;
        }
        else
        {
            $("#cust_id").css({'border-color':'#000'});
        }

        let current_dollar_rate = $("#sale_current_dollar_rate").val();
        if (current_dollar_rate == 0) {
            $("#dm_id").val(0);
            $("#sale_current_dollar_rate").css({'border-color':'red'});
            display_alert('err','Please enter current dollar rate!!!');
            $("body, html").animate({'scrollTop':0},1000);
            return false;
        } else {
            $("#sale_current_dollar_rate").css({'border-color':'#000'});
        }

        var data = '';
        data += '<div class="alert_msg_popup"></div>';
        data += '<div class="row">';
        data += '<div class="col-md-12">'
        data += '<form class="form-horizontal" id="diamond_form">';

        data += '<div class="form-group">';
        data += '<label for="inputEmail3" class="col-sm-3 control-label">*.xlxs (Only)</label>';
        data += '<div class="col-sm-6">';
        data += '<input type="file" class="form-control" name="diamond_import" id="diamond_import" value="" autocomplete="off" onchange="is_excel(this)">';
        data += '</div>';
        data += '</div>';

        data += '<div class="form-group">';
        data += '<div class="col-sm-10 col-sm-offset-1">';
        data += '<table class="table table-responsive" id="set_imported_result">';
        data += '</table>';
        data += '</div>';
        data += '</div>';

        data += '</form>';
        data += '</div>';
        data += '</div>';

        $(".modal-body-sm").html(data);

        var sbt_btn = '<button type="button" class="btn btn-default" onClick="reload_page();" data-dismiss="modal">Close</button>';

       sbt_btn += `<button type="button" class="btn btn-success" onClick="add_diamond(0, ${cust_id})">Submit</button>`;

        $(".modal-title-sm").html("Add Diamond");
        $(".modal-footer-sm").html(sbt_btn);
        $("#popup_modal_sm").modal('show');
    }

    // function is_excel
    function is_excel(element)
    {

        var element_id = "#"+element.id;
        var excelPath  = $(element_id)[0].value;
        var extn = excelPath.substring(excelPath.lastIndexOf('.') + 1).toLowerCase();
        if (extn == "xlx" || extn == "xlsx")
        {
            if (typeof (FileReader) != "undefined")
            {

            }
            else
            {
                alert("This browser does not custort FileReader.");
            }
        }
        else
        {
            alert("Pls select only excel");
            $(element_id).val('');
        }
    }


function add_diamond(id, cust_id)
{
    var check = 1;
    if($("#diamond_import").val() == '')
    {
        $("#diamond_import").css({'border-color':'red'}).addClass('shake');
        $('#diamond_import').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e){
            $('#diamond_import').delay(200).removeClass('shake');
        });
        check = 0;
    }
    else
    {
        $("#diamond_import").css({'border-color':'#CCC'});
    }

    if(check == 0)
    {
        display_alert_popup('err','Oh snap ! You forgot to enter some information');
        $("body, html").animate({'scrollTop':0},1000);
        return;
    }

    var form_id = document.getElementById('diamond_form');
    var form_data = new FormData(form_id);
    var path = base_url+"sales/salesctrl/import_diamond/"+cust_id;

    fileUpAjaxCall('POST', path, form_data, 'JSON', resp => {

        if (resp['resp'] == 0) {
            alert(resp['msg']);  
            return;
        }

        $("#popup_modal_sm").modal("hide");

        if(resp['resp'] == 1)
        {
            display_alert_popup('succ','Successfully imported!');
            $("#diamond_import").val('');

            let current_dollar_rate = $("#sale_current_dollar_rate").val();

            if(resp['imported_data'] && resp['imported_data'].length > 0)
            {
               resp['imported_data'].forEach((row) => {

    // if(duplicate.indexOf(row['st_dm_code']) === -1){
        // duplicate.push(row['st_dm_code']);

        var pcs = row['st_carat'] || '';
        pcs = pcs.replace(/[^0-9.]/g, ''); // numeric only

        let st_dollar_ct = row['st_price_ct'] / current_dollar_rate;
        let st_dollar_amt = st_dollar_ct * pcs;

        var data = '<tr id="rowid_'+st_cnt+'">';

        data += '<input type="hidden" name="st_id[]" value="0"/>'; // For transaction update
        data += '<input type="hidden" name="st_user_id[]" value="'+row['st_user_id']+'"/>'; 
       
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_date[]" value="'+(row['st_date'] || '')+'" readonly>';

        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_balance_stock[]" value="'+(row['st_balance_stock'] || '')+'" readonly>';

        data += '<td><input class="form-control floating-input floating-input1" name="st_hsn_code[]" value="'+(row['st_hsn_code'] || '')+'" readonly></td>';
        data += '<input type="hidden" name="st_hsn_id[]" id="st_hsn_id" value="'+(row['st_hsn_id'] || '')+'"/>';

        data += '<td><input class="form-control floating-input floating-input1 text-Uppercase" name="st_dm_code[]" value="'+row['st_dm_code']+'" readonly/>';
        data += '<input type="hidden" name="st_dm_id[]" value="'+row['st_dm_id']+'"/></td>';

        data += '<td><input type="number" class="form-control floating-input floating-input1" name="st_carat[]" value="'+(pcs || '')+'" oninput="calculatePriceFields('+st_cnt+', \'carat\')" readonly></td>';

        data += '<td><input type="number" class="form-control floating-input floating-input1" name="st_price_ct[]" value="'+ customRound(parseFloat(row['st_price_ct'] || 0)) +'" oninput="calculatePriceFields('+st_cnt+', \'price_ct\')" readonly></td>';

        // Rate
        data += '<td><input type="number" class="form-control no-edit floating-input floating-input1" name="st_pc_amt[]" value="'+ customRound(parseFloat(row['st_pc_amt'] || 0)) +'" oninput="calculatePriceFields('+st_cnt+', \'pc_amt\')" readonly></td>';

        data += '<td><input type="number" class="form-control floating-input floating-input1" name="st_dollar[]" value="'+ customRound(parseFloat(row['st_dollar'] || 0)) +'" oninput="calculatePriceFields('+st_cnt+', \'dollar_ct\')" readonly></td>';

        data += '<td><input type="number" class="form-control no-edit floating-input floating-input1" name="st_dollar_amt[]" value="'+ customRound(parseFloat(row['st_dollar_amt'] || 0)) +'" oninput="calculatePriceFields('+st_cnt+', \'dollar_amt\')" readonly></td>';

        data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_size[]" value="'+(row['st_size'] || '')+'" readonly></td>';

        data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_pcs[]" value="'+(row['st_pcs'] || '')+'" readonly></td>';

        data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_cpd[]" value="'+(row['st_cpd'] || '')+'" readonly></td>';
        data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_dm_sh[]" value="'+(row['st_dm_sh'] || '')+'" readonly></td>';
        data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_lab[]" value="'+(row['st_lab'] || '')+'" readonly></td>';
        data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_cert_no[]" value="'+(row['st_cert_no'] || '')+'" readonly></td>';

        data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_dm_col[]" value="'+(row['st_dm_col'] || '')+'" readonly></td>';
        data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_dm_cla[]" value="'+(row['st_dm_cla'] || '')+'" readonly></td>';
        data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_dm_cut[]" value="'+(row['st_dm_cut'] || '')+'" readonly></td>';
        data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_dm_pol[]" value="'+(row['st_dm_pol'] || '')+'" readonly></td>';
        data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_dm_sym[]" value="'+(row['st_dm_sym'] || '')+'" readonly></td>';
        data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_dm_fl[]" value="'+(row['st_dm_fl'] || '')+'" readonly></td>';
        data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_length[]" value="'+(row['st_length'] || '')+'" readonly></td>';
        data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_width[]" value="'+(row['st_width'] || '')+'" readonly></td>';
        data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_height[]" value="'+(row['st_height'] || '')+'" readonly></td>';
        data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_dm_lab[]" value="'+(row['st_dm_lab'] || '')+'" readonly></td>';
        data += '<td><input type="number" class="form-control floating-input floating-input1" name="st_disc[]" value="'+(row['st_disc'] || '')+'" readonly></td>';
        data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_rap[]" value="'+(row['st_rap'] || '')+'" readonly></td>';
        data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_video[]" value="'+(row['st_video'] || '')+'" readonly></td>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_status[]" value="'+(row['st_status'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_uploaded_date[]" value="'+(row['st_uploaded_date'] || '')+'" readonly>';
        data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_no_of_days[]" value="'+(row['st_no_of_days'] || '')+'" readonly></td>';
        data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_rapnet[]" value="'+(row['st_rapnet'] || '')+'" readonly></td>';
        data += '<td><input type="text" class="form-control floating-input floating-input1" name="st_suspense_stock[]" value="'+(row['st_suspense_stock'] || '')+'" readonly></td>';




        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_location[]" value="'+(row['st_location'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_dna[]" value="'+(row['st_dna'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_rap_dollar[]" value="'+(row['st_rap_dollar'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_tbl[]" value="'+(row['st_tbl'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_td_percentage[]" value="'+(row['st_td_percentage'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_l_w[]" value="'+(row['st_l_w'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_bic[]" value="'+(row['st_bic'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_bis[]" value="'+(row['st_bis'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_wic[]" value="'+(row['st_wic'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_col_tinge[]" value="'+(row['st_col_tinge'] || '')+'" readonly>';
         data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_lus[]" value="'+(row['st_lus'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_remarks[]" value="'+(row['st_remarks'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_h_a[]" value="'+(row['st_h_a'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_girdle[]" value="'+(row['st_girdle'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_girdle_percentage[]" value="'+(row['st_girdle_percentage'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_girdle_cond[]" value="'+(row['st_girdle_cond'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_ca[]" value="'+(row['st_ca'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_ch[]" value="'+(row['st_ch'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_pa[]" value="'+(row['st_pa'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_pd[]" value="'+(row['st_pd'] || '')+'" readonly>';
         data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_str_ln[]" value="'+(row['st_str_ln'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_lr_half[]" value="'+(row['st_lr_half'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_dm_culet[]" value="'+(row['st_dm_culet'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_kts[]" value="'+(row['st_kts'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_rep_com[]" value="'+(row['st_rep_com'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_cert_date[]" value="'+(row['st_cert_date'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_image_link[]" value="'+(row['st_image_link'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_certificate_link[]" value="'+(row['st_certificate_link'] || '')+'" readonly>';
        data += '<input type="hidden" class="form-control floating-input floating-input1" name="st_category[]" value="'+(row['st_category'] || '')+'" readonly>';



        let pur_with_registered = $("#pur_with_registered_hidden").val();
        var with_registered_sty = 'style="display:none;"';
        let st_cgst_total      = 0;
        let st_cgst            = 0;
        let st_sgst_total      = 0;
        let st_sgst            = 0;
        let st_igst_total      = 0;
        let st_igst            = 0;
        if(pur_with_registered == 0){
            with_registered_sty = '';

            st_cgst_total      = (parseFloat(row['st_amt_cgst'] || 0).toFixed(2));
            st_cgst            = (parseFloat(row['st_cgst'] || 0).toFixed(2));
            st_sgst_total      = (parseFloat(row['st_amt_sgst'] || 0).toFixed(2));
            st_sgst            = (parseFloat(row['st_sgst'] || 0).toFixed(2));
            st_igst_total      = (parseFloat(row['st_amt_igst'] || 0).toFixed(2));
            st_igst            = (parseFloat(row['st_igst'] || 0).toFixed(2));
            
        }
        // GST & Total
        data += '<td class="gst_block" '+with_registered_sty+'><input type="number" class="form-control floating-input floating-input1" name="st_cgst_total[]" value="'+st_cgst_total+'" readonly>';
        data += '<input type="hidden" name="st_cgst[]" value="'+st_cgst+'"></td>';

        data += '<td class="gst_block" '+with_registered_sty+'><input type="number" class="form-control floating-input floating-input1" name="st_sgst_total[]" value="'+st_sgst_total+'" readonly>';
        data += '<input type="hidden" name="st_sgst[]" value="'+st_sgst+'"></td>';

        data += '<td class="gst_block" '+with_registered_sty+'><input type="number" class="form-control floating-input floating-input1" name="st_igst_total[]" value="'+st_igst_total+'" readonly>';
        data += '<input type="hidden" name="st_igst[]" value="'+st_igst+'"></td>';

        // data += '<input type="hidden" name="st_cgst_total[]" value="0">';
        // data += '<input type="hidden" name="st_cgst[]" value="0">';
        // data += '<input type="hidden" name="st_sgst_total[]" value="0">';
        // data += '<input type="hidden" name="st_sgst[]" value="0">';
        // data += '<input type="hidden" name="st_igst_total[]" value="0">';
        // data += '<input type="hidden" name="st_igst[]" value="0">';

        // Subtotal & Total
        let pc_amt  = parseFloat(row['st_pc_amt'] || 0);
        let cgst    = parseFloat(st_cgst_total || 0);
        let sgst    = parseFloat(st_sgst_total || 0);
        let igst    = parseFloat(st_igst_total || 0);

        // Correct total calculation
        let total_amt = pc_amt + cgst + sgst + igst;
        let sub_total = customRound(parseFloat(row['st_pc_amt'] || 0));

        data += '<td><input type="hidden" name="st_sub_total[]" value="'+sub_total+'">';
        data += '<input class="form-control floating-input floating-input1" name="st_total[]" value="'+customRound(parseFloat(total_amt || 0))+'" readonly></td>';

        data += '<td class="sticky-col sticky-edit">';
            data += '<button type="button" class="edit-btn-premium edit-row" onclick="toggleEditRow('+st_cnt+')">';
                data += '<i class="glyphicon glyphicon-pencil"></i>';
            data += '</button>';
        data += '</td>';

        data += '<td class="sticky-col sticky-remove"><a href="javascript:void(0)" class="remove-btn-premium" onclick="remove_sales_row('+st_cnt+')">';
        data += '<i class="glyphicon glyphicon-trash" style="margin-top:3px;"></i></a></td>';

        data += '</tr>';

        $("#sales_wrapper").append(data);
        st_cnt++;
    // }
});

                calculateTotals();
                calculate_sub_total_amt();
                // calculate_final_total_for_trans();
                updateGrandTotals();
            }

            // Show summary
            var total_count = parseInt(resp['add_cnt']) + parseInt(resp['edit_cnt']) + parseInt(resp['not_add_cnt']);
            $("#set_imported_result").html(
                `<tr>
                    <th>NEW ADDED</th><th>EXISTING UPDATED</th><th>NOT ADDED</th><th>TOTAL COUNT</th>
                 </tr>
                 <tr>
                    <td>${resp['add_cnt']}</td>
                    <td>${resp['edit_cnt']}</td>
                    <td>${resp['not_add_cnt']}</td>
                    <td>${total_count}</td>
                 </tr>`
            );
        }
        else if(resp['resp'] == 2)
        {
            display_alert_popup('err','No data in excel file');
        }
        else
        {
            display_alert_popup('warn','Unknown Error ! Please try again later');
        }

    }, errmsg => {});
}

// function toggleEditRow(rowId) {
//     let row = document.getElementById('rowid_' + rowId);
//     let editBtn = row.querySelector('.edit-row');

//     if (!row.classList.contains('editing')) {
//         // Make editable (skip .no-edit)
//         row.querySelectorAll('input[type="text"]:not(.no-edit)').forEach(input => input.removeAttribute('readonly'));
//         row.querySelectorAll('input[type="number"]:not(.no-edit)').forEach(input => input.removeAttribute('readonly'));

//         row.classList.add('editing');
//         editBtn.innerHTML = '<i class="glyphicon glyphicon-ok"></i> Save';

//         // Change button style to green for Save
//         editBtn.style.background = '#28a745'; // Bootstrap green
//         editBtn.style.color = '#ffffff';
//     } else {
//         // Make read-only again
//         row.querySelectorAll('input[type="text"]:not(.no-edit)').forEach(input => input.setAttribute('readonly', true));
//         row.querySelectorAll('input[type="number"]:not(.no-edit)').forEach(input => input.setAttribute('readonly', true));

//         row.classList.remove('editing');
//         editBtn.innerHTML = '<i class="glyphicon glyphicon-pencil"></i>';

//         // Revert button style to original color
//         editBtn.style.background = '#19305e';
//         editBtn.style.color = '#ffffff';
//     }
//     updateGrandTotals();
// }

function toggleEditRow(rowId) {
    let row = document.getElementById('rowid_' + rowId);
    let editBtn = row.querySelector('.edit-row');

    if (!row.classList.contains('editing')) {

        // 🔓 Make editable (except calculated fields)
        row.querySelectorAll('input[type="text"]:not(.no-edit), input[type="number"]:not(.no-edit)')
            .forEach(input => input.removeAttribute('readonly'));

        // ✅ Mark row as editing
        row.classList.add('editing');

        // ✏ Change button to Save
        editBtn.innerHTML = '<i class="glyphicon glyphicon-ok"></i> Save';
        editBtn.style.background = '#28a745';
        editBtn.style.color = '#ffffff';

        // 🌟 Optional: highlight row while editing
        row.style.backgroundColor = '#fff8e1';

    } else {

        // 🔒 Lock fields again
        row.querySelectorAll('input[type="text"]:not(.no-edit), input[type="number"]:not(.no-edit)')
            .forEach(input => input.setAttribute('readonly', true));

        // ❌ Remove edit mode flag
        row.classList.remove('editing');

        // 🔄 Restore button
        editBtn.innerHTML = '<i class="glyphicon glyphicon-pencil"></i>';
        editBtn.style.background = '#19305e';
        editBtn.style.color = '#ffffff';

        // Remove highlight
        row.style.backgroundColor = '';
    }

    updateGrandTotals();
}

function calculateRowTotal(rowId) {
    let row = document.getElementById('rowid_' + rowId);
   
    if (!row) return;

    let rate = parseFloat(row.querySelector('input[name="st_pc_amt[]"]').value) || 0;
    let qty = parseFloat(row.querySelector('input[name="st_carat[]"]').value) || 0;

    let cgst = parseFloat(row.querySelector('input[name="st_cgst[]"]').value) || 0;
    let sgst = parseFloat(row.querySelector('input[name="st_sgst[]"]').value) || 0;
    let igst = parseFloat(row.querySelector('input[name="st_igst[]"]').value) || 0;
// alert(cgst);
    // let sub_total = rate * qty;
    let sub_total = rate;

    let cgst_total = (sub_total * cgst) / 100;
    let sgst_total = (sub_total * sgst) / 100;
    let igst_total = (sub_total * igst) / 100;

    let total_amt = sub_total + cgst_total + sgst_total + igst_total;

    // Update totals
    row.querySelector('input[name="st_cgst_total[]"]').value = cgst_total.toFixed(2);
    row.querySelector('input[name="st_sgst_total[]"]').value = sgst_total.toFixed(2);
    row.querySelector('input[name="st_igst_total[]"]').value = igst_total.toFixed(2);
    row.querySelector('input[name="st_total[]"]').value = customRound(total_amt);

    updateGrandTotals();
    // calculatePriceFields(rowId);
}
function updateGrandTotals() {
    let total_rate = 0, total_dollar_amt = 0, total_qty = 0, total_cgst = 0, total_sgst = 0, total_igst = 0, total_amt = 0;

    document.querySelectorAll('#sales_wrapper tbody tr').forEach(row => {
        let rate = parseFloat(row.querySelector('input[name="st_pc_amt[]"]').value) || 0;
        let dollar_amt = parseFloat(row.querySelector('input[name="st_dollar_amt[]"]').value) || 0;
        let qty = parseFloat(row.querySelector('input[name="st_carat[]"]').value) || 0;
        let cgst_total = parseFloat(row.querySelector('input[name="st_cgst_total[]"]').value) || 0;
        let sgst_total = parseFloat(row.querySelector('input[name="st_sgst_total[]"]').value) || 0;
        let igst_total = parseFloat(row.querySelector('input[name="st_igst_total[]"]').value) || 0;
        let total = parseFloat(row.querySelector('input[name="st_total[]"]').value) || 0;

        total_rate += rate;
        total_dollar_amt += dollar_amt;
        total_qty += qty;
        total_cgst += cgst_total;
        total_sgst += sgst_total;
        total_igst += igst_total;
        total_amt += total;  
    });

    let total_price_ct  = total_qty > 0 ? (total_rate / total_qty) : 0;
    let total_dollar_ct = total_qty > 0 ? (total_dollar_amt / total_qty) : 0;

    document.getElementById('total_price_ct').value = total_price_ct.toFixed(2);
    document.getElementById('total_rate_price').value = total_rate.toFixed(2);
    document.getElementById('total_dollar_ct').value = total_dollar_ct.toFixed(2);
    document.getElementById('total_dollar_amt').value = total_dollar_amt.toFixed(2);
    document.getElementById('total_qty_pcs').value = total_qty.toFixed(2);
    document.getElementById('total_cgst').value = total_cgst.toFixed(2);
    document.getElementById('total_sgst').value = total_sgst.toFixed(2);
    document.getElementById('total_igst').value = total_igst.toFixed(2);
    document.getElementById('total_amount').value = total_amt.toFixed(2);
}

 function calculate_diamond_popup_fields(changedField = '') {
    let current_dollar_rate = $("#sale_current_dollar_rate").val();
    if (current_dollar_rate == 0) {
        $("#sale_current_dollar_rate").css({'border-color':'red'});
        display_alert('err','Please enter current dollar rate!!!');
        $("body, html").animate({'scrollTop':0},1000);
        return false;
    } else {
        $("#sale_current_dollar_rate").css({'border-color':'#000'});
    }

    let pcs          = parseFloat($("#rg_dm_carat").val()) || 0;
    let price_ct     = parseFloat($("#rg_dm_ppc").val()) || 0;
    let pc_amt       = parseFloat($("#rg_dm_pc_amt").val()) || 0;
    let dollar_ct    = parseFloat($("#rg_dm_dollar").val()) || 0;
    let dollar_amt   = parseFloat($("#rg_dm_dollar_amt").val()) || 0;

    // Prevent divide-by-zero
    if (pcs === 0) pcs = 1;

    // -------------------------
    // PRIORITY CALCULATIONS
    // -------------------------

    if (changedField === 'price_ct') {
        pc_amt     = price_ct * pcs;
        dollar_ct  = price_ct / current_dollar_rate;
        dollar_amt = dollar_ct * pcs;
    }
    if (changedField === 'pc_amt') {
        price_ct   = pc_amt / pcs;
        dollar_ct  = price_ct / current_dollar_rate;
        dollar_amt = dollar_ct * pcs;
    }
    if (changedField === 'dollar_ct') {
        price_ct   = dollar_ct * current_dollar_rate;
        pc_amt     = price_ct * pcs;
        dollar_amt = dollar_ct * pcs;
        
    }
    if (changedField === 'dollar_amt') {
        dollar_ct  = dollar_amt / pcs;
        price_ct   = dollar_ct * current_dollar_rate;
        pc_amt     = price_ct * pcs;
    }
    if (changedField === 'carat') {
        // price_ct   = dollar_ct * current_dollar_rate;
        // dollar_ct  = price_ct / current_dollar_rate;

        pc_amt     = price_ct * pcs;
        dollar_amt = dollar_ct * pcs;
    }

    // --------------------------------------------------
    // UPDATE BACK TO INPUT FIELDS
    // --------------------------------------------------
    if (changedField !== 'price_ct')
        $("#rg_dm_ppc").val(customRound(price_ct));

    if (changedField !== 'pc_amt')
        $("#rg_dm_pc_amt").val(customRound(pc_amt));

    if (changedField !== 'dollar_ct')
        $("#rg_dm_dollar").val(customRound(dollar_ct));

    if (changedField !== 'dollar_amt')
        $("#rg_dm_dollar_amt").val(customRound(dollar_amt));
}

function calculate_single_fields(changedField = '') {

    let cust_id = $("#cust_id").val();
    if(cust_id == 0)
    {
        $("#dm_id").val(0);
        $("#dm_id_flexselect").val("PLEASE SELECT");

        $("#cust_id").css({'border-color':'red'});
        var msg = 'Please select customer name first!!!';
        display_alert('err',msg);
        $("body, html").animate({'scrollTop':0},1000);

        // Reset all sales form fields safely
        $("#pre_id, #dm_id, #dm_id_flexselect, #hsn_id, #hsn_id_flexselect, #dm_sh, #dm_wt, #dm_col, #dm_cla, #dm_cut, #dm_pol, #dm_sym, #dm_fl, #dm_lab, #dm_code, #cert_no, #carat, #length, #width, #height, #video, #status, #uploaded_date, #no_of_days, #rapnet, #suspense_stock, #disc, #rap, #price_ct, #dm_rap, #dm_disc, #pro_dm_lab_grown, #pro_height, #pro_width, #pro_length, #dm_carat, #dm_cert_no, #pro_cpd, #pro_size, #pro_dollar_amt, #pro_dollar_ct, #pro_price_ct, #pro_video, #dollar, #pro_no_of_days, #pro_rapnet, #pro_suspense_stock, #dollar_amt, #size, #cpd, #pro_rate, #pro_qty, #pro_cgst, #pro_sgst, #pro_igst, #pro_cgst_total, #pro_sgst_total, #pro_igst_total, #pro_sub_total, #pro_final_total")
            .val('')                                   // clear value
            .trigger('change.select2')                 // reset select2 dropdowns if any
            .prop('selectedIndex', 0);                 // reset <select> to first option
        return false;
    }
    else
    {    
        $("#cust_id").css({'border-color':'#000'});
    }

    let current_dollar_rate = $("#sale_current_dollar_rate").val();
    if (current_dollar_rate == 0) {
        $("#dm_id").val(0);
        $("#sale_current_dollar_rate").css({'border-color':'red'});
        display_alert('err','Please enter current dollar rate!!!');
        $("body, html").animate({'scrollTop':0},1000);
        return false;
    } else {
        $("#sale_current_dollar_rate").css({'border-color':'#000'});
    }

    const caratBal   = $("#carat_bal").text();  // USE text()
    let pcs          = parseFloat($("#dm_carat").val()) || 0;

    if (pcs > caratBal) {
        $("#dm_carat").val(caratBal);
        $("#dm_carat").css({'border-color':'red'});
        display_alert('err','Cannot exceed the balance Carat!!!');
        $("body, html").animate({'scrollTop':0},1000);
        return false;
    } else {
        $("#dm_carat").css({'border-color':'#000'});
    }

    let price_ct     = parseFloat($("#pro_price_ct").val()) || 0;
    let pc_amt       = parseFloat($("#pro_rate").val()) || 0;
    let dollar_ct    = parseFloat($("#pro_dollar_ct").val()) || 0;
    let dollar_amt   = parseFloat($("#pro_dollar_amt").val()) || 0;

    // Prevent divide-by-zero
    if (pcs === 0) pcs = 1;

    // -------------------------
    // PRIORITY CALCULATIONS
    // -------------------------

    if (changedField === 'price_ct') {
        pc_amt     = price_ct * pcs;
        dollar_ct  = price_ct / current_dollar_rate;
        dollar_amt = dollar_ct * pcs;
    }
    if (changedField === 'pc_amt') {
        price_ct   = pc_amt / pcs;
        dollar_ct  = price_ct / current_dollar_rate;
        dollar_amt = dollar_ct * pcs;
    }
    if (changedField === 'dollar_ct') {
        price_ct   = dollar_ct * current_dollar_rate;
        pc_amt     = price_ct * pcs;
        dollar_amt = dollar_ct * pcs;
        
    }
    if (changedField === 'dollar_amt') {
        dollar_ct  = dollar_amt / pcs;
        price_ct   = dollar_ct * current_dollar_rate;
        pc_amt     = price_ct * pcs;
    }
    if (changedField === 'carat') {
        // price_ct   = dollar_ct * current_dollar_rate;
        // dollar_ct  = price_ct / current_dollar_rate;

        pc_amt     = price_ct * pcs;
        dollar_amt = dollar_ct * pcs;
    }

    // --------------------------------------------------
    // UPDATE BACK TO INPUT FIELDS
    // --------------------------------------------------
    if (changedField !== 'price_ct')
        $("#pro_price_ct").val(customRound(price_ct));

    if (changedField !== 'pc_amt')
        $("#pro_rate").val(customRound(pc_amt));

    if (changedField !== 'dollar_ct')
        $("#pro_dollar_ct").val(customRound(dollar_ct));

    if (changedField !== 'dollar_amt')
        $("#pro_dollar_amt").val(customRound(dollar_amt));

    calculate_sub_total_amt();
}

function calculatePriceFields(rowId, changedField) {

    let row = document.getElementById("rowid_" + rowId);
    if (!row) return;

    // 🚫 STOP if row is not in edit mode
    if (!row.classList.contains("editing")) {
        return;
    }

    let caratInput = row.querySelector('input[name="st_carat[]"]');

    let pcs          = parseFloat(row.querySelector('input[name="st_carat[]"]').value)        || 0;

    let dmCode = row.querySelector('input[name="st_dm_code[]"]').value;

    // AJAX request to get balance stock
    $.ajax({
        url: base_url + 'sales/salesctrl/get_balance_stock', // replace with your actual URL
        type: 'POST',
        data: { dm_code: dmCode },
        dataType: 'json',
        async: false, // synchronous so we have balance before continuing
        success: function(res) {
            let balanceStock = 0;

        // If using balance_list (for multiple DM codes)
        if(res['balance_list'] && res['balance_list'][dmCode] !== undefined){
            balanceStock = parseFloat(res['balance_list'][dmCode]) || 0;
        }
        // fallback if single 'balance' returned
        else if(res['balance'] !== undefined){
            balanceStock = parseFloat(res['balance']) || 0;
        }

        // total carat used in ALL rows for this DM CODE
        let totalUsed = getTotalUsedCarat(dmCode);

        // calculate remaining stock for current row
        let remaining = balanceStock - (totalUsed - pcs); // totalUsed includes current row

        // ensure remaining is never negative
        if(remaining < 0) remaining = 0;

        if(totalUsed > balanceStock){
            caratInput.value = remaining;          // set to max allowed
            caratInput.style.borderColor = 'red';
            display_alert('err', 
                'Exceeded Balance Stock for DM Code: ' + dmCode + 
                '<br>Total Used: ' + totalUsed + 
                '<br>Balance: ' + balanceStock
            );
            $("body, html").animate({ scrollTop: 0 }, 1000);
            pcs = remaining;                        // update pcs variable
        } else {
            caratInput.style.borderColor = '#000';
        }
        }
    });


    // ---------- Convert All Inputs to Numbers ----------
    
    let price_ct     = parseFloat(row.querySelector('input[name="st_price_ct[]"]').value)     || 0;
    let pc_amt       = parseFloat(row.querySelector('input[name="st_pc_amt[]"]').value)       || 0;
    let dollar_ct    = parseFloat(row.querySelector('input[name="st_dollar[]"]').value)       || 0;
    let dollar_amt   = parseFloat(row.querySelector('input[name="st_dollar_amt[]"]').value)   || 0;
    let current_dollar_rate = parseFloat($("#sale_current_dollar_rate").val()) || 0;

    // Prevent divide-by-zero
    if (pcs === 0) pcs = 1;

    // -------------------------
    // PRIORITY CALCULATIONS
    // -------------------------

    if (changedField === 'price_ct') {
        pc_amt     = price_ct * pcs;
        dollar_ct  = price_ct / current_dollar_rate;
        dollar_amt = dollar_ct * pcs;
    }

    if (changedField === 'pc_amt') {
        price_ct   = pc_amt / pcs;
        dollar_ct  = price_ct / current_dollar_rate;
        dollar_amt = dollar_ct * pcs;
    }

    if (changedField === 'dollar_ct') {
        price_ct   = dollar_ct * current_dollar_rate;
        pc_amt     = price_ct * pcs;
        dollar_amt = dollar_ct * pcs;
    }

    if (changedField === 'dollar_amt') {
        dollar_ct  = dollar_amt / pcs;
        price_ct   = dollar_ct * current_dollar_rate;
        pc_amt     = price_ct * pcs;
    }

    if (changedField === 'carat') {
        // price_ct   = dollar_ct * current_dollar_rate;
        // dollar_ct  = price_ct / current_dollar_rate;
        
        pc_amt     = price_ct * pcs;
        dollar_amt = dollar_ct * pcs;
    }

    // -------------------------
    // UPDATE INPUT FIELDS
    // -------------------------
    
    if (changedField !== 'pc_amt')
        row.querySelector('input[name="st_pc_amt[]"]').value = pc_amt.toFixed(2);

    if (changedField !== 'price_ct')
        row.querySelector('input[name="st_price_ct[]"]').value = price_ct.toFixed(2);

    if (changedField == 'dollar_rate'  || changedField == 'dollar_ct') {  // ✅ Skip price calc if rate changed
        if (changedField !== 'dollar_amt')
            row.querySelector('input[name="st_dollar_amt[]"]').value = dollar_amt.toFixed(2);

        if (changedField !== 'dollar_ct')
            row.querySelector('input[name="st_dollar[]"]').value = dollar_ct.toFixed(2);
    }

    // Update Row Totals
    // calculateRowTotal(rowId);
    calculate_final_total_for_trans();
    updateGrandTotals();
}
function calculateDollarRateChange() {
    let rows = document.querySelectorAll('tr.editing'); // only rows in edit mode
    rows.forEach(row => {
        let rowId = row.id.replace('rowid_', '');
        calculatePriceFields(rowId, 'dollar_rate'); // special flag
    });
}

function getTotalUsedCarat(dmCode) {
    let total = 0;

    document.querySelectorAll('tr[id^="rowid_"]').forEach(row => {
        let rowDmCode = row.querySelector('input[name="st_dm_code[]"]').value;
        let carat = parseFloat(row.querySelector('input[name="st_carat[]"]').value) || 0;

        if (rowDmCode === dmCode) total += carat;
    });
    return total;
}



 function add_customer_popup(){

        var data = '';

        var path = base_url+"master/masterctrl/get_account_assets";


        ajaxCall('POST',path,'','JSON',resp =>
        {
            data += '<div class="alert_msg_popup"></div>';
            data += '<div class="row">';
            data += '<div class="col-md-12">';
            data += '<form class="form-horizontal" id="account_form">';
          
            data += '<div class="form-group floating-form">';


            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<input type="text" name="acc_contact" class="form-control floating-input" id="acc_contact" placeholder=" " autocomplete="off">';
           
            data += '<label for="inputEmail3" >customer Name</label>';
          
            data += '</div>'; //col-sm-4

            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<input type="text" name="acc_aumobile" class="form-control floating-input" id="acc_aumobile" placeholder=" " autocomplete="off">';
            
            data += '<label for="inputEmail3" >customer Mobile</label>';
           
            data += '</div>'; //col-sm-4
            data += '</div>'; //form-group

            data += '<div class="form-group floating-form">';
            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<textarea name="acc_address" class="form-control floating-input" id="acc_address" placeholder=" " autocomplete="off"></textarea>';
            data += '<label for="inputEmail3">Address</label>';
            data += '</div>'; //col-sm-4

            data += '<div class="col-sm-2 col-sm-offset-1 floating-label">';
            data += '<select class="form-control floating-select" name="acc_city_id" id="acc_city_id">';
            data += '<option value="0">Please select</option>';
            $.each(resp['city_data'], function(index, value){

            data += '<option value="'+value['city_id']+'">'+value['city_name']+'</option>';
            });
            data += '</select>';
            data += '<label for="inputEmail3">City</label>';
            data += '</div>'; //col-sm-4

            data += '<div class="col-sm-2 floating-label">';
            data += '<select class="form-control floating-select" name="acc_state_id" id="acc_state_id">';
            data += '<option value="0">Please select</option>';
            $.each(resp['state_data'], function(index, value){

            data += '<option value="'+value['state_id']+'">'+value['state_name']+'</option>';
            });
            data += '</select>';
            data += '<label for="inputEmail3">State</label>';
            data += '</div>'; //col-sm-4
            data += '</div>'; //form-group
           
            data += '<div class="form-group floating-form">';
            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<input type="hidden" name="acc_website" id="acc_website">';
            data += '<input type="text" name="acc_ref" class="form-control floating-input" id="acc_ref" placeholder=" " autocomplete="off">';
            data += '<label for="inputEmail3">Refer By</label>';
            data += '</div>'; //col-sm-4

            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<input type="text" name="acc_ref2" class="form-control floating-input" id="acc_ref2" placeholder=" " autocomplete="off">';
            data += '<label for="inputEmail3">Refer By 2</label>';
            data += '</div>';
            data += '</div>'; //col-sm-4

            data += '<div class="form-group floating-form">';
            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<input type="text" name="acc_email" class="form-control floating-input" id="acc_email" placeholder=" " autocomplete="off">';
            data += '<label for="inputEmail3">Email</label>';
            data += '</div>'; //col-sm-4
            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<select class="form-control floating-select" id="acc_status" name="acc_status">';
            data += '<option value="GOOD">GOOD</option>';
            data += '<option value="LIMITED">LIMITED</option>';
            data += '<option value="BLACKLISTED">BLACKLISTED</option>';
            data += '</select>';
           
            data += '</div>'; //col-sm-4
            data += '</div>'; //form-group
            data += '<div class="form-group floating-form">';
            data += '<div class="col-sm-2 col-sm-offset-1 floating-label">';
            data += '<select class="form-control floating-select" id="acc_type" name="acc_type">';
            data += '<option value="0">PLEASE SELECT</option>';
            data += '<option value="1">WITHIN STATE</option>';
            data += '<option value="2">OUTSIDE STATE</option>';
            data += '</select>';
            data += '<label for="inputEmail3">Type<span style="color : red;">*</span></label>';
            data += '</div>'; //col-sm-4

            data += '<div class="col-sm-2 floating-label">';
            data += '<input type="hidden" name="acc_fax" id="acc_fax">';
            data += '<select class="form-control floating-select" id="acc_kyc" name="acc_kyc">';
            data += '<option value="0">NO</option>';
            data += '<option value="1">YES</option>';
            data += '</select>';
            data += '<label for="inputEmail3">KYC</label>';
            data += '</div>'; //col-sm-4



                data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
                data += '<input type="text" name="acc_gst" class="form-control floating-input" id="acc_gst" placeholder=" " autocomplete="off">';
                data += '<label for="inputEmail3">GST</label>';
                data += '</div>';//col-sm-4

                data += '<input type="hidden" name="acc_grp_id" id="acc_grp_id" value="6">';
          
            data += '</div>'; //form-group

            data += '<div class="form-group floating-form">';

             data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<textarea name="acc_remark" class="form-control floating-input" id="acc_remark" placeholder=" " autocomplete="off"></textarea>';
            data += '<label for="inputEmail3">Remark</label>';
            data += '</div>'; //col-sm-4

            data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
            data += '<textarea name="acc_billing_address" class="form-control floating-input" id="acc_billing_address" placeholder=" " autocomplete="off"></textarea>';
            data += '<label for="inputEmail3">Address</label>';
            data += '</div>'; //col-sm-4


              //account status
               data += '<div class="col-sm-4 col-sm-offset-1 floating-label">';
               data += '<select class="form-control floating-select" id="acc_status1" name="acc_status1">';
               data += '<option value="1">ACTIVE</option>';
               data += '<option value="0">INACTIVE</option>';
               data += '</select>';
               data += '<label for="inputEmail3">Account Status</label></div>';


            data += '</form>';
            data += '</div>'; // col-md-12
            data += '</div>'; // row

            $(".modal-body").html(data);

            $('#acc_diamond_type').multiselect({
                includeSelectAllOption: true,
                buttonWidth: '100%',
                nonSelectedText: 'Select'
            });

            $(document).on('change', '#acc_kyc', function() {
                if ($(this).val() == '1') { // YES
                    $('#kyc_section').css('display', 'block'); // show
                } else { // NO
                    $('#kyc_section').css('display', 'none');  // hide
                    $('#kyc_img_preview').html('');                      // clear previews
                    $('#kyc_img').val('');                               // reset file input
                }
            });

            var sbt_btn = '<button type="button" class="btn btn-default" onClick="reload_page();" data-dismiss="modal">Close</button>';

            
            sbt_btn += '<button type="button" class="btn btn-success" onClick="add_customer(0)">Submit</button>';

                $(".modal-title").html("Add customer");
          

            $(".modal-footer").html(sbt_btn);
            $("#popup_modal_lg").modal('show');
        },
        errmsg =>{});

    }



    function add_customer(id = 0) {
    let check = 1;

    // ---- Basic validation ----
    const fields = ["acc_owner", "acc_broker_id", "acc_grp_id", "acc_type", "acc_gst", "acc_pan"];
    fields.forEach(f => {
        const el = $("#" + f);
        if (el.val() === '' || el.val() === '0') {
            el.css({ 'border-color': 'red' });
            check = 0;
        } else {
            el.css({ 'border-color': '#CCC' });
        }
    });

    if (check === 0) {
        display_alert_popup('err', 'Oh snap! You forgot to enter some information.');
        $("#popup_modal_lg").animate({ scrollTop: 0 }, 1000);
        return;
    }

    // ---- Submit Form ----
    const path = base_url + "sales/salesctrl/customer_insert/" + id;
    const form = document.getElementById('account_form');
    const formData = new FormData(form);

    fileUpAjaxCall('POST', path, formData, 'JSON',
        function (resp) {
            // Ensure resp is parsed JSON
            if (typeof resp === "string") {
                try { resp = JSON.parse(resp); } catch (e) { resp = {}; }
            }

            if (resp.status === 1) {
                // ✅ Success
                display_alert_popup('succ', 'Successfully added!');
                $("#popup_modal_lg").animate({ scrollTop: 0 }, 1000);
                $("#account_form")[0].reset();

                // Optionally close popup and refresh dropdown
                if (resp.id && resp.name) {
                    // Example: Add to customer dropdown if exists
                    const custSelect = $("#cust_id");
                    if (custSelect.length) {
                        custSelect.append(new Option(resp.name, resp.id, true, true)).trigger('change');
                    }
                }

                $("#popup_modal_lg").modal('hide');

                // Reload tables if visible
                $("#table_reload").load(window.location + " .table");
                $("#count_reload").load(window.location + " #total_rows");
            }
            else if (resp.status === 2) {
                // ⚠️ Already exists
                display_alert_popup('err', 'Account already exists!');
                $("#popup_modal_lg").animate({ scrollTop: 0 }, 1000);
            }
            else {
                // ⚠️ Unknown error
                display_alert_popup('warn', 'Unknown error! Please try again later.');
                $("#popup_modal_lg").animate({ scrollTop: 0 }, 1000);
            }
        },
        function (err) {
            display_alert_popup('err', 'Server error! Please try again later.');
            console.error(err);
        }
    );
}

// function set_bill_type(toggle) {
//     alert(1);
//     calculate_sub_total_amt();

//     const isRegistered = toggle.checked;
//     const saleNo = document.getElementById('sale_no');
//     const saleUnregiNo = document.getElementById('sale_unregi_entry_no');
//     const label = document.getElementById('entry_no_label');

//     if (isRegistered) {
//         saleNo.style.display = 'block';
//         saleUnregiNo.style.display = 'none';
//         label.innerText = "ENTRY NO (Registered)";
//     } else {
//         saleNo.style.display = 'none';
//         saleUnregiNo.style.display = 'block';
//         label.innerText = "ENTRY NO (Unregistered)";
//     }

//     // Update hidden field for backend submission
//     // document.getElementById('pur_with_registered').value = isRegistered ? 1 : 0;
// }


function validateDollarRate(el) {
    let val = parseFloat(el.value);
    if (val <= 0 || isNaN(val)) {
        el.value = 1;
    }
    
    calculate_single_fields('price_ct');
    calculate_single_fields('pc_amt');
    calculate_single_fields('dollar_ct');
    calculate_single_fields('dollar_amt');

    // Row fields (loop for ALL rows)
    $('#sales_wrapper tbody tr').each(function(index) {
        calculatePriceFields(index + 1, 'price_ct');
        calculatePriceFields(index + 1, 'pc_amt');
        calculatePriceFields(index + 1, 'dollar_ct');
        calculatePriceFields(index + 1, 'dollar_amt');
    });
}

function hsn_changed() {
    $("#dm_id").trigger("change");  
}


const remove_sales_preview_image = (id) => {

  let path = `remove_sales_preview_image/`+id;
  let form_data = new FormData();

  $.ajax({
    type: 'POST',
    url: path,
    data: form_data,
    contentType: false,     // REQUIRED
    processData: false,     // REQUIRED
    cache: false,

    success: (resp) => {
      display_alert_popup('succ', 'Document deleted successfully!!!');

      $("body, html").animate({ scrollTop: 0 }, 1000);

      window.location.reload();
    },

    error: (err) => {
      console.log(err);
    },
  });
};

let BALANCE_STOCK = {}; // cache for all balances

// ===============================
// LOAD ALL BALANCE STOCK (ONE TIME)
// ===============================
$(document).ready(function() {

    $.ajax({
        url: base_url + "sales/salesctrl/get_total_balance_stock",
        type: "GET",
        dataType: "json",
        success: function(res) {
            if (res.resp == 1) {
                BALANCE_STOCK = res.balance_list;
                console.log("Loaded balances:", BALANCE_STOCK);
            }
        }
    });

});

// ========================================
// INSTANT HOVER FOR st_carat[] & st_dm_code[]
// ========================================
document.addEventListener("mouseenter", function(e) {

    // Prevent errors for non-elements
    if (!(e.target instanceof HTMLElement)) return;

    // -------------- st_dm_code[] hover --------------
    if (e.target.matches('input[name="st_dm_code[]"]')) {

        let dmCode = e.target.value.trim();
        let balance = BALANCE_STOCK[dmCode] ?? 0;

        e.target.title = "Balance Stock: " + balance;
    }

}, true);