// Custody Requests Module
let custodyRequests = [];
let custodyReqItems = [];
    window.currentCustodyAttachments = [];
    if(document.getElementById('custody-req-attachments-list')) document.getElementById('custody-req-attachments-list').innerHTML = '';
    if(document.getElementById('custody-req-attachment-input')) document.getElementById('custody-req-attachment-input').value = '';
let currentCustodyReqId = null;

async function loadCustodyRequests() {
    try {
        custodyRequests = await window.DB.getAll('custody_requests') || [];
    } catch (e) {
        console.error("Error loading custody requests:", e);
    }
}

window.renderCustodyRequests = async function() {
    await loadCustodyRequests();
    const tbody = document.getElementById('custody-requests-tbody');
    if (!tbody) return;
    
    const search = document.getElementById('custody-req-search').value.toLowerCase();
    const currentUser = JSON.parse(sessionStorage.getItem('currentUser') || '{}');
    const isAdmin = currentUser.role === 'مدير عام';
    const allowedProjectIds = currentUser.allowed_projects || [];
    const allowedProjectNames = typeof currentProjects !== 'undefined' ? currentProjects.filter(p => allowedProjectIds.includes(parseInt(p.id))).map(p => p.name) : [];
    
    let filtered = custodyRequests.filter(req => {
        const isOwner = req.requester === currentUser.username || req.requester === currentUser.name;
        const isProjectAllowed = allowedProjectNames.includes(req.project);
        
        if (!isAdmin && !isOwner && !isProjectAllowed) {
            return false;
        }

        const matchSearch = (req.id && req.id.toString().includes(search)) || 
                            (req.project && req.project.toLowerCase().includes(search)) ||
                            (req.from && req.from.toLowerCase().includes(search)) ||
                            (req.requester && req.requester.toLowerCase().includes(search));
        return matchSearch;
    });

    // Sort by date descending
    filtered.sort((a, b) => new Date(b.date) - new Date(a.date));

    tbody.innerHTML = '';
    
    if (filtered.length === 0) {
        tbody.innerHTML = `<tr><td colspan="6" style="text-align:center;">لا توجد طلبات عهدة</td></tr>`;
        return;
    }

    filtered.forEach(req => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${req.date || ''}</td>
            <td>${req.project || ''}</td>
            <td>${req.requester || ''}</td>
            <td>${req.from || ''}</td>
            <td style="font-weight:bold;">${(req.total || 0).toLocaleString()} ج.م.</td>
            <td>
                <button class="action-btn btn-view" onclick="openCustodyRequestDetails('${req.id}')"><i class="fas fa-eye"></i> عرض</button>
                <button class="action-btn btn-delete" onclick="deleteCustodyRequest('${req.id}')"><i class="fas fa-trash"></i> حذف</button>
            </td>
        `;
        tbody.appendChild(tr);
    });
};

window.openCustodyRequestDetails = async function(id = null) {
    currentCustodyReqId = id;
    custodyReqItems = [];
    
    const tbody = document.getElementById('custody-req-items');
    tbody.innerHTML = '';
    
    document.getElementById('custody-req-comments-list').innerHTML = '';
    
    // Populate projects dropdown
    const projectSelect = document.getElementById('custody-req-project');
    const projects = await window.DB.getAll('projects') || [];
    projectSelect.innerHTML = '<option value="">اختيار الموقع...</option>';
    projects.forEach(p => {
        const opt = document.createElement('option');
        opt.value = p.name;
        opt.textContent = p.name;
        projectSelect.appendChild(opt);
    });
    
    // Populate users datalist
    const usersList = document.getElementById('custody-users-list');
    const users = await window.DB.getAll('users') || [];
    usersList.innerHTML = '';
    users.forEach(u => {
        const opt = document.createElement('option');
        opt.value = u.username || u.name;
        usersList.appendChild(opt);
    });
    const intendedApproverSelect = document.getElementById('custody-req-intended-approver');
    if(intendedApproverSelect) {
        intendedApproverSelect.innerHTML = '<option value="">اختر المعتمد...</option>';
        users.forEach(u => {
            const opt = document.createElement('option');
            opt.value = u.name || u.username;
            opt.textContent = u.name || u.username;
            intendedApproverSelect.appendChild(opt);
        });
          if(window.setupMultiSelect) window.setupMultiSelect('custody-req-intended-approver');
    }

    // Populate transfer vouchers
    const transferSelect = document.getElementById('custody-req-transfer');
    if (transferSelect) {
        const vouchers = await window.DB.getAll('transactions') || [];
        const transfers = vouchers.filter(v => v.type === 'money_transfer');
        transferSelect.innerHTML = '<option value="">بدون سند...</option>';
        transfers.sort((a,b) => new Date(b.date || 0) - new Date(a.date || 0)).forEach(v => {
            const opt = document.createElement('option');
            opt.value = v.id;
            opt.textContent = `سند #${v.id} - ${v.total || v.amount || 0} ج.م - ${new Date(v.date).toLocaleDateString('ar-EG')}`;
            transferSelect.appendChild(opt);
        });
        transferSelect.onchange = function() {
            document.getElementById('btn-view-custody-transfer').style.display = this.value ? 'inline-block' : 'none';
        };
    }

    const currentUser = JSON.parse(sessionStorage.getItem('currentUser') || '{}');

    // Load settings for print logo
    try {
        const settings = await window.DB.getAll('settings');
        if (settings && settings.length > 0) {
            const currentSettings = settings[0];
            const logoImg = document.getElementById('custody-company-logo');
            const nameH3 = document.getElementById('custody-company-name');
            if (currentSettings.companyName) {
                nameH3.innerText = currentSettings.companyName;
            }
            if (currentSettings.companyLogo) {
                logoImg.src = currentSettings.companyLogo;
                logoImg.style.display = 'inline-block';
            } else {
                logoImg.style.display = 'none';
            }
        }
    } catch(e) {
        console.error("Error loading settings for custody req", e);
    }

    if (id) {
        await loadCustodyRequests();
        const req = custodyRequests.find(r => String(r.id) === String(id));
        if (req) {
            document.getElementById('custody-req-id').value = req.id;
            document.getElementById('custody-req-date').value = req.date || '';
            document.getElementById('custody-req-project').value = req.project || '';
            document.getElementById('custody-req-from').value = req.from || '';
        if(document.getElementById('custody-req-intended-approver')) {
            if(window.setMultiSelectValues) window.setMultiSelectValues('custody-req-intended-approver', req.intended_approver || ''); else document.getElementById('custody-req-intended-approver').value = req.intended_approver || '';
        }
        
        if (document.getElementById('custody-req-reference')) document.getElementById('custody-req-reference').value = req.reference || '';
        if (document.getElementById('custody-req-transfer')) {
            document.getElementById('custody-req-transfer').value = req.transfer_voucher_id || '';
            document.getElementById('btn-view-custody-transfer').style.display = req.transfer_voucher_id ? 'inline-block' : 'none';
        }

        const sigContainer = document.getElementById('custody-req-signatures-container');
        const sigList = document.getElementById('custody-req-signatures-list');
        if (sigContainer && sigList) {
            if (req.paper_approved_by) {
                sigContainer.style.display = 'block';
                sigList.innerHTML = req.paper_approved_by;
            } else {
                sigContainer.style.display = 'none';
                sigList.innerHTML = '';
            }
        }
        const btnSign = document.getElementById('btn-sign-custody');
        if (btnSign) {
            const currentName = currentUser.name || currentUser.username;
            if ((req.intended_approver || '').split(',').map(s=>s.trim()).includes(currentName) && !(req.paper_approved_by || '').split(',').some(s=>s.trim().startsWith(currentName))) {
                btnSign.style.display = 'inline-block';
            } else {
                btnSign.style.display = 'none';
            }
        }
            
            document.getElementById('custody-req-requester').innerText = req.requester || '';
            document.getElementById('custody-req-balance').innerText = (req.requesterBalance || 0).toLocaleString() + ' ج.م.';
            
            if (req.items && req.items.length) {
                req.items.forEach(item => window.addCustodyReqRow(item));
            }
            

            if (req.attachments && req.attachments.length) {
                window.currentCustodyAttachments = [...req.attachments];
                window.renderCustodyAttachments();
            }

            if (req.comments && req.comments.length) {
                req.comments.forEach(c => renderCustodyReqComment(c));
            }
        }
    } else {
        // New
        document.getElementById('custody-req-id').value = '';
        document.getElementById('custody-req-date').value = new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().split('T')[0];
        document.getElementById('custody-req-project').value = '';
        document.getElementById('custody-req-from').value = '';
        if(document.getElementById('custody-req-intended-approver')) {
            if(window.setMultiSelectValues) window.setMultiSelectValues('custody-req-intended-approver', '');
            else document.getElementById('custody-req-intended-approver').value = '';
        }
        
        if (document.getElementById('custody-req-reference')) document.getElementById('custody-req-reference').value = '';
        if (document.getElementById('custody-req-transfer')) {
            document.getElementById('custody-req-transfer').value = '';
            document.getElementById('btn-view-custody-transfer').style.display = 'none';
        }

        const sigContainer = document.getElementById('custody-req-signatures-container');
        const sigList = document.getElementById('custody-req-signatures-list');
        if (sigContainer && sigList) {
            sigContainer.style.display = 'none';
            sigList.innerHTML = '';
        }
        const btnSign = document.getElementById('btn-sign-custody');
        if(btnSign) btnSign.style.display = 'none';
        let reqUsername = currentUser.username || currentUser.name || '';
        document.getElementById('custody-req-requester').innerText = reqUsername;
        let cBal = window.getUserCustodyBalance(reqUsername);
        if (typeof cBal === 'number') {
            document.getElementById('custody-req-balance').innerText = Math.abs(cBal).toLocaleString('ar-EG') + (cBal >= 0 ? ' مدين' : ' دائن');
        } else {
            document.getElementById('custody-req-balance').innerText = cBal;
        }
        


        window.addCustodyReqRow();
    }
    
    window.calcCustodyReqTotal();
    
    if (typeof showView === 'function') {
        showView('view-custody-request-details');
    } else {
        document.querySelectorAll('.view').forEach(v => { 
            v.style.display = ''; 
            v.classList.remove('active'); 
        });
        const targetView = document.getElementById('view-custody-request-details');
        if(targetView) {
            targetView.style.display = '';
            targetView.classList.add('active');
        }
    }
};

