const fs = require('fs');
let content = fs.readFileSync('sales_purchases_module.js', 'utf8');

const unitLogic = `
window.updateSalesUnitOptions = function() {
    const itemId = document.getElementById('sales-item').value;
    const unitSel = document.getElementById('sales-unit');
    if (!unitSel) return;
    
    if (!itemId) {
        unitSel.innerHTML = '<option value="base">الأساسية</option>';
        return;
    }
    const item = currentItems.find(i => String(i.id) === String(itemId));
    if (!item) return;

    let html = '<option value="base">' + (item.unit || 'الأساسية') + ' (1)</option>';
    if (item.conversions && Array.isArray(item.conversions)) {
        item.conversions.forEach(conv => {
            html += '<option value="' + conv.to_unit + '" data-factor="' + conv.factor + '">' + conv.to_unit + ' (' + conv.factor + ')</option>';
        });
    }
    unitSel.innerHTML = html;
};

window.updatePurchasesUnitOptions = function() {
    const itemId = document.getElementById('purchases-item').value;
    const unitSel = document.getElementById('purchases-unit');
    if (!unitSel) return;
    
    if (!itemId) {
        unitSel.innerHTML = '<option value="base">الأساسية</option>';
        return;
    }
    const item = currentItems.find(i => String(i.id) === String(itemId));
    if (!item) return;

    let html = '<option value="base">' + (item.unit || 'الأساسية') + ' (1)</option>';
    if (item.conversions && Array.isArray(item.conversions)) {
        item.conversions.forEach(conv => {
            html += '<option value="' + conv.to_unit + '" data-factor="' + conv.factor + '">' + conv.to_unit + ' (' + conv.factor + ')</option>';
        });
    }
    unitSel.innerHTML = html;
};
`;

if (!content.includes('updatePurchasesUnitOptions')) {
    content += '\n' + unitLogic + '\n';
    fs.writeFileSync('sales_purchases_module.js', content, 'utf8');
    console.log('Added unit logic');
} else {
    console.log('Unit logic already exists');
}
