let GOLD_RATE = 0;

// INIT
document.getElementById("inv").innerText =
"INV-" + Math.floor(Math.random() * 999999);

document.getElementById("date").innerText =
new Date().toLocaleDateString();


// FETCH RATE (FIXED)
function fetchRate() {

    $.ajax({
        url: base_url + "DashboardController/live_rate",
        type: "GET",
        dataType: "json",
        success: function (res) {

            if (res.status) {
                GOLD_RATE = parseFloat(res.rate);

                document.getElementById("rate").value = GOLD_RATE;

                calc();
            }
        },
        error: function () {
            console.log("API failed");
        }
    });
}


// CALC ENGINE
function calc() {

    let name = document.getElementById("name").value;
    let mobile = document.getElementById("mobile").value;
    let city = document.getElementById("city").value;

    let weight = parseFloat(document.getElementById("weight").value) || 0;

    let rateInput = parseFloat(document.getElementById("rate").value);
    let rate = (!isNaN(rateInput) && rateInput > 0) ? rateInput : GOLD_RATE;

    let purity = parseFloat(document.getElementById("purity").value) || 0;

    let making = parseFloat(document.getElementById("making").value) || 0;
    let wastage = parseFloat(document.getElementById("wastage").value) || 0;
    let gst = parseFloat(document.getElementById("gst").value) || 0;
    let stone = parseFloat(document.getElementById("stone").value) || 0;

    let net = weight - stone;
    if (net < 0) net = 0;

    let pure = net * purity;
    let gold = pure * rate;

    let make = gold * making / 100;
    let waste = gold * wastage / 100;

    let sub = gold + make + waste;
    let tax = sub * gst / 100;
    let total = sub + tax;

    // 🔥 CUSTOMER FIX (PRINT ISSUE SOLVED)
    document.getElementById("cname").innerText = name || "-";
    document.getElementById("cmobile").innerText = mobile || "-";
    document.getElementById("ccity").innerText = city || "-";

    // CALC DISPLAY
    document.getElementById("rweight").innerText = weight.toFixed(2);
    document.getElementById("pure").innerText = pure.toFixed(2);
    document.getElementById("gold").innerText = gold.toFixed(2);
    document.getElementById("make").innerText = make.toFixed(2);
    document.getElementById("tax").innerText = tax.toFixed(2);
    document.getElementById("total").innerText = total.toFixed(2);
}


// PRINT FIX (IMPORTANT)
function printInvoice(){
    calc(); // update values first
    setTimeout(() => {
        window.print();
    }, 300);
}


// INIT CALL (VERY IMPORTANT)
fetchRate();
setInterval(fetchRate, 60000);