window.viewCustodyTransfer = function() {
    const transferId = document.getElementById('custody-req-transfer').value;
    if (transferId) {
        if (typeof window.editTransfer === 'function') {
            window.editTransfer(transferId);
        } else if (typeof window.editVoucher === 'function') {
            window.editVoucher(transferId);
        } else {
            console.error("No function found to view transfer.");
        }
    }
};

window.addCustodyReqRow = function(item = {}) {
    const tbody = document.getElementById('custody-req-items');
    const tr = document.createElement('tr');
    
    tr.innerHTML = `
        <td style="text-align:center; font-size:18px; font-weight:bold;" class="row-index"></td>
        <td><textarea class="req-item-desc" rows="1" placeholder="البيان..." oninput="this.style.height = '1px'; this.style.height = this.scrollHeight + 'px'" style="width:100%; border:none; background:transparent; font-size:14px; font-weight:bold; font-family:'Cairo'; resize:none; overflow:hidden; min-height:22px; padding:2px 0; margin:0; line-height:1.4;">${item.description || ''}</textarea></td>
        <td><input type="number" class="req-item-val" placeholder="0" value="${item.value || ''}" onkeyup="calcCustodyReqTotal()" onchange="calcCustodyReqTotal()" style="width:100%; border:none; background:transparent; font-size:14px; font-weight:bold; font-family:'Cairo'; text-align:center;"></td>
        <td>
           <select class="req-item-ref-type" onchange="window.renderRowRefDropdown(this)" style="width:100%; border:none; font-family:'Cairo'; margin-bottom:2px; background:transparent; font-size:13px; font-weight:bold; padding:0;" title="نوع المرجع">
              <option value="">بدون مرجع</option>
              <option value="payroll" ${item.reference_type === 'payroll' ? 'selected' : ''}>مسير رواتب</option>
              <option value="supplier_invoice" ${item.reference_type === 'supplier_invoice' ? 'selected' : ''}>فاتورة مشتريات</option>
              <option value="abstract" ${item.reference_type === 'abstract' ? 'selected' : ''}>مستخلص مقاول باطن</option>
              <option value="payment_voucher" ${item.reference_type === 'payment_voucher' ? 'selected' : ''}>سند صرف</option>
           </select>
           <div class="ref-target-container" style="display:${item.reference_type ? 'flex' : 'none'}; gap:4px; align-items:center; margin-top:2px; width:100%; min-width:0;">
               <select class="req-item-ref-target" onchange="this.title = this.options[this.selectedIndex].text; const btn = this.nextElementSibling; if(btn) btn.style.display = this.value ? 'block' : 'none';" style="flex:1; min-width:0; border:none; font-family:'Cairo'; background:transparent; font-size:13px; padding:0; text-overflow:ellipsis; overflow:hidden; white-space:nowrap;" title="${item.reference_label || ''}">
                  ${item.reference_id ? `<option value="${item.reference_id}">${item.reference_label || item.reference_id}</option>` : ''}
               </select>
               <button type="button" class="btn-secondary no-print btn-view-ref" style="display:${item.reference_id ? 'block' : 'none'}; padding:2px 5px; font-size:12px; flex-shrink:0; white-space:nowrap;" onclick="window.viewCustodyReference(this.closest('tr').querySelector('.req-item-ref-type').value, this.previousElementSibling.value)" title="عرض المرجع">
                   <i class="fas fa-external-link-alt"></i>
               </button>
           </div>
        </td>
        <td class="no-print" style="text-align:center;"><button class="action-btn btn-danger" onclick="this.closest('tr').remove(); calcCustodyReqTotal()"><i class="fas fa-times"></i></button></td>
    `;
    tbody.appendChild(tr);
    updateCustodyReqIndexes();
    if (item.reference_type && !item.reference_label) {
       window.renderRowRefDropdown(tr.querySelector('.req-item-ref-type'), item.reference_id);
    }
    setTimeout(() => {
        const textareas = tr.querySelectorAll('textarea');
        textareas.forEach(ta => {
            ta.style.height = '1px';
            ta.style.height = ta.scrollHeight + 'px';
        });
    }, 10);
};

