const fs = require('fs');
let c = fs.readFileSync('db.js', 'utf8');

const logFn = `
function logToActivity(storeName, action, dataId) {
    if (storeName === 'activity_logs') return;
    const user = JSON.parse(sessionStorage.getItem('currentUser') || '{}');
    if (!user.username) return;
    
    const storeMap = {
        'items': 'الأصناف',
        'projects': 'المشاريع',
        'warehouses': 'المخازن',
        'users': 'المستخدمين',
        'contacts': 'جهات الاتصال',
        'units': 'الوحدات',
        'transactions': 'المستندات والفواتير',
        'journal_entries': 'القيود اليومية',
        'client_abstracts': 'المستخلصات',
        'accounts': 'شجرة الحسابات',
        'notifications': 'الإشعارات'
    };
    
    const actionMap = {
        'add': 'إضافة',
        'update': 'تعديل',
        'remove': 'حذف'
    };

    const modName = storeMap[storeName] || storeName;
    const actName = actionMap[action] || action;
    const details = \`تم \${actName} سجل في \${modName} (ID: \${dataId})\`;

    const logEntry = {
        id: Date.now() + Math.floor(Math.random() * 10000),
        timestamp: new Date().toLocaleString('en-GB'),
        username: user.username,
        action: actName,
        module: modName,
        record_id: String(dataId),
        details: details
    };

    fetch(\`\${API_BASE}?store=activity_logs\`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(logEntry)
    }).catch(e => console.error(e));
}
`;

if (!c.includes('logToActivity')) {
  c = c.replace('function add(storeName, data) {', logFn + '\nfunction add(storeName, data) {');
  
  c = c.replace('.then(result => result.id)', '.then(result => { logToActivity(storeName, "add", result.id); return result.id; })');
  c = c.replace('.then(res => res.json())\n    .catch(err => {', '.then(res => res.json()).then(res => { logToActivity(storeName, "update", data.id); return res; })\n    .catch(err => {');
  
  // For remove, there's no data.id, only id
  c = c.replace('.then(res => res.json())\n    .catch(err => {', '.then(res => res.json()).then(res => { logToActivity(storeName, "remove", id); return res; })\n    .catch(err => {');
  
  fs.writeFileSync('db.js', c);
  console.log('Fixed db.js to include logging');
} else {
  console.log('Already has logging');
}
