window.getMultiSelectValues = function(id) {
    const el = document.getElementById(id);
    if (!el) return '';
    return Array.from(el.selectedOptions).map(o => o.value).join(', ');
};
window.setMultiSelectValues = function(id, valuesStr) {
      const el = document.getElementById(id);
      if (!el) return;
      if (!valuesStr) { 
          el.selectedIndex = -1; 
      } else {
          const values = valuesStr.split(',').map(v => v.trim());
          Array.from(el.options).forEach(opt => {
              opt.selected = values.includes(opt.value.trim());
          });
      }
      if (typeof el.updateCustomUI === 'function') {
          el.updateCustomUI();
      }
  };

// Digital Signature / Paper Approval Module
document.addEventListener('DOMContentLoaded', () => {
    // Populate all approver dropdowns once DB is ready
    setTimeout(async () => {
        if(!window.DB) return;
        const users = await window.DB.getAll('users') || [];
        const selects = ['custody-req-intended-approver', 'ab-intended-approver', 'client-ab-intended-approver'];
        selects.forEach(id => {
            const sel = document.getElementById(id);
            if(sel) {
                sel.innerHTML = '';
                sel.multiple = true;
                users.forEach(u => {
                    const opt = document.createElement('option');
                    opt.value = u.name || u.username;
                    opt.textContent = u.name || u.username;
                    sel.appendChild(opt);
                });
                if(window.setupMultiSelect) window.setupMultiSelect(id);
            }
        });
    }, 2000);
});

// Hook into Client Abstract open
const originalOpenClientAbstractModal = window.openClientAbstractModal;
if (originalOpenClientAbstractModal) {
    window.openClientAbstractModal = async function(id = null) {
        originalOpenClientAbstractModal.apply(this, arguments);
        
        setTimeout(async () => {
            const btnSign = document.getElementById('btn-sign-client-ab');
            const intendedSel = document.getElementById('client-ab-intended-approver');
            if(id) {
                const abs = await window.DB.getAll('client_abstracts') || [];
                const ab = abs.find(a => String(a.id) === String(id));
                if(ab && intendedSel) window.setMultiSelectValues('client-ab-intended-approver', ab.intended_approver || '');
                
                if (btnSign && ab) {
                    const cu = JSON.parse(sessionStorage.getItem('currentUser') || '{}');
                    const cname = cu.name || cu.username;
                    if ((ab.intended_approver || '').split(',').map(s=>s.trim()).includes(cname) && !(ab.paper_approved_by || '').split(',').some(s=>s.trim().startsWith(cname))) {
                        btnSign.style.display = 'inline-block';
                    } else {
                        btnSign.style.display = 'none';
                    }
                }
            } else {
                if(intendedSel) window.setMultiSelectValues('client-ab-intended-approver', '');
                if(btnSign) btnSign.style.display = 'none';
                const sigContainer = document.getElementById('client-abstract-signatures-container');
                  const sigList = document.getElementById('client-abstract-signatures-list');
                  if (sigContainer && sigList) {
                      sigContainer.style.display = 'none';
                      sigList.innerHTML = '';
                  }
            }
        }, 500);
    };
}

// Hook into saveClientAbstract to save the field
const originalSaveClientAbstract = window.saveClientAbstract;
if (originalSaveClientAbstract) {
    window.saveClientAbstract = async function() {
        const intendedSel = document.getElementById('client-ab-intended-approver');
        window.currentIntendedApproverForSave = window.getMultiSelectValues('client-ab-intended-approver');
        // We will intercept the DB update by monkey patching window.DB.add and update temporarily
        const oldAdd = window.DB.add;
        const oldUpdate = window.DB.update;
        
        window.DB.add = async function(store, data) {
            if(store === 'client_abstracts') data.intended_approver = window.currentIntendedApproverForSave;
            return oldAdd.apply(this, arguments);
        };
        window.DB.update = async function(store, data) {
            if(store === 'client_abstracts') data.intended_approver = window.currentIntendedApproverForSave;
            return oldUpdate.apply(this, arguments);
        };
        
        await originalSaveClientAbstract.apply(this, arguments);
        
        window.DB.add = oldAdd;
        window.DB.update = oldUpdate;
    };
}

window.signClientAbstract = async function() {
    const id = document.getElementById('edit-client-abstract-id').value;
    if(!id) return;
    if(!confirm("هل أنت متأكد من توقيع هذا المستخلص كمعتمد؟")) return;
    
    const abstracts = await window.DB.getAll('client_abstracts') || [];
    const ab = abstracts.find(a => String(a.id) === String(id));
    if(!ab) return;
    
    const cu = JSON.parse(sessionStorage.getItem('currentUser') || '{}');
    const cName = cu.name || cu.username;
    
    const dtNow = new Date().toLocaleString('ar-EG', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: true });
    const signedName = cName + ' - ' + dtNow;
    if (!ab.paper_approved_by) {
        ab.paper_approved_by = signedName;
    } else if (!(ab.paper_approved_by || '').split(',').some(s=>s.trim().startsWith(cName))) {
        ab.paper_approved_by += '<br>' + signedName;
    }
    
    await window.DB.update('client_abstracts', ab);
    document.getElementById('btn-sign-client-ab').style.display = 'none';
      const sigContainer = document.getElementById('client-abstract-signatures-container');
      const sigList = document.getElementById('client-abstract-signatures-list');
      if (sigContainer && sigList) {
          sigContainer.style.display = 'block';
          sigList.innerHTML = ab.paper_approved_by;
      }
      const sigContainer = document.getElementById('client-abstract-signatures-container');
      const sigList = document.getElementById('client-abstract-signatures-list');
      if (sigContainer && sigList) {
          sigContainer.style.display = 'block';
          sigList.innerHTML = ab.paper_approved_by;
      }
    alert("تم التوقيع بنجاح!");
};

// Hook into printClientAbstract
const originalPrintClientAbstract = window.printClientAbstract;
if (originalPrintClientAbstract) {
    window.printClientAbstract = async function(id) {
        const oldOpen = window.open;
        let mockWin = null;
        window.open = function() {
            mockWin = oldOpen.apply(this, arguments);
            const oldWrite = mockWin.document.write;
            mockWin.document.write = function(html) {
                // Find abstract to get paper_approved_by
                window.DB.getAll('client_abstracts').then(abs => {
                    const ab = abs.find(a => String(a.id) === String(id));
                    if (ab && ab.paper_approved_by) {
                        const sigBlock = '<p style="margin-top:50px; font-weight:bold; line-height:1.5;">توقيع المعتمد:<br>' + (ab.paper_approved_by || '').replace(/, /g, '<br>') + '</p>';
                        html = html.replace('</body>', sigBlock + '</body>');
                    }
                    oldWrite.call(mockWin.document, html);
                });
            };
            return mockWin;
        };
        
        await originalPrintClientAbstract.apply(this, arguments);
        
        window.open = oldOpen;
    };
}
