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

// Find where "purchases-paid-amount" is (we know it's there)
let paidIdx = content.indexOf('id="purchases-paid-amount"');
if (paidIdx !== -1) {
    // Find the NEXT <table class="data-table"
    let tableStart = content.indexOf('<table class="data-table"', paidIdx);
    if (tableStart !== -1) {
        // Find the NEXT <div class="modal-actions"
        let modalActions = content.indexOf('<div class="modal-actions"', tableStart);
        if (modalActions !== -1) {
            let before = content.substring(0, tableStart);
            let after = content.substring(modalActions);
            
            let replacement = `<table class="data-table" style="margin-top: 15px;">
        <thead>
          <tr>
            <th>الصنف</th>
            <th>الكمية</th>
            <th>سعر الوحدة</th>
            <th>خصم %</th>
            <th>الإجمالي</th>
            <th>إجراء</th>
          </tr>
        </thead>
        <tbody id="purchases-lines-tbody"></tbody>
      </table>
      
      <div style="display: flex; justify-content: space-between; flex-wrap: wrap; gap: 10px; margin-top: 15px; font-weight: bold; font-size: 16px; background: rgba(0,0,0,0.05); padding: 15px; border-radius: 8px;">
        <div>الإجمالي: <span id="purchases-subtotal">0</span></div>
        <div>إجمالي الخصم: <span id="purchases-total-discount">0</span></div>
        <div style="color: var(--primary);">الصافي: <span id="purchases-net-total">0</span></div>
        <div style="color: var(--success);">إجمالي المسدد: <span id="purchases-paid-total">0</span></div>
        <div style="color: var(--danger);">المتبقي بعد المسدد: <span id="purchases-remaining">0</span></div>
      </div>
      <div id="purchases-linked-vouchers-container" style="display: none; margin-top: 15px; padding: 15px; background: rgba(0,0,0,0.03); border-radius: 8px;">
        <h5 style="color: var(--primary); margin-bottom: 10px; border-bottom: 1px solid var(--border); padding-bottom: 5px;"><i class="fas fa-receipt"></i> تفاصيل السندات المدفوعة لهذه الفاتورة:</h5>
        <ul id="purchases-linked-vouchers-list" style="list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 5px;"></ul>
      </div>

      `;
            
            content = before + replacement + after;
            fs.writeFileSync('index.html', content);
            console.log("Successfully replaced purchases table.");
        } else {
            console.log("Could not find modal actions");
        }
    } else {
        console.log("Could not find table");
    }
} else {
    console.log("Could not find purchases-paid-amount");
}
