
window.sendApproverNotifications = async function(newApproversStr, oldApproversStr, message, linkStr = null) {
      if (!newApproversStr) return;
      const newArr = newApproversStr.split(',').map(s=>s.trim()).filter(Boolean);
      const oldArr = (oldApproversStr || '').split(',').map(s=>s.trim()).filter(Boolean);
      
      for (const u of newArr) {
          if (!oldArr.includes(u)) {
              const notifObj = {
                  user: u,
                  message: message,
                  date: new Date().toISOString(),
                  read: false
              };
              if (linkStr) notifObj.link = linkStr;
              if (window.DB && window.DB.add) {
                  await window.DB.add('notifications', notifObj);
              }
          }
      }
};

window.getMultiSelectValues = function(id) {
    const el = document.getElementById(id);
    if (!el) return '';
    return Array.from(el.selectedOptions).map(o => o.value).join(', ');
};

window.showView = function(viewId) {
    document.querySelectorAll('.view').forEach(v => {
        v.style.display = 'none';
        v.classList.remove('active');
    });
    const target = document.getElementById(viewId);
    if(target) {
        target.style.display = 'block';
        target.classList.add('active');
    }
}

window.createNewReq = function() {
    window.currentViewingReqId = null;
    window.currentLoadedRequest = null;
    
    // Clear form
    document.getElementById('req-id-display').innerText = '';
    document.getElementById('warehouse-select').value = '';
    window.fetchItemsStock();
    document.getElementById('req-tbody').innerHTML = '';
    document.getElementById('req-comments-list').innerHTML = '<div style="color:var(--text-muted); font-size:13px;">لا توجد تعليقات بعد.</div>';
    reqComments = [];
    
    // Clear signatures
    document.getElementById('store-req-signatures-container').style.display = 'none';
    document.getElementById('store-req-signatures-list').innerHTML = '';
    document.getElementById('btn-sign-store-req').style.display = 'none';
    const saveBtn = document.getElementById('btn-save-req');
    if (saveBtn) {
        saveBtn.style.display = 'inline-block';
        saveBtn.disabled = false;
        saveBtn.innerHTML = '<i class="fas fa-save"></i> حفظ الطلب';
        saveBtn.style.background = 'var(--primary)';
    }
    
    if(window.setMultiSelectValues) window.setMultiSelectValues('req-intended-approver', '');
    else document.getElementById('req-intended-approver').value = '';
    
    window.addRow();
    window.showView('view-store-req-details');
}

window.loadArchive = async function() {
    const tb = document.getElementById('archive-tbody');
    if(!tb) return;
    tb.innerHTML = '<tr><td colspan="6">جاري التحميل...</td></tr>';
    try {
        const res = await fetch('process_store_request.php?action=fetch_archive');
        const data = await res.json();
        if(data.success && data.data.length) {
            tb.innerHTML = '';
            data.data.forEach(r => {
                tb.innerHTML += `
                    <tr>
                        <td>#${r.id}</td>
                        <td>${new Date(r.req_date).toLocaleString('ar-EG')}</td>
                        <td>${r.user_name}</td>
                        <td>${r.warehouse_name}</td>
                        <td><span style="background:var(--primary); color:white; padding:2px 5px; border-radius:4px; font-size:12px;">${r.status}</span></td>
                        <td>
    <button onclick="window.viewRequisitionDetails(${r.id})" style="padding:4px 8px; border:none; background:var(--panel-bg); cursor:pointer; color:var(--text-color); margin-left:5px;"><i class="fas fa-eye"></i></button>
    <button onclick="window.deleteRequisition(${r.id})" style="padding:4px 8px; border:none; background:#e74c3c; cursor:pointer; color:white; border-radius:4px;" title="حذف"><i class="fas fa-trash"></i></button>
</td>
                    </tr>
                `;
            });
        } else {
            tb.innerHTML = '<tr><td colspan="6">لا توجد طلبات سابقة.</td></tr>';
        }
    } catch(e) {
        tb.innerHTML = '<tr><td colspan="6">حدث خطأ في تحميل الأرشيف.</td></tr>';
    }
}

let allItems = [];
let currentWarehouseId = null;
let currentWarehouseName = '';
let tagsList = [];
let localBalancesCache = {};
let reqComments = [];

