var today = new Date().toISOString().split('T')[0];
var VORI  = 11.664;
var ANA   = 11.664 / 16;
var ROTI  = 11.664 / 96;
var POINT = 0.01;

var pureRatios = {
    '24K'  : 1.0000,
    '22K'  : 0.9167,
    '21K'  : 0.8750,
    '18K'  : 0.7500,
    'other': 0.5833
};

function tk(n) {
    return '\u09F3' +
        Number(parseFloat(n||0).toFixed(0))
        .toLocaleString('en-IN');
}

function convertWeight() {
    var v = parseFloat(
        document.getElementById('wVori').value  || 0);
    var a = parseFloat(
        document.getElementById('wAna').value   || 0);
    var r = parseFloat(
        document.getElementById('wRoti').value  || 0);
    var p = parseFloat(
        document.getElementById('wPoint').value || 0);
    var gram = (v*VORI) + (a*ANA) + (r*ROTI) + (p*POINT);
    document.getElementById('wGram').textContent =
        gram.toFixed(3);
    calculate();
}

function calculate() {
    var karat    = document.getElementById('mKarat').value;
    var gram     = parseFloat(
        document.getElementById('wGram').textContent || 0);
    var rateVori = parseFloat(
        document.getElementById('mRate').value || 0);

    // পার ভরি থেকে পার গ্রাম
    var rateGram = rateVori / VORI;

    var ratio = pureRatios[karat] || 0.9167;
    var pure  = gram * ratio;
    var total = pure * rateGram;

    // ভরিতে কনভার্ট করে দেখাই
    var pureVori = pure / VORI;

    document.getElementById('cRatio').textContent =
        (ratio*100).toFixed(2) + '%';
    document.getElementById('cGross').textContent =
        gram.toFixed(3) + ' g';
    document.getElementById('cPure').textContent =
        pure.toFixed(3) + ' g' +
        ' (' + pureVori.toFixed(3) + ' vori)';
    document.getElementById('cTotal').textContent =
        tk(total);

    // rate per gram লুকিয়ে রাখি
    document.getElementById('cRateGram').textContent =
        tk(rateGram) + '/g';
}

function toggleCash() {
    var pay = document.getElementById('mPayment').value;
    document.getElementById('cashAccDiv').style.display =
        (pay == 1) ? 'block' : 'none';
}

function openModal() {
    document.getElementById('mDate').value       = today;
    document.getElementById('wVori').value       = '';
    document.getElementById('wAna').value        = '';
    document.getElementById('wRoti').value       = '';
    document.getElementById('wPoint').value      = '';
    document.getElementById('wGram').textContent = '0.000';
    document.getElementById('mRate').value       = '';
    document.getElementById('mNote').value       = '';
    document.getElementById('mKarat').value      = '22K';
    document.getElementById('mPayment').value    = '1';
    document.getElementById('mParty').value      = '';
    document.getElementById('mOk').style.display = 'none';
    document.getElementById('mEr').style.display = 'none';
    document.getElementById('mBtn').textContent  = 'Save Purchase';
    document.getElementById('mBtn').disabled     = false;

    document.getElementById('wVori').oninput   = convertWeight;
    document.getElementById('wAna').oninput    = convertWeight;
    document.getElementById('wRoti').oninput   = convertWeight;
    document.getElementById('wPoint').oninput  = convertWeight;
    document.getElementById('mKarat').onchange = calculate;
    document.getElementById('mRate').oninput   = calculate;
    document.getElementById('mPayment').onchange = toggleCash;

    toggleCash();
    loadTodayRate();
    calculate();
    document.getElementById('purModal').style.display = 'block';
}

function closeModal() {
    document.getElementById('purModal').style.display = 'none';
}

function loadParties() {
    fetch('../api/parties/get_parties.php?limit=200')
    .then(function(r){ return r.json(); })
    .then(function(d){
        if (!d.success) return;
        var sel = document.getElementById('mParty');
        sel.innerHTML =
            '<option value="">-- Select Party --</option>';
        d.data.parties.forEach(function(p) {
            var opt = document.createElement('option');
            opt.value       = p.id;
            opt.textContent = p.name +
                (p.phone ? ' - ' + p.phone : '');
            sel.appendChild(opt);
        });
    });
}

function loadCashAccounts() {
    fetch('../api/cash/get_accounts.php')
    .then(function(r){ return r.json(); })
    .then(function(d){
        if (!d.success) return;
        var sel = document.getElementById('mCashAcc');
        sel.innerHTML = '';
        d.data.accounts.forEach(function(a) {
            var opt = document.createElement('option');
            opt.value       = a.id;
            opt.textContent = a.account_name +
                ' (' + tk(a.current_balance) + ')';
            sel.appendChild(opt);
        });
    });
}

function loadTodayRate() {
    fetch('../api/gold/get_rate.php')
    .then(function(r){ return r.json(); })
    .then(function(d){
        if (!d.success || !d.data) return;
        // rate_24k পার গ্রাম — পার ভরিতে কনভার্ট
        var rateVori = d.data.rate_24k * VORI;
        document.getElementById('mRate').value =
            rateVori.toFixed(0);
        calculate();
    });
}