function updateCustodyReqIndexes() {
    const tbody = document.getElementById('custody-req-items');
    Array.from(tbody.children).forEach((tr, index) => {
        tr.querySelector('.row-index').innerText = index + 1;
    });
}

window.calcCustodyReqTotal = function() {
    const tbody = document.getElementById('custody-req-items');
    let total = 0;
    Array.from(tbody.children).forEach(tr => {
        const val = parseFloat(tr.querySelector('.req-item-val').value) || 0;
        total += val;
    });
    document.getElementById('custody-req-total').innerText = total.toLocaleString() + ' ج.م.';
    return total;
};

window.saveCustodyRequest = async function() {
    const id = document.getElementById('custody-req-id').value;
    const reqDate = document.getElementById('custody-req-date').value;
    const project = document.getElementById('custody-req-project').value;
    const fromUser = document.getElementById('custody-req-from').value;
    const reqRef = document.getElementById('custody-req-reference') ? document.getElementById('custody-req-reference').value : '';
    const transferId = document.getElementById('custody-req-transfer') ? document.getElementById('custody-req-transfer').value : '';
    const intendedApprover = document.getElementById('custody-req-intended-approver') ? (window.getMultiSelectValues ? window.getMultiSelectValues('custody-req-intended-approver') : document.getElementById('custody-req-intended-approver').value) : '';
    let paper_approved_by = document.getElementById('custody-req-signatures-list') ? document.getElementById('custody-req-signatures-list').innerHTML : '';

    const requester = document.getElementById('custody-req-requester').innerText;
    
    if(!reqDate || !project || !fromUser) {
        alert("يرجى ملء كافة الحقول (التاريخ، الموقع، المطلوب منه العهدة).");
        return;
    }
    
    const tbody = document.getElementById('custody-req-items');
    const items = [];
    Array.from(tbody.children).forEach(tr => {
        const typeSel = tr.querySelector('.req-item-ref-type');
        const targetSel = tr.querySelector('.req-item-ref-target');
        let refType = typeSel ? typeSel.value : '';
        let refId = targetSel ? targetSel.value : '';
        let refLabel = '';
        if (refType && refId && targetSel && targetSel.options[targetSel.selectedIndex]) {
            refLabel = targetSel.options[targetSel.selectedIndex].text;
        }

        items.push({
            description: tr.querySelector('.req-item-desc').value,
            value: parseFloat(tr.querySelector('.req-item-val').value) || 0,
            note: tr.querySelector('.req-item-note') ? tr.querySelector('.req-item-note').value : '',
            reference_type: refType,
            reference_id: refId,
            reference_label: refLabel
        });
    });
    
    const total = window.calcCustodyReqTotal();

    const comments = [];
    document.querySelectorAll('.custody-req-comment').forEach(div => {
        comments.push({
            id: div.dataset.id,
            user: div.dataset.user,
            text: div.dataset.text,
            timestamp: div.dataset.timestamp
        });
    });

    const custodyRequests = await window.DB.getAll('custody_requests') || [];
    
    let reqData;
    if (id) {
        // Edit existing
        const existingRecord = custodyRequests.find(r => String(r.id) === String(id));
        reqData = existingRecord ? { ...existingRecord } : {};
        
        reqData.date = reqDate;
        reqData.project = project;
        reqData.from = fromUser;
        reqData.requester = requester;
        reqData.requesterBalance = parseFloat(document.getElementById('custody-req-balance').innerText) || 0;
        reqData.items = items;
        reqData.total = total;
        reqData.intended_approver = intendedApprover;
        reqData.paper_approved_by = paper_approved_by;
        reqData.comments = comments;
        reqData.reference = reqRef;
        reqData.transfer_voucher_id = transferId;
        reqData.attachments = window.currentCustodyAttachments || [];
        
        reqData.id = id; // Ensure ID is present
        await window.DB.update('custody_requests', reqData);
    } else {
        // Create new
        reqData = {
            date: reqDate,
            project,
            from: fromUser,
            requester,
            requesterBalance: parseFloat(document.getElementById('custody-req-balance').innerText) || 0,
            items,
            total,
            intended_approver: intendedApprover,
            paper_approved_by: paper_approved_by,
            status: 'pending',
            comments,
            reference: reqRef,
            transfer_voucher_id: transferId,
            attachments: window.currentCustodyAttachments || []
        };
        await window.DB.add('custody_requests', reqData);
    }
    
    
    if (reqData.intended_approver) {
        let approvers = Array.isArray(reqData.intended_approver) ? reqData.intended_approver : reqData.intended_approver.split(',').map(s=>s.trim());
        const currentUser = JSON.parse(sessionStorage.getItem('currentUser') || '{}');
        const sender = currentUser.name || currentUser.username || '';
        
        try {
            const users = await window.DB.getAll('users');
            for (let appr of approvers) {
                if (!appr) continue;
                let u = users.find(x => x.name === appr || x.username === appr);
                let targetUser = u ? (u.username || u.name) : appr;
                
                let msg = `تم إنشاء/تعديل عهدة مالية (${reqData.date}) بقيمة ${reqData.total} لمراجعته لاعتماده (بواسطة ${sender}).`;
                await window.DB.add('notifications', {
                    user: targetUser,
                    message: msg,
                    date: new Date().toISOString(),
                    read: false,
                    custody_id: reqData.id
                });
                
                if (window.fetch) {
                    const pushRes = await fetch('api.php?store=send_push', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({ user: targetUser, title: 'طلب عهدة مالية', body: msg, link: "openCustodyRequestDetails('" + reqData.id + "')" })
                    });
                    const pushResultText = await pushRes.text();
                    if(pushResultText.includes('error') || pushResultText.includes('Failed')) {
                        throw new Error('Push API returned: ' + pushResultText);
                    }
                }
            }
        } catch (e) {
            console.error(e);
            alert("حدث خطأ أثناء إرسال الإشعار الخارجي: " + e.message);
        }
    }
    
    alert("تم الحفظ بنجاح!");

    window.closeCustodyRequestDetails();
};