// Initialize
window.onload = async function() {
    const urlParams = new URLSearchParams(window.location.search);
    const viewId = urlParams.get('viewId');
    try {
        const userJson = sessionStorage.getItem('currentUser');
        if(userJson) currentUser = JSON.parse(userJson);
    } catch(e) {}
    
    const uName = currentUser ? (currentUser.fullname || currentUser.username) : 'غير معروف';
    const reqDateUser = document.getElementById('req-date-user');
    if (reqDateUser) reqDateUser.innerText = `التاريخ: ${new Date().toLocaleDateString('ar-EG')} | الموظف: ${uName}`;
    const hdrUser = document.querySelector('#header-user-name span');
    if(hdrUser) hdrUser.innerText = uName;
    
    // Fetch required data from db.js
    try {
        if(typeof getMultiStores === 'function') {
            const data = await getMultiStores(['items', 'warehouses', 'transactions', 'users']);
            window.currentItems = data.items || [];
            window.currentWarehouses = data.warehouses || [];
            window.allInvoices = data.transactions || [];
            window.allUsers = data.users || [];
        }
    } catch(e) {
        console.error('Error fetching data from API:', e);
    }
    
    populateUsersDatalist();
    populateApproversDropdown();
    calculateLocalBalances();
    populateWarehouses();
    
    // Add one initial row
    setTimeout(window.addRow, 500);

    if (viewId) {
        if(window.viewRequisitionDetails) window.viewRequisitionDetails(viewId);
    } else {
        if(window.showView) window.showView('view-store-req-list');
        if(window.loadArchive) window.loadArchive();
    }
};

function populateUsersDatalist() {
    const list = document.getElementById('users-list');
    if(!list || !window.allUsers) return;
    list.innerHTML = '';
    window.allUsers.forEach(u => {
        const opt = document.createElement('option');
        opt.value = '@' + (u.fullname || u.username || '');
        list.appendChild(opt);
    });
}

window.handleMentionInput = function(input) {
    const val = input.value;
    const lastWord = val.split(' ').pop();
    if (lastWord.startsWith('@')) {
        input.setAttribute('list', 'users-list');
    } else {
        input.removeAttribute('list');
    }
}

window.addReqComment = function() {
    const input = document.getElementById('req-new-comment');
    const text = input.value.trim();
    if(!text) return;
    
    const comment = {
        text: text,
        user: currentUser ? (currentUser.fullname || currentUser.username) : 'غير معروف',
        timestamp: new Date().toISOString()
    };
    
    reqComments.push(comment);
    renderReqComments();
    input.value = '';
}

function renderReqComments() {
    const list = document.getElementById('req-comments-list');
    list.innerHTML = '';
    
    if(reqComments.length === 0) {
        list.innerHTML = '<div style="color:var(--text-muted); font-size:13px;">لا توجد تعليقات بعد.</div>';
        return;
    }
    
    reqComments.forEach(c => {
        const div = document.createElement('div');
        div.style.cssText = 'padding:8px; border-bottom:1px solid rgba(0,0,0,0.05); margin-bottom:5px;';
        
        let htmlText = c.text.replace(/@([^\\s]+)/g, '<span style="color:var(--primary); font-weight:bold;">@$1</span>');
        
        div.innerHTML = `
            <div style="font-size:12px; color:var(--text-muted); margin-bottom:3px;">
                <strong><i class="fas fa-user-circle"></i> ${c.user}</strong> - ${new Date(c.timestamp).toLocaleString('ar-EG')}
            </div>
            <div style="font-size:14px; color:var(--text-color);">${htmlText}</div>
        `;
        list.appendChild(div);
    });
    list.scrollTop = list.scrollHeight;
}

