const fs = require('fs');

let app = fs.readFileSync('app_final.js', 'utf8');

const newCode = `
// --- STOREKEEPERS DASHBOARD ---
window.renderStorekeepersDashboard = function() {
    const section = document.getElementById('storekeepers-dashboard-section');
    const tbody = document.getElementById('storekeepers-dashboard-tbody');
    if (!section || !tbody) return;

    // Only general manager should see all storekeepers
    if (currentUser.role !== 'مدير عام') {
        section.style.display = 'none';
        return;
    }

    // Find storekeepers
    const storekeepers = currentUsers.filter(u => u.role === 'أمين مخزن' || u.role === 'أمينة مخزن' || u.role === 'مدير مخازن' || u.username.includes('امين'));
    
    // Also include anyone who has a custody account that has the word عهدة in it
    currentUsers.forEach(u => {
       if (u.custody_account_id && !storekeepers.find(sk => sk.id === u.id)) {
           const acc = currentAccounts.find(a => a.id === u.custody_account_id);
           if (acc && acc.name.includes('عهد')) {
               storekeepers.push(u);
           }
       }
    });

    if (storekeepers.length === 0) {
        section.style.display = 'none';
        return;
    }

    section.style.display = 'block';
    tbody.innerHTML = '';

    storekeepers.forEach(sk => {
        let accName = 'لا يوجد';
        let balanceStr = '0';
        let balanceHtml = '<span>0</span>';

        if (sk.custody_account_id) {
            const acc = currentAccounts.find(a => a.id === sk.custody_account_id);
            if (acc) {
                accName = acc.name;
                
                // Calculate balance
                let runningBalance = 0;
                currentJournals.forEach(j => {
                    if (j.status !== 'posted') return;
                    if (j.rows) {
                        j.rows.forEach(r => {
                            if (r.account_id == sk.custody_account_id) {
                                runningBalance += (parseFloat(r.debit) || 0) - (parseFloat(r.credit) || 0);
                            }
                        });
                    }
                });

                balanceStr = Math.abs(runningBalance).toLocaleString('ar-EG');
                if (runningBalance > 0) balanceHtml = \`<span style="color:var(--danger); font-weight:bold;">\${balanceStr} مدين</span>\`;
                else if (runningBalance < 0) balanceHtml = \`<span style="color:var(--success); font-weight:bold;">\${balanceStr} دائن</span>\`;
                else balanceHtml = \`<span>0</span>\`;
            }
        }

        let actionBtn = \`<button class="btn btn-sm btn-secondary" disabled>📄 كشف حساب</button>\`;
        if (sk.custody_account_id) {
            actionBtn = \`<button class="btn btn-sm btn-primary" onclick="openAccountStatement(\${sk.custody_account_id})">📄 كشف حساب</button>\`;
        }

        tbody.innerHTML += \`
            <tr>
                <td>\${sk.username}</td>
                <td>\${accName}</td>
                <td style="font-size: 16px;">\${balanceHtml}</td>
                <td>\${actionBtn}</td>
            </tr>
        \`;
    });
};
`;

// Insert the new function before calculateBalances()
if (!app.includes('window.renderStorekeepersDashboard')) {
  app = app.replace('function calculateBalances() {', newCode + '\nfunction calculateBalances() {');
}

// Call it in loadData()
if (!app.includes('renderStorekeepersDashboard();')) {
  app = app.replace(
      'renderInvoices(); renderBalances(); renderNotifications(myNotifs); renderDecisions();',
      'renderInvoices(); renderBalances(); renderNotifications(myNotifs); renderDecisions(); renderStorekeepersDashboard();'
  );
}

fs.writeFileSync('app_final.js', app, 'utf8');
console.log('Added Storekeepers dashboard logic to app_final.js');