window.closeCustodyRequestDetails = function() {
    if (typeof showView === 'function') {
        showView('view-custody-requests');
    } else {
        document.querySelectorAll('.view').forEach(v => { 
            v.style.display = ''; 
            v.classList.remove('active'); 
        });
        const targetView = document.getElementById('view-custody-requests');
        if (targetView) {
            targetView.style.display = '';
            targetView.classList.add('active');
        }
        window.renderCustodyRequests();
    }
};

// Comments and Mentions
window.addCustodyReqComment = async function() {
    const input = document.getElementById('custody-req-new-comment');
    const text = input.value.trim();
    if(!text) return;
    
    const currentUser = JSON.parse(sessionStorage.getItem('currentUser') || '{}');
    const comment = {
        id: Date.now().toString(),
        user: currentUser.name || 'مستخدم',
        text: text,
        timestamp: new Date().toISOString()
    };
    
    renderCustodyReqComment(comment);
    input.value = '';
    
    const id = document.getElementById('custody-req-id').value;
    if(id) {
        await loadCustodyRequests();
        const req = custodyRequests.find(r => String(r.id) === String(id));
        if(req) {
            req.comments = req.comments || [];
            req.comments.push(comment);
            await window.DB.update('custody_requests', req);
        }
    }
};

function renderCustodyReqComment(comment) {
    const list = document.getElementById('custody-req-comments-list');
    const div = document.createElement('div');
    div.dataset.id = comment.id;
    div.dataset.user = comment.user;
    div.dataset.text = comment.text;
    div.dataset.timestamp = comment.timestamp;
    div.className = 'custody-req-comment';
    
    div.style.marginBottom = '10px';
    div.style.padding = '8px';
    div.style.background = '#f9f9f9';
    div.style.borderRadius = '5px';
    div.style.borderLeft = '3px solid var(--primary)';
    
    let htmlText = comment.text.replace(/@([^\s]+)/g, '<span style="color:var(--primary); font-weight:bold;">@$1</span>');
    
    div.innerHTML = `
        <div style="font-size:12px; color:#666; margin-bottom:4px;">
            <strong>${comment.user}</strong> - ${new Date(comment.timestamp).toLocaleString('ar-EG')}
        </div>
        <div style="font-size:14px;">${htmlText}</div>
    `;
    list.appendChild(div);
    list.scrollTop = list.scrollHeight;
}