// 100% accurate balances calculation matching main app
function calculateLocalBalances() {
    localBalancesCache = {};
    if(!window.currentItems || !window.allInvoices) return;
    
    window.currentItems.forEach(i => {
        localBalancesCache[i.id] = { globalQty: 0, totalValue: 0, avgCost: 0, warehouses: {} };
    });

    const sortedInvoices = [...window.allInvoices].sort((a, b) => new Date(a.date) - new Date(b.date));

    sortedInvoices.forEach(inv => {
        (inv.items || []).forEach(item => {
            const b = localBalancesCache[item.item_id];
            if (!b) return;

            const fromWh = inv.from_warehouse_id;
            const toWh = inv.to_warehouse_id;

            if (fromWh && !b.warehouses[fromWh]) b.warehouses[fromWh] = 0;
            if (toWh && !b.warehouses[toWh]) b.warehouses[toWh] = 0;

            if ((inv.type === 'in' || inv.type === 'opening_balance') || ((inv.type === 'purchases' || inv.type === 'sales_return') && inv.status === 'posted')) {
                b.globalQty += item.qty;
                if (inv.type === 'sales_return') {
                    if (fromWh) b.warehouses[fromWh] += item.qty;
                } else {
                    if (toWh) b.warehouses[toWh] += item.qty;
                }
                b.totalValue += (item.qty * item.price);
                b.avgCost = b.globalQty > 0 ? (b.totalValue / b.globalQty) : 0;
            }
            else if (inv.type === 'out' || inv.type === 'out_project' || inv.type === 'depreciate_asset' || ((inv.type === 'sales' || inv.type === 'purchases_return') && inv.status === 'posted')) {
                b.globalQty -= item.qty;
                if (inv.type === 'purchases_return') {
                    if (fromWh) b.warehouses[fromWh] -= item.qty;
                } else {
                    if (fromWh) b.warehouses[fromWh] -= item.qty;
                }
                b.totalValue -= (item.qty * b.avgCost);
            }
            else if (inv.type === 'transfer') {
                if (inv.status === 'pending_receipt' || inv.status === 'pending_decision') {
                    if (fromWh) b.warehouses[fromWh] -= item.qty;
                }
                else if (inv.status === 'completed') {
                    const deducted = item.deducted_qty !== undefined ? item.deducted_qty : item.qty;
                    const received = item.received_qty !== undefined ? item.received_qty : item.qty;
                    if (fromWh) b.warehouses[fromWh] -= deducted;
                    if (toWh) b.warehouses[toWh] += received;
                    if (deducted > received) {
                        const deficit = deducted - received;
                        b.globalQty -= deficit;
                        b.totalValue -= (deficit * b.avgCost);
                    }
                }
            }
        });

        if (inv.type === 'manufacture') {
            let totalRawCost = 0;
            (inv.items || []).forEach(raw => {
                let b = localBalancesCache[raw.item_id];
                if (b) {
                    let fromWh = inv.from_warehouse_id;
                    b.globalQty -= raw.qty;
                    if (fromWh) {
                        if (b.warehouses[fromWh] === undefined) b.warehouses[fromWh] = 0;
                        b.warehouses[fromWh] -= raw.qty;
                    }
                    let consumedCost = raw.qty * b.avgCost;
                    b.totalValue -= consumedCost;
                    totalRawCost += consumedCost;
                }
            });

            let producedId = inv.product_id || inv.produced_item_id;
            let prodB = localBalancesCache[producedId];

            if (prodB) {
                let toWh = inv.from_warehouse_id;
                prodB.globalQty += inv.produced_qty;
                if (toWh) {
                    if (prodB.warehouses[toWh] === undefined) prodB.warehouses[toWh] = 0;
                    prodB.warehouses[toWh] += inv.produced_qty;
                }
                prodB.totalValue += totalRawCost;
                prodB.avgCost = prodB.globalQty > 0 ? (prodB.totalValue / prodB.globalQty) : 0;
            }
            inv.produced_cost = totalRawCost;
        }
    });
}

function populateWarehouses() {
    const sel = document.getElementById('warehouse-select');
    if (!sel) return;
    sel.innerHTML = '<option value="">-- اختر المخزن --</option>';
    if(window.currentWarehouses) {
        window.currentWarehouses.forEach(w => {
            const opt = document.createElement('option');
            opt.value = w.id;
            opt.innerText = w.name;
            sel.appendChild(opt);
        });
    }
}

window.fetchItemsStock = function() {
    const sel = document.getElementById('warehouse-select');
    currentWarehouseId = sel.value;
    currentWarehouseName = sel.options[sel.selectedIndex]?.text || '';
    
    document.getElementById('req-warehouse-name').innerText = currentWarehouseId ? `المخزن: ${currentWarehouseName}` : 'الرجاء اختيار المخزن';
    
    if(!currentWarehouseId || !window.currentItems) {
        allItems = [];
        tagsList = [];
        return;
    }
    
    allItems = window.currentItems;
    let tSet = new Set();
    allItems.forEach(i => tSet.add((i.tag || 'أخرى').trim()));
    tagsList = Array.from(tSet);
    
    document.querySelectorAll('#req-tbody tr').forEach(tr => {
        populateTagsDropdown(tr.querySelector('.row-tag'));
    });
}

window.addRow = function() {
    const tbody = document.getElementById('req-tbody');
    if (!tbody) return;
    const tr = document.createElement('tr');
    
    tr.innerHTML = `
        <td class="no-print">
            <select class="row-tag" onchange="window.onTagChange(this)">
                <option value="">اختر التصنيف...</option>
            </select>
        </td>
        <td>
            <select class="row-item" onchange="window.onItemChange(this)">
                <option value="">اختر الصنف...</option>
            </select>
        </td>
        <td>
            <input type="number" class="row-qty" min="0.1" step="any" placeholder="الكمية">
        </td>
        <td>
            <select class="row-unit" onchange="window.onUnitChange(this)">
                <option value="">الوحدة...</option>
            </select>
        </td>
        <td>
            <input type="text" class="row-note" placeholder="ملاحظة" style="width:100%;">
        </td>
        <td class="row-current-stock" style="color:#27ae60; font-weight:bold;">-</td>
        <td class="row-other-stock" style="color:#3498db; font-weight:bold;">-</td>
        <td class="no-print">
            <button class="btn-delete-row" onclick="this.closest('tr').remove()"><i class="fas fa-trash"></i></button>
        </td>
    `;
    
    tbody.appendChild(tr);
    populateTagsDropdown(tr.querySelector('.row-tag'));
}

