// Custody Requests Module
let custodyRequests = [];
let custodyReqItems = [];
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');
    }


    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 || '';
        }
        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.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().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 = '';
        }
        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';
        document.getElementById('custody-req-requester').innerText = currentUser.username || currentUser.name || '';
        document.getElementById('custody-req-balance').innerText = '0 ج.م.';
        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'); });
        document.getElementById('view-custody-request-details').classList.add('active');
    }
};

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><input type="text" class="req-item-desc" placeholder="البيان..." value="${item.description || ''}" style="width:100%; border:none; background:transparent; font-size:18px; font-weight:bold; font-family:'Cairo';"></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:18px; font-weight:bold; font-family:'Cairo'; text-align:center;"></td>
        <td><input type="text" class="req-item-note" placeholder="ملاحظات..." value="${item.note || ''}" style="width:100%; border:none; background:transparent; font-size:18px; font-weight:bold; font-family:'Cairo';"></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();
};

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 date = document.getElementById('custody-req-date').value;
    const project = document.getElementById('custody-req-project').value;
    const from = document.getElementById('custody-req-from').value;
      const intended_approver = window.getMultiSelectValues ? window.getMultiSelectValues('custody-req-intended-approver') : (document.getElementById('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(!date || !project || !from) {
        alert("يرجى إكمال البيانات الأساسية (التاريخ، الموقع، المطلوب منه العهدة).");
        return;
    }
    
    const tbody = document.getElementById('custody-req-items');
    const items = [];
    Array.from(tbody.children).forEach(tr => {
        items.push({
            description: tr.querySelector('.req-item-desc').value,
            value: parseFloat(tr.querySelector('.req-item-val').value) || 0,
            note: tr.querySelector('.req-item-note').value
        });
    });
    
    const total = window.calcCustodyReqTotal();
    
    // Retrieve existing comments if updating
    let comments = [];
    if(id) {
        await loadCustodyRequests();
        const existing = custodyRequests.find(r => String(r.id) === String(id));
        if(existing && existing.comments) comments = existing.comments;
    }
    
    const reqData = {
        date,
        project,
        from,
        requester,
        requesterBalance: parseFloat(document.getElementById('custody-req-balance').innerText) || 0,
        items,
        total,
        intended_approver: typeof intended_approver !== 'undefined' ? intended_approver : '',
          paper_approved_by: typeof paper_approved_by !== 'undefined' ? paper_approved_by : '',
          status: id ? (custodyRequests.find(r => String(r.id) === String(id))?.status || 'pending') : 'pending',
        comments
    };
    if (id) reqData.id = parseInt(id);
    
    try {
        if (id) {
            await window.DB.update('custody_requests', reqData);
        } else {
            reqData.id = await window.DB.add('custody_requests', reqData);
        }
        await window.sendApproverNotifications(reqData.intended_approver, (typeof existing !== 'undefined' && existing) ? existing.intended_approver : '', 'لديك طلب عهدة يحتاج إلى اعتمادك من ' + reqData.requester, 'openCustodyRequestDetails(' + (reqData.id || "''") + ')');
        alert("تم الحفظ بنجاح!");
        window.closeCustodyRequestDetails();
    } catch(e) {
        console.error("Save error", e);
        alert("حدث خطأ أثناء الحفظ");
    }
};

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

window.closeCustodyRequestDetails = function() {
    if (typeof showView === 'function') {
        showView('view-custody-requests');
    } else {
        document.querySelectorAll('.view').forEach(v => { v.style.display = ''; v.classList.remove('active'); });
        document.getElementById('view-custody-requests').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 = '';
    
    // Save immediately if we are editing an existing request
    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.style.marginBottom = '10px';
    div.style.padding = '8px';
    div.style.background = '#f9f9f9';
    div.style.borderRadius = '5px';
    div.style.borderLeft = '3px solid var(--primary)';
    
    // Process mentions
    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 printContent = document.getElementById('custody-request-print-area').innerHTML;
    const originalContent = document.body.innerHTML;
    
    document.body.innerHTML = printContent;
    document.body.style.backgroundColor = 'white';
    
    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
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';
    
    alert("تم التوقيع بنجاح!");
};