function loadPurchases() {
    var from = document.getElementById('fromDate').value;
    var to   = document.getElementById('toDate').value;
    document.getElementById('purList').innerHTML =
        '<div class="empty">Loading...</div>';
    fetch('../api/purchases/get_purchases.php' +
        '?from_date=' + from +
        '&to_date='   + to +
        '&limit=50')
    .then(function(r){ return r.json(); })
    .then(function(d){
        if (!d.success) return;
        var purs = d.data.purchases;
        var sum  = d.data.summary;
        document.getElementById('sumEntries').textContent =
            sum.total_entries;
        document.getElementById('sumAmount').textContent =
            tk(sum.total_amount);
        document.getElementById('sumGross').textContent =
            parseFloat(sum.total_gross||0).toFixed(3) + 'g';
        document.getElementById('sumPure').textContent =
            parseFloat(sum.total_pure||0).toFixed(3) + 'g';
        var list = document.getElementById('purList');
        if (!purs || purs.length === 0) {
            list.innerHTML =
                '<div class="empty">No purchase found</div>';
            return;
        }
        var html = '';
        purs.forEach(function(p) {
            var kc = 'k-' +
                p.karat.toLowerCase().replace('k','');
            // rate per gram থেকে per vori
            var rateVori = parseFloat(p.rate_24k) * VORI;
            html += '<div class="pur-card">';
            html += '<div class="pur-top"><div>';
            html += '<div class="pur-party">' +
                (p.party_name||'Unknown') + '</div>';
            html += '<div class="pur-date">' +
                p.purchase_date + ' | #' + p.id + '</div>';
            html += '</div><span class="pur-karat ' + kc +
                '">' + p.karat + '</span></div>';
            html += '<div class="pur-details">';
            html += '<div class="pur-detail">' +
                '<div class="lbl">Gross</div>' +
                '<div class="val">' +
                parseFloat(p.gross_weight).toFixed(3) +
                'g</div></div>';
            html += '<div class="pur-detail">' +
                '<div class="lbl">Pure</div>' +
                '<div class="val">' +
                parseFloat(p.pure_weight).toFixed(3) +
                'g</div></div>';
            html += '<div class="pur-detail">' +
                '<div class="lbl">Rate/vori</div>' +
                '<div class="val">' +
                tk(rateVori) + '</div></div>';
            html += '</div>';
            html += '<div class="pur-bottom">';
            html += '<div class="pur-amount">' +
                tk(p.total_amount) + '</div>';
            html += '<div class="pur-meta">' +
                '<div class="loc">' +
                (p.location_name||'') + '</div>' +
                '<div class="pay">' +
                (p.payment_method||'CASH') +
                '</div></div></div></div>';
        });
        list.innerHTML = html;
    })
    .catch(function(){
        document.getElementById('purList').innerHTML =
            '<div class="empty">Error!</div>';
    });
}

function savePurchase() {
    var gram     = parseFloat(
        document.getElementById('wGram').textContent || 0);
    var rateVori = parseFloat(
        document.getElementById('mRate').value || 0);
    var er       = document.getElementById('mEr');
    var ok       = document.getElementById('mOk');
    er.style.display = 'none';
    ok.style.display = 'none';

    if (gram <= 0) {
        er.style.display = 'block';
        er.textContent   = 'Weight দিন! Vori/Ana/Roti/Point এ সংখ্যা দিন';
        return;
    }
    if (rateVori <= 0) {
        er.style.display = 'block';
        er.textContent   = 'Rate দিন!';
        return;
    }

    // পার ভরি থেকে পার গ্রামে কনভার্ট
    var rateGram = rateVori / VORI;

    var btn      = document.getElementById('mBtn');
    var karat    = document.getElementById('mKarat').value;
    var payMeth  = parseInt(
        document.getElementById('mPayment').value);
    var partyVal = document.getElementById('mParty').value;

    btn.disabled    = true;
    btn.textContent = 'Saving...';

    var payload = {
        purchase_date     : document.getElementById('mDate').value,
        party_id          : partyVal ? parseInt(partyVal) : null,
        location_id       : parseInt(
            document.getElementById('mLocation').value),
        karat             : karat,
        gross_weight      : gram,
        rate_24k          : rateGram,
        payment_method_id : payMeth,
        cash_account_id   : parseInt(
            document.getElementById('mCashAcc').value),
        note              : document.getElementById('mNote').value
    };

    fetch('../api/purchases/add_purchase.php', {
        method  : 'POST',
        headers : {'Content-Type':'application/json'},
        body    : JSON.stringify(payload)
    })
    .then(function(r){ return r.json(); })
    .then(function(d){
        btn.disabled    = false;
        btn.textContent = 'Save Purchase';
        if (d.success) {
            ok.style.display = 'block';
            ok.textContent   =
                'Saved! Pure: ' +
                d.data.pure_weight + 'g | ' +
                tk(d.data.total_amount);
            er.style.display = 'none';
            setTimeout(function(){
                closeModal();
                setTimeout(function(){
                    loadPurchases();
                }, 300);
            }, 2000);
        } else {
            er.style.display = 'block';
            er.textContent   = d.message;
        }
    })
    .catch(function(){
        btn.disabled    = false;
        btn.textContent = 'Save Purchase';
        er.style.display = 'block';
        er.textContent   = 'Server error!';
    });
}

window.onload = function() {
    document.getElementById('fromDate').value = today;
    document.getElementById('toDate').value   = today;
    document.getElementById('mDate').value    = today;
    loadParties();
    loadCashAccounts();
    loadPurchases();
};