function populateTagsDropdown(selectElem) {
    if(!selectElem) return;
    const currentVal = selectElem.value;
    selectElem.innerHTML = '<option value="">اختر التصنيف...</option>';
    tagsList.forEach(t => {
        const opt = document.createElement('option');
        opt.value = t; opt.innerText = t;
        selectElem.appendChild(opt);
    });
    if(tagsList.includes(currentVal)) selectElem.value = currentVal;
}

window.onTagChange = function(tagSelect) {
    const tr = tagSelect.closest('tr');
    const itemSelect = tr.querySelector('.row-item');
    const tag = tagSelect.value;
    
    itemSelect.innerHTML = '<option value="">اختر الصنف...</option>';
    tr.querySelector('.row-current-stock').innerText = '-';
    tr.querySelector('.row-other-stock').innerText = '-';
    
    if(!tag) return;
    
    const filtered = allItems.filter(i => (i.tag || 'أخرى').trim() === tag);
    filtered.forEach(i => {
        const opt = document.createElement('option');
        opt.value = i.id;
        opt.innerText = i.name;
        
        let cQty = 0, oQty = 0;
        if (localBalancesCache[i.id]) {
            const b = localBalancesCache[i.id];
            cQty = b.warehouses[currentWarehouseId] || 0;
            oQty = b.globalQty - cQty;
        }
        
        opt.dataset.current = cQty;
        opt.dataset.other = oQty;
        opt.dataset.unit = i.unit || '';
        opt.dataset.altUnit = i.alt_unit || '';
        opt.dataset.convFactor = i.conv_factor || 1;
        
        itemSelect.appendChild(opt);
    });
}

window.onItemChange = function(itemSelect) {
    const tr = itemSelect.closest('tr');
    const opt = itemSelect.options[itemSelect.selectedIndex];
    const unitSelect = tr.querySelector('.row-unit');
    
    if(opt && opt.value) {
        // Populate units
        unitSelect.innerHTML = '';
        if (opt.dataset.unit) {
            unitSelect.innerHTML += `<option value="${opt.dataset.unit}" data-factor="1">${opt.dataset.unit}</option>`;
        } else {
            unitSelect.innerHTML += `<option value="وحدة" data-factor="1">وحدة</option>`;
        }
        if (opt.dataset.altUnit) {
            unitSelect.innerHTML += `<option value="${opt.dataset.altUnit}" data-factor="${opt.dataset.convFactor}">${opt.dataset.altUnit}</option>`;
        }
        // trigger unit change to update the text
        window.onUnitChange(unitSelect);
    } else {
        unitSelect.innerHTML = '<option value="">الوحدة...</option>';
        tr.querySelector('.row-current-stock').innerText = '-';
        tr.querySelector('.row-other-stock').innerText = '-';
    }
}

window.onUnitChange = function(unitSelect) {
    const tr = unitSelect.closest('tr');
    const itemSelect = tr.querySelector('.row-item');
    const opt = itemSelect.options[itemSelect.selectedIndex];
    
    if(opt && opt.value) {
        const selectedUnitOpt = unitSelect.options[unitSelect.selectedIndex];
        const factor = parseFloat(selectedUnitOpt.dataset.factor || 1);
        const unitName = selectedUnitOpt.value;
        
        let cQty = parseFloat(opt.dataset.current) / factor;
        let oQty = parseFloat(opt.dataset.other) / factor;
        
        // Round to 2 decimal places to avoid long floats
        cQty = Math.round(cQty * 100) / 100;
        oQty = Math.round(oQty * 100) / 100;

        tr.querySelector('.row-current-stock').innerText = cQty + ' ' + unitName;
        tr.querySelector('.row-other-stock').innerText = oQty + ' ' + unitName;
    }
}

