console.log("Running client script");

var stage = ZDK.Page.getField("Stage").getValue();
console.log("Stage:", stage);
// Get the current record ID
var recordId = $Page.record_id;

console.log(recordId);


var booking = ZDK.Apps.CRM.Deals.fetchById(recordId);
var related_invoices = booking.__fetchRelatedRecords("Invoices");
console.log("Related Invoices: ",related_invoices);

for(var i=0; i< related_invoices.length; i++){
    log(related_invoices[i]);
    balance = related_invoices[i]._Balance;
    console.log("Balance: ", balance);
    if (balance > 0)
    {
        ZDK.Client.showAlert("Can not close the deal, we have outstanding balance in Invoices!");
        return false;
    }
}

var related_reservation = booking.__fetchRelatedRecords("Supplier_Reservation");
console.log("Related Suppliers: ",related_reservation);
for(var i=0; i< related_reservation.length; i++){
    log(related_reservation[i]);
    balance = related_reservation[i]._Balance_Due_2;
    console.log("Balance: ", balance);
    if (balance > 0)
    {
        ZDK.Client.showAlert("Can not close the deal, we have outstanding balance in Supplier Reservations!");
        return false;
    }
}