// Print
window.printCustodyRequest = function() {
    const printArea = document.getElementById('custody-request-print-area');
    
    // Create a clone to manipulate for printing
    const clone = printArea.cloneNode(true);
    
    // Replace inputs and selects with spans to allow text wrapping and preserve values
    const originalInputs = printArea.querySelectorAll('input, textarea, select');
    const cloneInputs = clone.querySelectorAll('input, textarea, select');
    
    originalInputs.forEach((orig, index) => {
        const clonedEl = cloneInputs[index];
        if (!clonedEl) return;
        
        let displayVal = orig.value || '';
        if (orig.tagName === 'SELECT') {
            const selectedOption = orig.options[orig.selectedIndex];
            if (selectedOption) {
                // If it's the placeholder option, don't print it
                displayVal = orig.value ? selectedOption.text : '';
            }
        }
        
        const span = document.createElement('span');
        span.textContent = displayVal;
        
        span.style.fontFamily = "'Cairo', sans-serif";
        span.style.fontSize = '16px';
        span.style.fontWeight = 'bold';
        span.style.whiteSpace = 'pre-wrap';
        span.style.wordBreak = 'break-word';
        span.style.display = orig.style.display === 'none' ? 'none' : 'block';
        span.style.width = '100%';
        if (orig.style.textAlign) span.style.textAlign = orig.style.textAlign;
        
        clonedEl.parentNode.replaceChild(span, clonedEl);
    });
    
    // Remove no-print elements from the clone
    const noPrint = clone.querySelectorAll('.no-print');
    noPrint.forEach(el => el.remove());
    
    const printContent = clone.innerHTML;
    const originalContent = document.body.innerHTML;
    
    document.body.innerHTML = printContent;
    document.body.style.backgroundColor = 'white';
    
    // Force some CSS for better printing
    const style = document.createElement('style');
    style.innerHTML = `
        @media print {
            table { width: 100% !important; border-collapse: collapse; }
            td, th { word-wrap: break-word !important; overflow-wrap: break-word !important; }
        }
    `;
    document.head.appendChild(style);
    
    window.print();
    
    // Restore
    document.body.innerHTML = originalContent;
    window.location.reload();
};

// WhatsApp
window.sendCustodyWhatsApp = async function() {
    // Show a loading indicator on the button
    const btn = document.querySelector('button[onclick="sendCustodyWhatsApp()"]');
    const originalBtnText = btn ? btn.innerHTML : '';
    if (btn) btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> جاري تجهيز الصورة...';

    try {
        // 1. Load html2canvas dynamically if not available
        if (typeof html2canvas === 'undefined') {
            await new Promise((resolve, reject) => {
                const script = document.createElement('script');
                script.src = 'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js';
                script.onload = resolve;
                script.onerror = reject;
                document.head.appendChild(script);
            });
        }

        const printArea = document.getElementById('custody-request-print-area');
        
        // 2. Hide no-print elements
        const noPrintElements = printArea.querySelectorAll('.no-print');
        const originalDisplays = [];
        noPrintElements.forEach(el => {
            originalDisplays.push(el.style.display);
            el.style.display = 'none';
        });

        // 3. Add Easy ERP watermark footer
        let watermark = document.getElementById('easy-erp-watermark');
        if (!watermark) {
            watermark = document.createElement('div');
            watermark.id = 'easy-erp-watermark';
            watermark.innerHTML = '<i class="fas fa-check-circle" style="color: #27ae60;"></i> تم إنشاء واعتماد هذا الطلب آلياً بواسطة نظام <strong>Easy ERP</strong> لإدارة المشروعات';
            watermark.style.cssText = 'text-align: center; color: #555; font-size: 16px; margin-top: 30px; font-weight: bold; border-top: 2px dashed #ccc; padding-top: 15px; font-family: "Cairo";';
            printArea.appendChild(watermark);
        }

        // 4. Temporarily force desktop width to fix mobile rendering
        const originalPrintAreaStyles = {
            width: printArea.style.width,
            maxWidth: printArea.style.maxWidth,
            padding: printArea.style.padding
        };
        printArea.style.width = '800px';
        printArea.style.maxWidth = 'none';
        printArea.style.padding = '20px';

        const tableContainer = document.querySelector('#custody-request-print-area div[style*="overflow-x"]');
        let originalOverflowX = '';
        if (tableContainer) {
            originalOverflowX = tableContainer.style.overflowX;
            tableContainer.style.overflowX = 'visible';
        }

        // Capture
        const canvas = await html2canvas(printArea, { 
            scale: 2, 
            backgroundColor: '#ffffff',
            useCORS: true,
            windowWidth: 850 // Trick html2canvas into thinking the window is wide
        });

        // Restore DOM
        printArea.style.width = originalPrintAreaStyles.width;
        printArea.style.maxWidth = originalPrintAreaStyles.maxWidth;
        printArea.style.padding = originalPrintAreaStyles.padding;
        
        if (tableContainer) {
            tableContainer.style.overflowX = originalOverflowX;
        }

        noPrintElements.forEach((el, index) => {
            el.style.display = originalDisplays[index];
        });
        if (watermark) watermark.remove();

        // 5. Share or Download
        canvas.toBlob(async (blob) => {
            if (!blob) {
                alert("حدث خطأ أثناء إنشاء الصورة.");
                if (btn) btn.innerHTML = originalBtnText;
                return;
            }
            
            const file = new File([blob], 'Custody_Request.png', { type: 'image/png' });

            // Check if Web Share API is supported and can share files
            const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
            if (isMobile && navigator.canShare && navigator.canShare({ files: [file] })) {
                try {
                    await navigator.share({
                        files: [file],
                        title: 'طلب عهدة',
                        text: 'مرفق صورة طلب عهدة من نظام Easy ERP'
                    });
                } catch (err) {
                    console.log('Share cancelled or failed', err);
                    // If user just cancelled, we don't necessarily need to force download, 
                    // but it's safe to offer it.
                }
            } else {
                // Fallback for desktop browsers that don't support file sharing to WhatsApp
                const a = document.createElement('a');
                a.href = URL.createObjectURL(blob);
                a.download = 'Custody_Request.png';
                a.click();
                URL.revokeObjectURL(a.href);
                
                // Open WhatsApp Web with a pre-filled message telling them to attach the downloaded image
                const text = `مرحباً، مرفق صورة طلب العهدة من نظام Easy ERP.\n(يرجى إرفاق الصورة التي تم تحميلها للتو)`;
                const url = `https://wa.me/?text=${encodeURIComponent(text)}`;
                window.open(url, '_blank');
            }
            
            if (btn) btn.innerHTML = originalBtnText;
        }, 'image/png');

    } catch (error) {
        console.error("Error generating image:", error);
        alert("حدث خطأ أثناء تجهيز الصورة للمشاركة.");
        if (btn) btn.innerHTML = originalBtnText;
    }
};