window.saveRequisition = async function() {
    if(!currentWarehouseId) { alert("الرجاء اختيار المخزن أولاً"); return; }
    
    const rows = document.querySelectorAll('#req-tbody tr');
    let itemsToSave = [];
    
    rows.forEach(tr => {
        const itemSelect = tr.querySelector('.row-item');
        const qtyInput = tr.querySelector('.row-qty');
        const noteInput = tr.querySelector('.row-note');
        
        if(itemSelect && itemSelect.value && qtyInput && qtyInput.value > 0) {
            const opt = itemSelect.options[itemSelect.selectedIndex];
            const unitSelect = tr.querySelector('.row-unit');
            const unitName = unitSelect.value || opt.dataset.unit || '';
            const factor = parseFloat(unitSelect.options[unitSelect.selectedIndex]?.dataset.factor || 1);
            
            itemsToSave.push({
                item_id: itemSelect.value,
                item_name: opt.text,
                req_qty: parseFloat(qtyInput.value),
                unit: unitName,
                conv_factor: factor,
                note: noteInput ? noteInput.value : '',
                current_qty: Math.round((parseFloat(opt.dataset.current) / factor) * 100) / 100,
                other_qty: Math.round((parseFloat(opt.dataset.other) / factor) * 100) / 100
            });
        }
    });
    
    if(itemsToSave.length === 0) { alert("الرجاء إضافة أصناف وتحديد الكميات المطلوبة"); return; }
    
    const payload = {
        id: window.currentViewingReqId,
        warehouse_id: currentWarehouseId,
        warehouse_name: currentWarehouseName,
        user_name: currentUser ? (currentUser.fullname || currentUser.username) : 'غير معروف',
        items: itemsToSave,
        comments: reqComments,
        intended_approver: window.getMultiSelectValues('req-intended-approver')
    };
    
    const btn = document.getElementById('btn-save-req');
    const originalText = btn.innerHTML;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> جاري الحفظ...';
    btn.disabled = true;
    
    try {
        const res = await fetch('process_store_request.php?action=save_request', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(payload)
        });
        const data = await res.json();
        
        if(data.success) {
            // Send notifications!
            const approversStr = window.getMultiSelectValues('req-intended-approver');
            if (approversStr && window.sendApproverNotifications) {
                // PHP API returns inserted ID in data.id
                window.sendApproverNotifications(approversStr, '', 'يوجد لك طلب عهدة مخزنية جديد بانتظار الاعتماد', "window.location.href='store_stock_request.html?viewId=" + (data.id || data.req_id) + "'");
            }
            btn.innerHTML = '<i class="fas fa-check"></i> تم الحفظ';
            btn.style.background = '#27ae60';
            
            // Disable inputs so they are ready for screenshot
            document.querySelectorAll('.row-item, .row-tag, .row-qty, .row-note').forEach(el => el.disabled = true);
            document.querySelectorAll('.btn-delete-row').forEach(b => b.style.display = 'none');
            const addRowBtn = document.querySelector('.btn-add-row');
            if (addRowBtn) addRowBtn.style.display = 'none';
        } else {
            alert('حدث خطأ أثناء الحفظ: ' + (data.error || ''));
            btn.innerHTML = originalText;
            btn.disabled = false;
        }
    } catch(err) {
        console.error('Error saving:', err);
        alert('حدث خطأ بالشبكة أثناء الحفظ');
        btn.innerHTML = originalText;
        btn.disabled = false;
    }
}

window.shareReqWhatsApp = async function() {
    const btn = document.getElementById('btn-share-whatsapp');
    
    let hasItems = false;
    document.querySelectorAll('.row-qty').forEach(q => { if(q.value > 0) hasItems = true; });
    if(!hasItems) {
        alert('الرجاء إضافة أصناف وتحديد الكمية قبل الإرسال!');
        return;
    }
    
    const originalText = btn.innerHTML;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> جاري التجهيز...';
    
    try {
        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('requisition-capture-area');
        
        // Hide no-print elements
        const noPrintElements = printArea.querySelectorAll('.no-print');
        const originalDisplays = [];
        noPrintElements.forEach(el => {
            originalDisplays.push(el.style.display);
            el.style.display = 'none';
        });

        // Convert Selects and Inputs to plain text for clean screenshot
        const elementsToReplace = printArea.querySelectorAll('select.row-item, input.row-qty, select.row-unit, input.row-note');
        const replacements = [];
        
        elementsToReplace.forEach(el => {
            const span = document.createElement('span');
            if(el.tagName === 'SELECT') {
                span.innerText = el.options[el.selectedIndex] ? el.options[el.selectedIndex].text : '';
                span.style.fontWeight = 'bold';
                if(el.classList.contains('row-unit')) span.style.color = '#8e44ad';
            } else {
                span.innerText = el.value;
                span.style.fontWeight = 'bold';
                span.style.color = '#e74c3c';
            }
            replacements.push({ parent: el.parentNode, el: el, span: span });
            el.parentNode.replaceChild(span, el);
        });
        
        let watermark = document.getElementById('req-watermark');
        if (!watermark) {
            watermark = document.createElement('div');
            watermark.id = 'req-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);
        }

        const originalWidth = printArea.style.width;
        const originalMaxWidth = printArea.style.maxWidth;
        printArea.style.width = '800px';
        printArea.style.maxWidth = 'none';

        const canvas = await html2canvas(printArea, { 
            scale: 2, 
            backgroundColor: '#ffffff',
            useCORS: true,
            windowWidth: 850
        });
        
        printArea.style.width = originalWidth;
        printArea.style.maxWidth = originalMaxWidth;
        noPrintElements.forEach((el, index) => { el.style.display = originalDisplays[index]; });
        replacements.forEach(rep => { rep.parent.replaceChild(rep.el, rep.span); });
        if (watermark) watermark.remove();
        
        canvas.toBlob(async (blob) => {
            if (!blob) {
                alert("حدث خطأ أثناء إنشاء الصورة.");
                btn.innerHTML = originalText;
                return;
            }
            
            const file = new File([blob], 'Stock_Requisition.png', { type: 'image/png' });
            
            // Check if mobile device
            const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);

            if (navigator.canShare && navigator.canShare({ files: [file] }) && isMobile) {
                try {
                    await navigator.share({
                        files: [file],
                        title: 'طلب عهدة مخزنية',
                        text: 'مرفق صورة طلب عهدة مخزنية من نظام Easy ERP'
                    });
                } catch (err) {
                    console.log('Share cancelled or failed', err);
                }
            } else {
                // Fallback / Desktop - Force WhatsApp Web as requested
                const a = document.createElement('a');
                a.href = URL.createObjectURL(blob);
                a.download = 'Stock_Requisition.png';
                a.click();
                URL.revokeObjectURL(a.href);
                
                const message = encodeURIComponent('مرفق صورة طلب عهدة مخزنية، الرجاء إرسال الصورة التي تم تحميلها.');
                window.open(`https://web.whatsapp.com/send?text=${message}`, '_blank');
            }
            btn.innerHTML = originalText;
        });
        
    } catch(err) {
        console.error('Error in html2canvas:', err);
        alert('حدث خطأ أثناء إعداد الصورة.');
        btn.innerHTML = originalText;
    }
}

