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

// 1. Remove the current view-audit-logs completely
const startIdx = c.indexOf('            <!-- Audit Logs View -->');
if(startIdx !== -1) {
  const endIdx = c.indexOf('<!-- Modals -->', startIdx);
  if(endIdx !== -1) {
    c = c.substring(0, startIdx) + c.substring(endIdx);
  }
}

// 2. Insert view-audit-logs inside .main-content
// Find the exact place to insert.
// We want to insert it right before the two </div> that precede <!-- Modals -->.
const viewStr = `      <!-- Audit Logs View -->
      <div id="view-audit-logs" class="view">
        <div class="header-actions">
          <h2>سجل المراقبة والنسخ الاحتياطي</h2>
          <button class="btn-primary" onclick="window.runBackup()">💾 أخذ نسخة احتياطية الآن</button>
        </div>
        
        <div style="display:flex; gap: 15px; margin-bottom: 20px;">
           <input type="text" id="audit-search" placeholder="بحث باسم المستخدم أو الحركة..." style="flex:1;" oninput="window.renderAuditLogs()">
           <input type="date" id="audit-date" style="width:150px;" onchange="window.renderAuditLogs()">
        </div>
        
        <div class="card" style="margin-bottom: 20px; display:none;" id="backup-result-card">
           <p id="backup-result-msg" style="color: green; font-weight: bold;"></p>
        </div>

        <div class="table-responsive">
          <table class="data-table">
            <thead>
              <tr>
                <th>التاريخ والوقت</th>
                <th>المستخدم</th>
                <th>الحركة</th>
                <th>الموديول</th>
                <th>رقم السجل</th>
                <th>التفاصيل</th>
              </tr>
            </thead>
            <tbody id="audit-logs-tbody">
              <!-- Audit Logs -->
            </tbody>
          </table>
        </div>
      </div>\n`;

const targetPattern = '</div>\n  </div>\n\n  \n<!-- Modals -->';
if (c.includes(targetPattern)) {
  c = c.replace(targetPattern, viewStr + targetPattern);
} else {
  // Try another pattern
  c = c.replace(/<\/div>\s*<\/div>\s*<!-- Modals -->/g, viewStr + '</div>\n</div>\n<!-- Modals -->');
}

fs.writeFileSync('index.html', c);
console.log('Fixed index.html structure properly!');
