const fs = require('fs');

if (fs.existsSync('app_final.js')) {
    let js = fs.readFileSync('app_final.js', 'utf8');
    
    // Add account statement button unconditionally, and append the manager actions
    const searchString = `      let actions = '';
      if(currentUser && currentUser.role === 'مدير عام') {
        actions = \`<button class="action-btn btn-edit" onclick="openAccountModal(\${acc.id})">✏️ تعديل</button>
                   <button class="action-btn btn-view" onclick="openAccountModal(null, \${acc.id})">➕ فرعي</button>
                   <button class="action-btn btn-delete" onclick="deleteAccount(\${acc.id})">🗑️ حذف</button>\`;
      }`;
      
    const replaceString = `      let actions = \`<button class="action-btn" style="background:#17a2b8; color:#fff; padding:5px 10px;" onclick="openAccountStatement(\${acc.id})">📄 كشف حساب</button>\`;
      if(currentUser && currentUser.role === 'مدير عام') {
        actions += \` <button class="action-btn btn-edit" onclick="openAccountModal(\${acc.id})">✏️ تعديل</button>
                   <button class="action-btn btn-view" onclick="openAccountModal(null, \${acc.id})">➕ فرعي</button>
                   <button class="action-btn btn-delete" onclick="deleteAccount(\${acc.id})">🗑️ حذف</button>\`;
      }`;
      
    if (js.includes(searchString) && !js.includes('📄 كشف حساب</button>')) {
        js = js.replace(searchString, replaceString);
        fs.writeFileSync('app_final.js', js, 'utf8');
        console.log('Added account statement button to app_final.js');
    } else {
        console.log('Could not find the exact string or already replaced.');
    }
}

// Cache buster
if (fs.existsSync('index.html')) {
    let html = fs.readFileSync('index.html', 'utf8');
    html = html.replace(/v=\d+/g, 'v=' + Date.now());
    fs.writeFileSync('index.html', html, 'utf8');
}
