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

// Fix sales-returns-status: replace lines 1448-1451
// Find by line numbers approach
const lines = html.split('\n');
let salesFixed = false;
let purchFixed = false;

for (let i = 0; i < lines.length; i++) {
  // Fix sales returns status dropdown
  if (lines[i].includes('id="sales-returns-status"') && !lines[i].includes('pending_store')) {
    // Find the closing </select> and replace
    let j = i;
    while (j < lines.length && !lines[j].includes('</select>')) j++;
    // lines[i] to lines[j] is the select block
    const newSelect = '          <select id="sales-returns-status"><option value="draft">مسودة (لا تؤثر على الأرصدة)</option><option value="pending_store" selected>بانتظار اعتماد المخزن (الموصى به)</option></select>';
    lines.splice(i, j - i + 1, newSelect);
    salesFixed = true;
    console.log('Fixed sales-returns-status at line', i + 1);
    break;
  }
}

for (let i = 0; i < lines.length; i++) {
  // Fix purchases returns status dropdown
  if (lines[i].includes('id="purchases-returns-status"') && !lines[i].includes('pending_store')) {
    let j = i;
    while (j < lines.length && !lines[j].includes('</select>')) j++;
    const newSelect = '          <select id="purchases-returns-status"><option value="draft">مسودة (لا تؤثر على الأرصدة)</option><option value="pending_store" selected>بانتظار اعتماد المخزن (الموصى به)</option></select>';
    lines.splice(i, j - i + 1, newSelect);
    purchFixed = true;
    console.log('Fixed purchases-returns-status at line', i + 1);
    break;
  }
}

if (!salesFixed) console.log('WARNING: sales-returns-status not found or already fixed');
if (!purchFixed) console.log('WARNING: purchases-returns-status not found or already fixed');

// Update cache versions
const now = Date.now();
let result = lines.join('\n');
result = result.replace(/app_final\.js\?v=[^\s"]+/, 'app_final.js?v=' + now);
result = result.replace(/store_module\.js\?v=[^\s"]+/, 'store_module.js?v=' + now);
result = result.replace(/vouchers_returns\.js\?v=[^\s"]+/, 'vouchers_returns.js?v=' + now);

fs.writeFileSync('index.html', result);
console.log('Done! Cache version: ' + now);
