getId=(idName)=>{
    return document.getElementById(idName);
}
let paymentMethod = getId("paymentMethod");
let invoiceDetails = [];
let cashPay = getId("cashEntry");
let bankPay = getId("bankEntry");
let chequeNo = getId("chequeNo");
bankPay.readOnly=true;
cashPay.readOnly =true;
chequeNo.readOnly=true;
paymentMethod.addEventListener("change",function(e){
let pay = e.target.value;
if(pay == "cash")
{
bankPay.readOnly=true;
cashPay.readOnly =false;
chequeNo.readOnly=true;
bankPay.value = 0;
chequeNo.value = "-";
}
if(pay == "bank")
{
bankPay.readOnly=false;
cashPay.readOnly =true;
chequeNo.readOnly=false;
cashPay.value=0;
}
if(pay == "all")
{
bankPay.readOnly=false;
cashPay.readOnly =false;
chequeNo.readOnly=false;
}
});

$(document).ready(function(){
    $("#customerAdd").on("change",function(){
        let customer = $(this).val();
        fetchAmountDetails(customer);
        fetchSalesBill(customer);
    });
    $("#invoiceAdd").on("change",function(){
        let invoice = $(this).val();
        fetchInvoiceAmountDetails(invoice);
    });
});
function fetchAmountDetails(customer){
     $.ajax({
            type:'POST',
            url:'ajaxpath1/fetch_amount_details.php',
            data:{customer:customer},
            success:function(data){
            var output = data.split("||");
            $("#totalAmount").val(output[0]);
            $("#pendingAmount").val(output[1]);
                        }
           });  
}
function fetchSalesBill(customer){
    let optionData = '';
     $.ajax({
            type:'POST',
            url:'ajaxpath1/fetch_customer_bill_details.php',
            data:{customer:customer},
            success:function(dataRec){
                let data = JSON.parse(dataRec);
           console.log(typeof(data));
           if(data.length > 0) {
            invoiceDetails = data;
            optionData+=`<option value="">-- Select Bill ---</option>`;
             data.map((list)=>{
                optionData+=`<option value="${list.code}">${list.code}</option>`;
             });
             getId("invoiceAdd").innerHTML = optionData;
                         $("#totalAmount").val(0);
            $("#pendingAmount").val(0);

           }
         }
           });  
}
function fetchInvoiceAmountDetails(invoice) {
    let customer = getId("customerAdd").value;
 $.ajax({
            type:'POST',
            url:`ajaxpath1/fetch_invoice_amount_details.php`,
            data:{invoice:invoice,customer:customer},
            success:function(data){
            let dataVal = JSON.parse(data);
            console.log(dataVal);
            $("#totalAmount").val(dataVal.value);
            $("#pendingAmount").val(dataVal.pending);
                        }
           });   
}