// Mention dropdown logic (simplified generic approach)
let mentionUsers = [];
window.handleMentionInput = async function(inputElem) {
    const val = inputElem.value;
    const dropdown = inputElem.nextElementSibling;
    
    const lastAtIdx = val.lastIndexOf('@');
    if(lastAtIdx !== -1 && (lastAtIdx === 0 || val[lastAtIdx-1] === ' ')) {
        const query = val.substring(lastAtIdx + 1).toLowerCase();
        
        if(mentionUsers.length === 0) {
            mentionUsers = await window.DB.getAll('users') || [];
        }
        
        const matches = mentionUsers.filter(u => (u.name||'').toLowerCase().includes(query) || (u.username||'').toLowerCase().includes(query));
        
        if(matches.length > 0) {
            dropdown.innerHTML = '';
            matches.forEach(u => {
                const div = document.createElement('div');
                div.className = 'mention-item';
                div.style.padding = '5px 10px';
                div.style.cursor = 'pointer';
                div.innerText = u.name || u.username;
                div.onclick = function() {
                    inputElem.value = val.substring(0, lastAtIdx) + '@' + (u.name || u.username) + ' ';
                    dropdown.style.display = 'none';
                    inputElem.focus();
                };
                dropdown.appendChild(div);
            });
            dropdown.style.display = 'block';
        } else {
            dropdown.style.display = 'none';
        }
    } else {
        dropdown.style.display = 'none';
    }
};

// Document click to hide dropdown
document.addEventListener('click', function(e) {
    if(!e.target.closest('.flex-row')) {
        document.querySelectorAll('.mention-dropdown-generic').forEach(d => d.style.display = 'none');
    }
});

// Initial hook
window.getUserCustodyBalance = function(username) {
    try {
        if (!username || typeof username !== 'string') return 'Err: No username';
        if (typeof currentAccounts === 'undefined' || !currentAccounts) return 'Err: No currentAccounts';
        if (typeof currentJournals === 'undefined' || !currentJournals) return 'Err: No currentJournals';
        if (typeof currentUsers === 'undefined' || !currentUsers) return 'Err: No currentUsers';
        
        const userObj = currentUsers.find(u => u.username === username || u.name === username);
        if (!userObj) return 'Err: User Not Found';

        let custodyAcc = null;
        if (userObj && userObj.custody_account_id) {
            custodyAcc = currentAccounts.find(a => String(a.id) === String(userObj.custody_account_id));
        }
        
        if (!custodyAcc) {
            const searchName = username.trim().toLowerCase();
            custodyAcc = currentAccounts.find(a => 
                (a.name || '').includes('عهدة') && (a.name || '').toLowerCase().includes(searchName)
            );
        }
        
        if (!custodyAcc) return 'Err: Acc Not Found';
        
        let runningBalance = (parseFloat(custodyAcc.op_debit) || 0) - (parseFloat(custodyAcc.op_credit) || 0);
        
        currentJournals.forEach(j => {
            if (j.status !== 'posted') return;
            if (j.rows) {
                j.rows.forEach(r => {
                    if (String(r.account_id) === String(custodyAcc.id)) {
                        runningBalance += (parseFloat(r.debit) || 0) - (parseFloat(r.credit) || 0);
                    }
                });
            }
        });
        
        return runningBalance;
    } catch(e) {
        return 'Err: ' + e.message;
    }
};

