const fs = require('fs');

if (fs.existsSync('app_final.js')) {
    let js = fs.readFileSync('app_final.js', 'utf8');

    // 1. Modify approveSettlement to accept skipConfirm
    const searchApprove = `window.approveSettlement = async function(id) {
    if (!confirm('هل أنت متأكد من اعتماد هذه التسوية؟ للمصروفات سيتم عمل قيد، وللمخزون سيتم إرساله لاعتماد أمين المخزن.')) return;`;
    
    const replaceApprove = `window.approveSettlement = async function(id, skipConfirm = false) {
    if (!skipConfirm && !confirm('هل أنت متأكد من اعتماد هذه التسوية؟ للمصروفات سيتم عمل قيد، وللمخزون سيتم إرساله لاعتماد أمين المخزن.')) return;`;
    
    js = js.replace(searchApprove, replaceApprove);


    // 2. Modify saveSettlement to call approveSettlement
    const searchSave = `        if (isEditId) {
            settlement.id = parseInt(isEditId);
            await window.DB.update('transactions', settlement);
        } else {
            await window.DB.add('transactions', settlement);
        }
        closeModal('settlement-modal'); await loadData(); if (typeof renderSettlements === 'function') renderSettlements();
    } catch(e) {`;
    
    const replaceSave = `        let savedId = isEditId ? parseInt(isEditId) : null;
        if (savedId) {
            settlement.id = savedId;
            await window.DB.update('transactions', settlement);
        } else {
            savedId = await window.DB.add('transactions', settlement);
        }
        closeModal('settlement-modal'); 
        await loadData(); 
        if (typeof renderSettlements === 'function') renderSettlements();
        
        // Auto approve
        if (savedId && typeof window.approveSettlement === 'function') {
            await window.approveSettlement(savedId, true);
        }
    } catch(e) {`;
    
    js = js.replace(searchSave, replaceSave);

    fs.writeFileSync('app_final.js', js, 'utf8');
}

if (fs.existsSync('index.html')) {
    let html = fs.readFileSync('index.html', 'utf8');
    
    // Fix modal scrolling and sizing for smaller screens
    const searchModal = `<div class="modal-content" style="width: 900px;">
      <div class="modal-header">
        <h3 id="settlement-modal-title">تسوية عهدة جديدة</h3>`;
        
    const replaceModal = `<div class="modal-content" style="width: 95%; max-width: 900px; max-height: 90vh; overflow-y: auto;">
      <div class="modal-header">
        <h3 id="settlement-modal-title">تسوية عهدة جديدة</h3>`;
        
    html = html.replace(searchModal, replaceModal);
    
    // Fix buttons
    const searchButtons = `<button class="btn btn-secondary" style="margin-top:10px;" onclick="addSettlementRow()">+ إضافة سطر</button>
      </div>
      
      <div style="margin-top:20px; text-align:left; font-size:18px; font-weight:bold;">
         الإجمالي: <span id="settlement-total-amount">0</span> ج.م
      </div>
      <div style="margin-top:20px; text-align:left;">
        <button id="btn-print-settlement" class="btn btn-secondary" style="display:none; margin-left:10px; background-color:#17a2b8;">🖨️ طباعة التسوية</button>
        <button class="btn btn-primary" onclick="saveSettlement()">حفظ كمسودة (معلق)</button>
        <button class="btn btn-secondary" onclick="closeModal('settlement-modal')">إلغاء</button>
      </div>`;
      
    const replaceButtons = `<div style="text-align: right;">
          <button class="btn btn-secondary" style="margin-top:10px; background-color:#28a745; color:white; border:none; padding:10px 20px; font-size:16px; border-radius:5px;" onclick="addSettlementRow()">➕ إضافة سطر جديد للتسوية</button>
        </div>
      </div>
      
      <div style="margin-top:20px; text-align:left; font-size:18px; font-weight:bold; background: rgba(0,0,0,0.1); padding: 10px; border-radius: 5px;">
         إجمالي التسوية: <span id="settlement-total-amount" style="color:var(--primary); font-size:24px;">0</span> ج.م
      </div>
      <div style="margin-top:20px; text-align:left; display:flex; justify-content: flex-end; gap: 10px;">
        <button id="btn-print-settlement" class="btn btn-secondary" style="display:none; background-color:#17a2b8;">🖨️ طباعة التسوية</button>
        <button class="btn btn-secondary" onclick="closeModal('settlement-modal')">إلغاء</button>
        <button class="btn btn-primary" onclick="saveSettlement()" style="padding: 10px 30px; font-size: 16px; font-weight: bold;">💾 حفظ واعتماد مباشر</button>
      </div>`;
      
    html = html.replace(searchButtons, replaceButtons);
    
    // cache buster
    html = html.replace(/v=\d+/g, 'v=' + Date.now());
    
    fs.writeFileSync('index.html', html, 'utf8');
    console.log('Patched index.html and app_final.js successfully');
}
