const fs = require('fs');

try {
    let indexHtml = fs.readFileSync('index.html', 'utf8');

    // Remove the manual entry row for sales returns
    const salesReturnsManualRow = `<tr>
                <td><select id="sales-returns-item"></select></td>
                <td><input type="number" id="sales-returns-qty" value="1" min="1" step="0.01"></td>
                <td><input type="number" id="sales-returns-price" value="0" min="0" step="0.01"></td>
                <td style="display:flex; gap:5px;"><input type="number" id="sales-returns-discount" value="0" min="0" step="0.01" style="width:70px;"><select id="sales-returns-discount-type" style="width:60px;"><option value="value">قيمة</option><option value="percent">%</option></select></td>
                <td><button class="btn-primary" onclick="addSalesReturnsLine()" style="background:var(--accent);">إضافة للقائمة</button></td>
              </tr>`;
              
    indexHtml = indexHtml.replace(salesReturnsManualRow, '');

    // Sometimes the whitespace differs, let's use a regex to be safe
    indexHtml = indexHtml.replace(/<tr>\s*<td><select id="sales-returns-item"><\/select><\/td>[\s\S]*?addSalesReturnsLine\(\)[\s\S]*?<\/tr>/, '');
    indexHtml = indexHtml.replace(/<tr>\s*<td><select id="purchases-returns-item"><\/select><\/td>[\s\S]*?addPurchasesReturnsLine\(\)[\s\S]*?<\/tr>/, '');

    // Add a call to loadSalesForReturn() inside openSalesReturnModal() after populating contacts, just in case!
    let vrJs = fs.readFileSync('vouchers_returns.js', 'utf8');
    vrJs = vrJs.replace(
        /document\.getElementById\('sales-returns-modal'\)\.classList\.add\('active'\);/g,
        `document.getElementById('sales-returns-modal').classList.add('active');\n    setTimeout(() => { if(typeof loadSalesForReturn === 'function') loadSalesForReturn(); }, 100);`
    );
    vrJs = vrJs.replace(
        /document\.getElementById\('purchases-returns-modal'\)\.classList\.add\('active'\);/g,
        `document.getElementById('purchases-returns-modal').classList.add('active');\n    setTimeout(() => { if(typeof loadPurchasesForReturn === 'function') loadPurchasesForReturn(); }, 100);`
    );

    const timestamp = Date.now();
    indexHtml = indexHtml.replace(/vouchers_returns\.js\?v=\d+/g, 'vouchers_returns.js?v=' + timestamp);
    
    fs.writeFileSync('index.html', indexHtml, 'utf8');
    fs.writeFileSync('vouchers_returns.js', vrJs, 'utf8');

    console.log('Cleanup of returns table done.');
} catch (e) {
    console.error('Error cleaning up returns table:', e);
}
