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

if (!code.includes('window.updatePurchasesUnitOptions =')) {
    code += `
window.updatePurchasesUnitOptions = function() {
    const sel = document.getElementById('purchases-item');
    if(!sel) return;
    const itemId = sel.value;
    const item = window.currentItems.find(i => String(i.id) === String(itemId));
    const unitSel = document.getElementById('purchases-unit');
    if(unitSel && item) {
        unitSel.innerHTML = \`<option value="base" data-factor="1">\${item.unit || 'الأساسية'}</option>\`;
        if(item.alt_unit && item.unit_factor) {
            unitSel.innerHTML += \`<option value="alt" data-factor="\${item.unit_factor}">\${item.alt_unit} (/\${item.unit_factor})</option>\`;
        }
    }
};

window.updateSalesUnitOptions = function() {
    const sel = document.getElementById('sales-item');
    if(!sel) return;
    const itemId = sel.value;
    const item = window.currentItems.find(i => String(i.id) === String(itemId));
    const unitSel = document.getElementById('sales-unit');
    if(unitSel && item) {
        unitSel.innerHTML = \`<option value="base" data-factor="1">\${item.unit || 'الأساسية'}</option>\`;
        if(item.alt_unit && item.unit_factor) {
            unitSel.innerHTML += \`<option value="alt" data-factor="\${item.unit_factor}">\${item.alt_unit} (/\${item.unit_factor})</option>\`;
        }
    }
};
`;
}

// Modify addPurchasesItem to use units
code = code.replace(
    /const itemId = document\.getElementById\('purchases-item'\)\.value;\s*const qty = parseFloat\(document\.getElementById\('purchases-qty'\)\.value\);\s*const price = parseFloat\(document\.getElementById\('purchases-price'\)\.value\);/g,
    `const itemId = document.getElementById('purchases-item').value;
    const unitSel = document.getElementById('purchases-unit');
    const factor = unitSel && unitSel.options[unitSel.selectedIndex] ? parseFloat(unitSel.options[unitSel.selectedIndex].dataset.factor) || 1 : 1;
    const unitName = unitSel && unitSel.options[unitSel.selectedIndex] ? unitSel.options[unitSel.selectedIndex].text.split(' ')[0] : '';
    
    let baseQty = parseFloat(document.getElementById('purchases-qty').value);
    const displayedQty = baseQty;
    baseQty = baseQty * factor; // Convert to base unit quantity
    
    let price = parseFloat(document.getElementById('purchases-price').value);
    // price is per selected unit.
    const qty = baseQty;`
);

code = code.replace(
    /currentPurchasesItems\.push\(\{item_id: item\.id, name: item\.name, qty, price, total\}\);/g,
    `currentPurchasesItems.push({
        item_id: item.id, 
        name: item.name, 
        qty: qty, 
        displayed_qty: displayedQty,
        unit: unitName || item.unit,
        price: price, 
        total
    });`
);

code = code.replace(
    /<td>\${i\.qty}<\/td>\s*<td>\${i\.price}<\/td>/g,
    `<td>\${i.displayed_qty || i.qty} \${i.unit || ''}</td>
            <td>\${i.price}</td>`
);


// Modify addSalesItem similarly
code = code.replace(
    /const itemId = document\.getElementById\('sales-item'\)\.value;\s*const qty = parseFloat\(document\.getElementById\('sales-qty'\)\.value\);\s*const price = parseFloat\(document\.getElementById\('sales-price'\)\.value\);/g,
    `const itemId = document.getElementById('sales-item').value;
    const unitSel = document.getElementById('sales-unit');
    const factor = unitSel && unitSel.options[unitSel.selectedIndex] ? parseFloat(unitSel.options[unitSel.selectedIndex].dataset.factor) || 1 : 1;
    const unitName = unitSel && unitSel.options[unitSel.selectedIndex] ? unitSel.options[unitSel.selectedIndex].text.split(' ')[0] : '';
    
    let baseQty = parseFloat(document.getElementById('sales-qty').value);
    const displayedQty = baseQty;
    baseQty = baseQty * factor;
    
    let price = parseFloat(document.getElementById('sales-price').value);
    const qty = baseQty;`
);

code = code.replace(
    /currentSalesItems\.push\(\{item_id: item\.id, name: item\.name, qty, price, total, store_id: storeId\}\);/g,
    `currentSalesItems.push({
        item_id: item.id, 
        name: item.name, 
        qty: qty, 
        displayed_qty: displayedQty,
        unit: unitName || item.unit,
        price: price, 
        total, 
        store_id: storeId
    });`
);

fs.writeFileSync('sales_purchases_module.js', code, 'utf8');
console.log('Patched sales_purchases_module.js for unit conversions');
