const fs = require('fs');
let html = fs.readFileSync('index.html', 'utf8');

// Sales returns: inject missing fields before the status select
const salesTarget = '<div class="flex-col"><label>حالة الفاتورة</label>';
const salesInject = `
          <div class="flex-col"><label>الخزينة</label><select id="sales-returns-treasury"></select></div>
          <div class="flex-col"><label>الإجمالي</label><input type="number" id="sales-returns-total" readonly></div>
          <div class="flex-col"><label>ملاحظات</label><input type="text" id="sales-returns-notes"></div>
          ` + salesTarget;

if (html.includes(salesTarget) && !html.includes('id="sales-returns-treasury"')) {
    html = html.replace(salesTarget, salesInject);
}

// Purchases returns: inject missing fields before the status select
// First we need to find the exact target for purchases
const purchTarget = '<div class="flex-col"><label>حالة الفاتورة</label>';
// Wait, the purchTarget is the same string! So we need to only replace the second occurrence, or just be specific.
// I will replace it using a regex that looks for the purchases-returns-project
const purchRegex = /(<div class="flex-col"><label>مركز \/ فرع التكلفة \(اختياري\)<\/label><select id="purchases-returns-project"><\/select><\/div>\s*)<div class="flex-col"><label>حالة الفاتورة<\/label>/;
const purchInject = `$1
          <div class="flex-col"><label>الخزينة</label><select id="purchases-returns-treasury"></select></div>
          <div class="flex-col"><label>الإجمالي</label><input type="number" id="purchases-returns-total" readonly></div>
          <div class="flex-col"><label>ملاحظات</label><input type="text" id="purchases-returns-notes"></div>
          <div class="flex-col"><label>حالة الفاتورة</label>`;

if (html.match(purchRegex) && !html.includes('id="purchases-returns-treasury"')) {
    html = html.replace(purchRegex, purchInject);
}

// Bust cache
html = html.replace(/v=\d+/g, 'v=' + Date.now());

fs.writeFileSync('index.html', html, 'utf8');
console.log('Successfully patched index.html with missing fields.');
