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

const regex = /window\.openSalesModal = function\(id = null\) \{/;
const replacement = `window.openSalesModal = async function(id = null) {
  if (!window.currentItems || window.currentItems.length === 0) window.currentItems = await window.DB.getAll('items') || [];
  if (!window.currentProjects || window.currentProjects.length === 0) window.currentProjects = await window.DB.getAll('projects') || [];
  if (!window.currentWarehouses || window.currentWarehouses.length === 0) window.currentWarehouses = await window.DB.getAll('warehouses') || [];
  if (!window.currentContacts || window.currentContacts.length === 0) window.currentContacts = await window.DB.getAll('contacts') || [];
  const treasuries = await window.DB.getAll('accounts') || [];
  const treasuryAccounts = treasuries.filter(a => a.type === 'treasury' || a.type === 'bank');
  let tHtml = '<option value="">اختر الخزينة / الحساب</option>';
  treasuryAccounts.forEach(a => { tHtml += '<option value="' + a.id + '">' + a.name + '</option>'; });
  const salesTreasury = document.getElementById('sales-treasury');
  if(salesTreasury) salesTreasury.innerHTML = tHtml;
`;

if(content.match(regex)) {
    content = content.replace(regex, replacement);
    fs.writeFileSync('sales_purchases_module.js', content, 'utf8');
    console.log('Patched openSalesModal in sales_purchases_module.js');
} else {
    console.log('Regex not found openSalesModal');
}

const regexP = /window\.openPurchasesModal = function\(id = null\) \{/;
const replacementP = `window.openPurchasesModal = async function(id = null) {
  if (!window.currentItems || window.currentItems.length === 0) window.currentItems = await window.DB.getAll('items') || [];
  if (!window.currentProjects || window.currentProjects.length === 0) window.currentProjects = await window.DB.getAll('projects') || [];
  if (!window.currentWarehouses || window.currentWarehouses.length === 0) window.currentWarehouses = await window.DB.getAll('warehouses') || [];
  if (!window.currentContacts || window.currentContacts.length === 0) window.currentContacts = await window.DB.getAll('contacts') || [];
  const treasuries = await window.DB.getAll('accounts') || [];
  const treasuryAccounts = treasuries.filter(a => a.type === 'treasury' || a.type === 'bank');
  let tHtml = '<option value="">اختر الخزينة / الحساب</option>';
  treasuryAccounts.forEach(a => { tHtml += '<option value="' + a.id + '">' + a.name + '</option>'; });
  const purchTreasury = document.getElementById('purchases-treasury');
  if(purchTreasury) purchTreasury.innerHTML = tHtml;
`;

if(content.match(regexP)) {
    content = content.replace(regexP, replacementP);
    fs.writeFileSync('sales_purchases_module.js', content, 'utf8');
    console.log('Patched openPurchasesModal in sales_purchases_module.js');
} else {
    console.log('Regex not found openPurchasesModal');
}