window.viewRequisitionDetails = async function(id) {
    window.currentViewingReqId = id;
    document.getElementById('req-id-display').innerText = '#' + id;
    window.showView('view-store-req-details');
    
    try {
        const res = await fetch('process_store_request.php?action=fetch_req_details&id=' + id);
        const data = await res.json();
        
        if (data.success) {
            const req = data.request;
            window.currentLoadedRequest = req;
            
            // Set basic info
            document.getElementById('req-date-user').innerText = `التاريخ: ${new Date(req.req_date).toLocaleDateString('ar-EG')} | الموظف: ${req.user_name}`;
            document.getElementById('warehouse-select').value = req.warehouse_id || '';
            window.fetchItemsStock();
            
            // Populate items
            const tb = document.getElementById('req-tbody');
            tb.innerHTML = '';
            if (data.details && data.details.length > 0) {
                data.details.forEach(d => {
                    const tr = document.createElement('tr');
                    tr.innerHTML = `
                        <td class="no-print">-</td>
                        <td>
                            <select class="row-item" disabled>
                                <option value="${d.item_id}">${d.item_name}</option>
                            </select>
                        </td>
                        <td>
                            <input type="number" class="row-qty" value="${d.req_qty}" disabled>
                        </td>
                        <td>
                            <select class="row-unit" disabled>
                                <option value="${d.unit}">${d.unit || ''}</option>
                            </select>
                        </td>
                        <td>
                            <input type="text" class="row-note" value="${d.note || ''}" disabled style="width:100%;">
                        </td>
                        <td class="row-current-stock">-</td>
                        <td class="row-other-stock">-</td>
                        <td class="no-print"></td>
                    `;
                    tb.appendChild(tr);
                });
            } else {
                tb.innerHTML = '<tr><td colspan="7">لا توجد أصناف في هذا الطلب.</td></tr>';
            }
            
            // Populate comments
            reqComments = [];
            if (req.comments && req.comments !== '[]' && req.comments !== '') {
                try {
                    reqComments = JSON.parse(req.comments);
                } catch(e) {}
            }
            renderReqComments();
            
            // Signatures
            const sigContainer = document.getElementById('store-req-signatures-container');
            const sigList = document.getElementById('store-req-signatures-list');
            
            if (req.paper_approved_by) {
                sigContainer.style.display = 'block';
                const approvers = req.paper_approved_by.split(',').filter(a => a.trim() !== '');
                let html = '';
                approvers.forEach(a => {
                    html += `<div style="background: white; border-radius: 8px; padding: 10px; margin-bottom: 8px; border-right: 4px solid var(--primary); box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
                        <div style="font-weight: bold; font-size: 14px; color: var(--primary);">تم الاعتماد بواسطة: ${a.trim()}</div>
                    </div>`;
                });
                sigList.innerHTML = html;
            } else {
                sigContainer.style.display = 'none';
                sigList.innerHTML = '';
            }
            
            // Approver UI logic
            const currentUser = JSON.parse(sessionStorage.getItem('currentUser') || '{}');
            const currentName = currentUser.name || currentUser.username;
            const btnSign = document.getElementById('btn-sign-store-req');
            
            if (req.intended_approver && req.intended_approver.includes(currentName) && 
               !(req.paper_approved_by || '').includes(currentName)) {
                btnSign.style.display = 'inline-block';
            } else {
                btnSign.style.display = 'none';
            }
            
            // Keep save button for comments
            document.getElementById('btn-save-req').style.display = 'inline-block';
            
            populateApproversDropdown();
        }
    } catch(e) {
        console.error('Error fetching details', e);
    }
}