document.addEventListener('DOMContentLoaded', () => {
    // We already hooked the nav clicks in app_final.js.
    // When custody-requests is clicked, render is called if we bind it.
    const nav = document.getElementById('nav-custody-requests');
    if(nav) {
        nav.addEventListener('click', () => {
            renderCustodyRequests();
        });
    }
});


window.signCustodyRequest = async function() {
    if(!currentCustodyReqId) return;
    const req = custodyRequests.find(r => String(r.id) === String(currentCustodyReqId));
    if(!req) return;
    
    if(!confirm("هل أنت متأكد من توقيع هذا الطلب كمعتمد؟")) return;
    
    const currentUser = JSON.parse(sessionStorage.getItem('currentUser') || '{}');
    const cName = currentUser.name || currentUser.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 (!req.paper_approved_by) {
        req.paper_approved_by = signedName;
    } else if (!(req.paper_approved_by || '').split(',').some(s=>s.trim().startsWith(cName))) {
        req.paper_approved_by += ', ' + signedName;
    }
    
    await window.DB.update('custody_requests', req);
    custodyRequests = await window.DB.getAll('custody_requests') || [];
    
    const sigContainer = document.getElementById('custody-req-signatures-container');
      const sigList = document.getElementById('custody-req-signatures-list');
      if (sigContainer && sigList) {
          sigContainer.style.display = 'block';
          sigList.innerHTML = req.paper_approved_by;
      }
    document.getElementById('btn-sign-custody').style.display = 'none';
    
    
    const currentUserForNotif = JSON.parse(sessionStorage.getItem('currentUser') || '{}');
    
    window.DB.getAll('users').then(users => {
        let targets = new Set();
        
        if (req.from) {
            let uFrom = users.find(x => x.name === req.from || x.username === req.from);
            let targetFrom = uFrom ? (uFrom.username || uFrom.name) : req.from;
            targets.add(targetFrom); // Allow self notification
        }
        
        if (req.requester) {
            let uReq = users.find(x => x.name === req.requester || x.username === req.requester);
            let targetReq = uReq ? (uReq.username || uReq.name) : req.requester;
            targets.add(targetReq); // Allow self notification
        }
        
        targets.forEach(targetUser => {
            let msg = `تم توقيع طلب العهدة (${req.date}) من قبل المعتمد: ${cName}.`;
            window.DB.add('notifications', {
                user: targetUser,
                message: msg,
                date: new Date().toISOString(),
                read: false,
                custody_id: req.id
            }).catch(e=>console.error(e));
        });
    }).catch(e=>console.error(e));

    alert("تم التوقيع بنجاح!");

};

window.renderRowRefDropdown = async function(typeSel, selectedId = null) {
    const tr = typeSel.closest('tr');
    const targetSel = tr.querySelector('.req-item-ref-target');
    const container = tr.querySelector('.ref-target-container');
    const btn = tr.querySelector('.btn-view-ref');
    if (!targetSel || !container) return;
    
    const type = typeSel.value;
    if (!type) {
        container.style.display = 'none';
        targetSel.innerHTML = '';
        if(btn) btn.style.display = 'none';
        return;
    }
    
    container.style.display = 'flex';
    targetSel.innerHTML = '<option value="">جاري التحميل...</option>';
    if(btn) btn.style.display = 'none';
    
    if (type === 'payroll') {
        const payrolls = await window.DB.getAll('payrolls') || [];
        targetSel.innerHTML = '<option value="">اختر مسير الرواتب...</option>';
        payrolls.sort((a,b) => new Date(b.created_at || 0) - new Date(a.created_at || 0)).forEach(p => {
            const opt = document.createElement('option');
            opt.value = String(p.id);
            opt.textContent = `مسير #${p.id} - ${p.month || p.date || ''} ${p.name ? '('+p.name+')' : ''}`;
            if (String(p.id) === String(selectedId)) opt.selected = true;
            targetSel.appendChild(opt);
        });
    } else if (type === 'supplier_invoice') {
        const trans = await window.DB.getAll('transactions') || [];
        const contacts = await window.DB.getAll('contacts') || [];
        const invs = trans.filter(t => t.type === 'purchases');
        targetSel.innerHTML = '<option value="">اختر الفاتورة...</option>';
        invs.sort((a,b) => new Date(b.date || 0) - new Date(a.date || 0)).forEach(inv => {
            const supplier = contacts.find(c => String(c.id) === String(inv.contact_id)) || {};
            const supName = inv.supplier_name || supplier.name || 'مورد غير محدد';
            const opt = document.createElement('option');
            opt.value = String(inv.id);
            opt.textContent = `فاتورة #${inv.id} - ${supName} - ${parseFloat(inv.total || 0).toFixed(2)} ج.م`;
            opt.title = opt.textContent;
            if (String(inv.id) === String(selectedId)) opt.selected = true;
            targetSel.appendChild(opt);
        });
    } else if (type === 'abstract') {
        const abstracts = await window.DB.getAll('subcontract_abstracts') || [];
        const scs = await window.DB.getAll('subcontracts') || [];
        const contacts = await window.DB.getAll('contacts') || [];
        
        targetSel.innerHTML = '<option value="">اختر المستخلص...</option>';
        abstracts.forEach(ab => {
            const sc = scs.find(s => String(s.id) === String(ab.contract_id)) || {};
            const subc = contacts.find(c => String(c.id) === String(ab.subcontractor_id || sc.subcontractor_id)) || {};
            const subcName = subc.name || 'مقاول غير محدد';
            
            const opt = document.createElement('option');
            opt.value = String(ab.id);
            opt.textContent = `مستخلص #${ab.abstract_number || ab.id} - ${subcName} - ${ab.net_value || 0} ج.م`;
            opt.title = opt.textContent;
            if (String(ab.id) === String(selectedId)) opt.selected = true;
            targetSel.appendChild(opt);
        });
    } else if (type === 'payment_voucher') {
        const trans = await window.DB.getAll('transactions') || [];
        const payments = trans.filter(t => t.type === 'payment');
        const contacts = await window.DB.getAll('contacts') || [];
        const accounts = await window.DB.getAll('accounts') || [];
        
        targetSel.innerHTML = '<option value="">اختر السند...</option>';
        payments.sort((a,b) => new Date(b.date || 0) - new Date(a.date || 0)).forEach(p => {
            const contact = contacts.find(c => String(c.id) === String(p.contact_id)) || {};
            const account = accounts.find(a => String(a.id) === String(p.account_id)) || {};
            const recipientName = p.recipient_name || contact.name || account.name || 'غير محدد';
            
            const opt = document.createElement('option');
            opt.value = String(p.id);
            opt.textContent = `سند صرف #${p.id} - ${recipientName} - ${parseFloat(p.amount || 0).toFixed(2)} ج.م`;
            opt.title = opt.textContent;
            if (String(p.id) === String(selectedId)) opt.selected = true;
            targetSel.appendChild(opt);
        });
    }
    if(selectedId && btn) {
        btn.style.display = 'block';
    }
};

