const fs = require('fs');

try {
    // 1. App Final JS
    let appFinalJs = fs.readFileSync('app_final.js', 'utf8');
    
    // Fix approveSettlement date
    appFinalJs = appFinalJs.replace(/date: s\.date,\s*reference:/g, "date: s.date && s.date.includes('T') ? s.date.split('T')[0] : s.date,\n                reference:");
    
    const relatedLinksFn = `
// --- CROSS LINKING ---
window.renderRelatedLinks = function(type, id, containerId) {
    const container = document.getElementById(containerId);
    if (!container) return;
    
    let html = '<div style="background: rgba(23, 162, 184, 0.1); padding: 10px; border-radius: 5px; border: 1px solid #17a2b8; margin-bottom: 15px;">';
    html += '<strong style="color: #17a2b8; display: block; margin-bottom: 8px;">🔗 حركات ومستندات مرتبطة:</strong>';
    let hasLinks = false;
    
    if (type === 'invoice') {
        const inv = allInvoices.find(i => i.id === id);
        if (inv) {
            if (inv.is_from_settlement && inv.settlement_ref) {
                html += \`<button class="btn btn-sm btn-info" style="margin-left: 5px; margin-bottom: 5px;" onclick="closeModal('details-modal'); viewSettlement(\${inv.settlement_ref})">👁️ عرض تسوية العهدة الأصلية</button>\`;
                hasLinks = true;
            }
            if (inv.type === 'purchases_return' || inv.type === 'sales_return') {
                if (inv.doc_no) {
                    const originalInv = allInvoices.find(i => String(i.id) === String(inv.doc_no) || String(i.doc_no) === String(inv.doc_no));
                    if (originalInv && originalInv.id !== inv.id) {
                        html += \`<button class="btn btn-sm btn-info" style="margin-left: 5px; margin-bottom: 5px;" onclick="closeModal('details-modal'); viewDetails(\${originalInv.id})">👁️ عرض الفاتورة الأصلية</button>\`;
                        hasLinks = true;
                    }
                }
            }
            if (inv.type === 'in' || inv.type === 'out' || inv.type === 'sales') {
                const returns = allInvoices.filter(i => (i.type === 'purchases_return' || i.type === 'sales_return') && (String(i.doc_no) === String(inv.id) || (inv.doc_no && String(i.doc_no) === String(inv.doc_no))));
                returns.forEach(r => {
                    html += \`<button class="btn btn-sm btn-warning" style="margin-left: 5px; margin-bottom: 5px; color:black;" onclick="closeModal('details-modal'); viewDetails(\${r.id})">👁️ عرض فاتورة مرتجع (#\${r.id})</button>\`;
                    hasLinks = true;
                });
            }
            if (typeof currentJournals !== 'undefined') {
                const relatedJournals = currentJournals.filter(j => 
                    (String(j.ref_id) === String(inv.id)) || 
                    (j.reference && j.reference.includes('#' + inv.id)) ||
                    (j.reference && j.reference.includes('_' + inv.id))
                );
                relatedJournals.forEach(j => {
                    if (new RegExp('\\\\b' + inv.id + '\\\\b').test(j.reference) || String(j.ref_id) === String(inv.id)) {
                        html += \`<button class="btn btn-sm" style="background:#6f42c1; color:white; margin-left: 5px; margin-bottom: 5px;" onclick="closeModal('details-modal'); openJournalModal(\${j.id})">📓 عرض قيد اليومية</button>\`;
                        hasLinks = true;
                    }
                });
            }
        }
    } else if (type === 'settlement') {
        const s = allInvoices.find(i => i.id === id);
        if (s) {
            if (typeof currentJournals !== 'undefined') {
                const settlementJournals = currentJournals.filter(j => j.type === 'settlement' && String(j.ref_id) === String(s.id));
                settlementJournals.forEach(j => {
                    html += \`<button class="btn btn-sm" style="background:#6f42c1; color:white; margin-left: 5px; margin-bottom: 5px;" onclick="closeModal('settlement-modal'); openJournalModal(\${j.id})">📓 عرض قيد المصروفات</button>\`;
                    hasLinks = true;
                });
            }
            const inventoryInvs = allInvoices.filter(i => i.is_from_settlement === true && String(i.settlement_ref) === String(s.id));
            inventoryInvs.forEach(inv => {
                html += \`<button class="btn btn-sm btn-info" style="margin-left: 5px; margin-bottom: 5px;" onclick="closeModal('settlement-modal'); viewDetails(\${inv.id})">📦 عرض إذن المخزن</button>\`;
                hasLinks = true;
            });
        }
    } else if (type === 'journal') {
        const j = currentJournals.find(x => x.id === id);
        if (j) {
            if (j.type === 'settlement' && j.ref_id) {
                html += \`<button class="btn btn-sm btn-info" style="margin-left: 5px; margin-bottom: 5px;" onclick="closeModal('journal-modal'); viewSettlement(\${j.ref_id})">👁️ عرض تسوية العهدة</button>\`;
                hasLinks = true;
            }
            if (j.reference) {
                const match = j.reference.match(/#(\\d+)/) || j.reference.match(/_(\\d+)$/);
                if (match && match[1]) {
                    const invId = parseInt(match[1]);
                    const relatedInv = allInvoices.find(i => i.id === invId);
                    if (relatedInv) {
                        html += \`<button class="btn btn-sm btn-info" style="margin-left: 5px; margin-bottom: 5px;" onclick="closeModal('journal-modal'); viewDetails(\${invId})">👁️ المستند المرتبط</button>\`;
                        hasLinks = true;
                    }
                }
            }
        }
    }
    
    html += '</div>';
    if (hasLinks) {
        container.innerHTML = html;
        container.style.display = 'block';
    } else {
        container.innerHTML = '';
        container.style.display = 'none';
    }
};
`;
    
    if (!appFinalJs.includes('window.renderRelatedLinks = function')) {
        appFinalJs += '\n' + relatedLinksFn;
    }
    
    appFinalJs = appFinalJs.replace(
        /btnHtml \+= `<button class="btn-secondary" onclick="closeModal\('details-modal'\)">إغلاق<\/button>`;\s*actions\.innerHTML = btnHtml;\s*showModal\('details-modal'\);/g,
        `btnHtml += \`<button class="btn-secondary" onclick="closeModal('details-modal')">إغلاق</button>\`;
  actions.innerHTML = btnHtml; 
  if (typeof renderRelatedLinks === 'function') renderRelatedLinks('invoice', inv.id, 'details-related-links');
  showModal('details-modal');`
    );
    
    appFinalJs = appFinalJs.replace(
        /if\(je\.rows && je\.rows\.length > 0\) {/g,
        `if(typeof renderRelatedLinks === 'function') renderRelatedLinks('journal', id, 'journal-related-links');
    if(je.rows && je.rows.length > 0) {`
    );
    
    appFinalJs = appFinalJs.replace(
        /document\.getElementById\('je-status'\)\.value = 'draft';/g,
        `document.getElementById('je-status').value = 'draft';
    if (document.getElementById('journal-related-links')) document.getElementById('journal-related-links').style.display = 'none';`
    );
    
    appFinalJs = appFinalJs.replace(
        /document\.getElementById\('settlement-modal-title'\)\.innerText = 'عرض تسوية عهدة #' \+ id;/g,
        `document.getElementById('settlement-modal-title').innerText = 'عرض تسوية عهدة #' + id;
    if (typeof renderRelatedLinks === 'function') renderRelatedLinks('settlement', id, 'settlement-related-links');`
    );
    
    appFinalJs = appFinalJs.replace(
        /document\.getElementById\('settlement-modal-title'\)\.innerText = 'تسوية عهدة جديدة';/g,
        `document.getElementById('settlement-modal-title').innerText = 'تسوية عهدة جديدة';
        if (document.getElementById('settlement-related-links')) document.getElementById('settlement-related-links').style.display = 'none';`
    );
    
    fs.writeFileSync('app_final.js', appFinalJs, 'utf8');
    
    // 2. Index HTML
    let indexHtml = fs.readFileSync('index.html', 'utf8');
    
    if (!indexHtml.includes('<div id="details-related-links"></div>')) {
        indexHtml = indexHtml.replace(
            /<div id="details-action-buttons" class="modal-actions" style="margin-top: 20px;">/g,
            `<div id="details-related-links"></div>\n      <div id="details-action-buttons" class="modal-actions" style="margin-top: 20px;">`
        );
    }
    
    if (!indexHtml.includes('<div id="journal-related-links"></div>')) {
        indexHtml = indexHtml.replace(
            /<div class="modal-actions" style="margin-top: 20px;">\s*<button class="btn-secondary" onclick="closeModal\('journal-modal'\)">إلغاء<\/button>/g,
            `<div id="journal-related-links"></div>\n      <div class="modal-actions" style="margin-top: 20px;">\n        <button class="btn-secondary" onclick="closeModal('journal-modal')">إلغاء</button>`
        );
    }
    
    if (!indexHtml.includes('<div id="settlement-related-links"></div>')) {
        indexHtml = indexHtml.replace(
            /<div style="margin-top:20px; text-align:left; font-size:18px; font-weight:bold; background: rgba\(0,0,0,0\.1\);/g,
            `<div id="settlement-related-links"></div>\n      <div style="margin-top:20px; text-align:left; font-size:18px; font-weight:bold; background: rgba(0,0,0,0.1);`
        );
    }
    
    indexHtml = indexHtml.replace(/v=\d+/g, 'v=' + Date.now());
    
    fs.writeFileSync('index.html', indexHtml, 'utf8');
    
    console.log('Cross links injected successfully!');
} catch (error) {
    console.error('Error during patch:', error);
}