window.signStoreReq = async function() {
    if(!window.currentViewingReqId) return;
    if(!confirm("هل أنت متأكد من توقيع هذا الطلب كمعتمد؟")) return;
    
    const currentUser = JSON.parse(sessionStorage.getItem('currentUser') || '{}');
    const approverName = currentUser.name || currentUser.username;
    
    const res = await fetch('process_store_request.php?action=sign_request', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            id: window.currentViewingReqId,
            paper_approved_by: approverName
        })
    });
    
    const data = await res.json();
    if(data.success) {
        const sigContainer = document.getElementById('store-req-signatures-container');
        const sigList = document.getElementById('store-req-signatures-list');
        sigContainer.style.display = 'block';
        
        const newSigHtml = `<div style="background: white; border-radius: 8px; padding: 10px; margin-bottom: 8px; border-right: 4px solid var(--primary); box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
            <div style="font-weight: bold; font-size: 14px; color: var(--primary);">تم الاعتماد بواسطة: ${approverName}</div>
            <div style="font-size: 11px; color: var(--text-muted); margin-top: 4px;">التاريخ: ${new Date().toLocaleString('ar-EG')}</div>
        </div>`;
        sigList.innerHTML += newSigHtml;
        
        document.getElementById('btn-sign-store-req').style.display = 'none';
        alert('تم التوقيع بنجاح!');
        if(window.loadArchive) window.loadArchive();
    } else {
        alert('حدث خطأ أثناء التوقيع.');
    }
};

function populateApproversDropdown() {
    const sel = document.getElementById('req-intended-approver');
    if (!sel || !window.allUsers) return;
    sel.innerHTML = '';
    sel.multiple = true;
    // Remove the style.height to not interfere with new UI
    window.allUsers.forEach(u => {
        const opt = document.createElement('option');
        opt.value = u.name || u.username;
        opt.textContent = u.name || u.username;
        sel.appendChild(opt);
    });
    
    if (window.currentLoadedRequest && window.currentLoadedRequest.intended_approver) {
        const values = window.currentLoadedRequest.intended_approver.split(',').map(v => v.trim());
        Array.from(sel.options).forEach(opt => {
            opt.selected = values.includes(opt.value.trim());
        });
    }

    if (sel.dataset.multiSelectInit) {
        sel.removeAttribute('data-multi-select-init');
        sel.parentNode.querySelectorAll('.custom-multi-select').forEach(e => e.remove());
    }
    
    if (window.setupMultiSelect) {
        window.setupMultiSelect('req-intended-approver');
    }
}