window.viewCustodyReference = async function(type, id) {
    if(!id) return;
    
    if (type === 'payroll') {
        // Open hr.html and pass the payroll ID to view it directly
        window.open('hr.html?viewPayroll=' + id, '_blank');
    } else if (type === 'supplier_invoice') {
        // Open native purchase invoice modal
        if (typeof window.openPurchasesModal === 'function') {
            window.openPurchasesModal(id);
        } else {
            console.error('openPurchasesModal function not found globally.');
            alert('عذراً، لم يتم العثور على دالة عرض الفاتورة.');
        }
    } else if (type === 'abstract') {
        if (typeof window.openAbstractModal === 'function') {
            window.openAbstractModal(id);
        } else {
            alert('وظيفة عرض المستخلص غير متاحة حالياً');
        }
    } else if (type === 'payment_voucher') {
        if (typeof window.editVoucher === 'function') {
            window.editVoucher(id);
        } else {
            alert('وظيفة عرض السند غير متاحة حالياً');
        }
    }
};




window.handleCustodyAttachmentsChange = async function(event) {
    const files = event.target.files;
    if(!files || files.length === 0) return;
    
    const progressDiv = document.getElementById('custody-req-upload-progress');
    progressDiv.style.display = 'block';
    
    for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const formData = new FormData();
        formData.append('file', file);
        formData.append('type', 'custody');
        
        try {
            const res = await fetch('upload_attachment.php', {
                method: 'POST',
                body: formData
            });
            const result = await res.json();
            if(result.success) {
                window.currentCustodyAttachments = window.currentCustodyAttachments || [];
                window.currentCustodyAttachments.push({
                    name: result.name,
                    path: result.path
                });
            } else {
                alert('خطأ في رفع الملف: ' + result.error);
            }
        } catch(e) {
            console.error('Upload error:', e);
            alert('حدث خطأ أثناء رفع الملف: ' + e.message);
        }
    }
    
    progressDiv.style.display = 'none';
    event.target.value = ''; // Reset input
    window.renderCustodyAttachments();
};

window.renderCustodyAttachments = function() {
    const list = document.getElementById('custody-req-attachments-list');
    if(!list) return;
    list.innerHTML = '';
    
    (window.currentCustodyAttachments || []).forEach((att, index) => {
        const div = document.createElement('div');
        div.style.border = '1px solid #ccc';
        div.style.padding = '5px 10px';
        div.style.borderRadius = '5px';
        div.style.display = 'flex';
        div.style.alignItems = 'center';
        div.style.gap = '10px';
        div.style.background = '#f9f9f9';
        
        const isImage = att.name.match(/.(jpg|jpeg|png|gif)$/i);
        
        div.innerHTML = `
            ${isImage ? `<img src="${att.path}" style="width:30px; height:30px; object-fit:cover; border-radius:3px;">` : '<i class="fas fa-file"></i>'}
            <a href="${att.path}" target="_blank" style="color: #007bff; text-decoration: none; font-size:12px;" title="${att.name}">
                ${att.name.length > 20 ? att.name.substring(0, 20) + '...' : att.name}
            </a>
            <button class="action-btn btn-danger no-print" onclick="window.removeCustodyAttachment(${index})" style="padding: 2px 5px; font-size:10px;"><i class="fas fa-times"></i></button>
        `;
        list.appendChild(div);
    });
};

window.removeCustodyAttachment = function(index) {
    if(confirm('هل أنت متأكد من حذف هذا المرفق؟')) {
        window.currentCustodyAttachments.splice(index, 1);
        window.renderCustodyAttachments();
    }
};

window.deleteCustodyRequest = async function(id) {
    if(!confirm('هل أنت متأكد من الحذف؟')) return;
    try {
        await window.DB.remove('custody_requests', id);
        if(window.loadCustodyRequests) await window.loadCustodyRequests();
        alert('تم الحذف بنجاح');
    } catch(e) {
        console.error(e);
        alert('حدث خطأ أثناء الحذف');
    }
};