// Custom Multi-Select UI Component
window.setupMultiSelect = function(selectId) {
    const originalSelect = document.getElementById(selectId);
    if (!originalSelect || originalSelect.dataset.multiSelectInit) return;
    
    originalSelect.style.display = 'none';
    originalSelect.dataset.multiSelectInit = 'true';
    originalSelect.multiple = true;
    
    const container = document.createElement('div');
    container.className = 'custom-multi-select';
    container.style.position = 'relative';
    container.style.display = 'inline-block';
    container.style.width = originalSelect.style.width || '100%';
    container.style.fontFamily = "'Cairo', sans-serif";
    
    const tagsArea = document.createElement('div');
    tagsArea.style.border = '1px solid #ccc';
    tagsArea.style.borderRadius = '4px';
    tagsArea.style.padding = '5px';
    tagsArea.style.minHeight = '35px';
    tagsArea.style.cursor = 'pointer';
    tagsArea.style.display = 'flex';
    tagsArea.style.flexWrap = 'wrap';
    tagsArea.style.gap = '5px';
    tagsArea.style.alignItems = 'center';
    tagsArea.style.background = '#fff';
    
    const placeholder = document.createElement('span');
    placeholder.innerText = 'اختر المعتمدين...';
    placeholder.style.color = '#999';
    placeholder.style.fontSize = '14px';
    
    const dropdown = document.createElement('div');
    dropdown.style.display = 'none';
    dropdown.style.position = 'absolute';
    dropdown.style.top = '100%';
    dropdown.style.left = '0';
    dropdown.style.width = '100%';
    dropdown.style.maxHeight = '200px';
    dropdown.style.overflowY = 'auto';
    dropdown.style.background = '#fff';
    dropdown.style.border = '1px solid #ccc';
    dropdown.style.borderTop = 'none';
    dropdown.style.zIndex = '1000';
    dropdown.style.boxShadow = '0 4px 6px rgba(0,0,0,0.1)';
    dropdown.style.borderRadius = '0 0 4px 4px';
    
    container.appendChild(tagsArea);
    container.appendChild(dropdown);
    originalSelect.parentNode.insertBefore(container, originalSelect);
    
    const updateUI = () => {
        tagsArea.innerHTML = '';
        let hasSelection = false;
        
        Array.from(originalSelect.options).forEach(opt => {
            if (opt.value && opt.selected) {
                hasSelection = true;
                const tag = document.createElement('div');
                tag.style.background = 'var(--primary, #007bff)';
                tag.style.color = '#fff';
                tag.style.padding = '2px 6px';
                tag.style.borderRadius = '3px';
                tag.style.fontSize = '12px';
                tag.style.display = 'flex';
                tag.style.alignItems = 'center';
                tag.style.gap = '5px';
                
                const txt = document.createElement('span');
                txt.innerText = opt.text;
                
                const closeBtn = document.createElement('span');
                closeBtn.innerHTML = '&times;';
                closeBtn.style.cursor = 'pointer';
                closeBtn.style.fontWeight = 'bold';
                closeBtn.onclick = (e) => {
                    e.stopPropagation();
                    opt.selected = false;
                    originalSelect.dispatchEvent(new Event('change'));
                };
                
                tag.appendChild(txt);
                tag.appendChild(closeBtn);
                tagsArea.appendChild(tag);
            }
        });
        
        if (!hasSelection) {
            tagsArea.appendChild(placeholder);
        }
        
        dropdown.innerHTML = '';
        Array.from(originalSelect.options).forEach(opt => {
            if (!opt.value) return; 
            const item = document.createElement('div');
            item.style.padding = '8px 10px';
            item.style.cursor = 'pointer';
            item.style.borderBottom = '1px solid #eee';
            item.style.display = 'flex';
            item.style.alignItems = 'center';
            item.style.gap = '8px';
            
            const cb = document.createElement('input');
            cb.type = 'checkbox';
            cb.checked = opt.selected;
            cb.style.cursor = 'pointer';
            cb.style.pointerEvents = 'none'; // let the row handle the click
            
            const lbl = document.createElement('span');
            lbl.innerText = opt.text;
            lbl.style.fontSize = '14px';
            
            item.appendChild(cb);
            item.appendChild(lbl);
            
            item.onclick = (e) => {
                e.stopPropagation();
                opt.selected = !opt.selected;
                originalSelect.dispatchEvent(new Event('change'));
            };
            
            item.onmouseover = () => item.style.background = '#f5f5f5';
            item.onmouseout = () => item.style.background = '#fff';
            
            dropdown.appendChild(item);
        });
    };
    
    originalSelect.addEventListener('change', updateUI);
    
    const observer = new MutationObserver(() => updateUI());
    observer.observe(originalSelect, { childList: true });
    updateUI();
    
    tagsArea.onclick = (e) => {
        e.stopPropagation();
        const isHidden = dropdown.style.display === 'none';
        document.querySelectorAll('.custom-multi-select > div:nth-child(2)').forEach(d => d.style.display = 'none');
        dropdown.style.display = isHidden ? 'block' : 'none';
    };
    
    document.addEventListener('click', (e) => {
        if (!container.contains(e.target)) {
            dropdown.style.display = 'none';
        }
    });
};

window.getMultiSelectValues = function(selectId) {
    const sel = document.getElementById(selectId);
    if (!sel) return '';
    return Array.from(sel.selectedOptions).map(o => o.value).filter(Boolean).join(', ');
};

window.setMultiSelectValues = function(selectId, valuesStr) {
    const sel = document.getElementById(selectId);
    if (!sel) return;
    const values = (valuesStr || '').split(',').map(s => s.trim());
    Array.from(sel.options).forEach(opt => {
        opt.selected = values.includes(opt.value);
    });
    sel.dispatchEvent(new Event('change'));
};


window.deleteRequisition = async function(id) {
    if(!confirm('هل أنت متأكد من حذف هذا الطلب نهائياً؟')) return;
    try {
        const res = await fetch('process_store_request.php?action=delete_request', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({id: id})
        });
        const data = await res.json();
        if(data.success) {
            window.loadArchive();
        } else {
            alert('حدث خطأ أثناء الحذف: ' + (data.error || ''));
        }
    } catch(err) {
        console.error(err);
        alert('حدث خطأ في الاتصال');
    }
};
