window.addEventListener('DOMContentLoaded', () => {
    // Refresh badge periodically
    refreshWABadge();
    setInterval(refreshWABadge, 60000); // Every minute
    
    // Bind change event to filter
    const filter = document.getElementById('wa-filter-status');
    if (filter) {
        filter.addEventListener('change', renderWhatsAppOrders);
    }
    
    // Add click listener for navigation
    document.querySelectorAll('[data-view="whatsapp-orders"]').forEach(el => {
        el.addEventListener('click', (e) => {
            e.preventDefault();
            if(window.switchView) window.switchView('whatsapp-orders');
            renderWhatsAppOrders();
        });
    });
    
    // Check periodically for user and show nav if Admin (avoids editing app_final.js)
    setInterval(() => {
        if (typeof currentUser !== 'undefined' && currentUser && currentUser.role === 'مدير عام') {
            const nav = document.getElementById('nav-whatsapp-orders');
            if (nav && nav.style.display === 'none') {
                nav.style.display = 'block';
            }
        }
    }, 1000);
});

async function refreshWABadge() {
    try {
        const orders = await window.DB.getAll('whatsapp_orders');
        const pendingCount = orders.filter(o => o.status === 'pending').length;
        const badge = document.getElementById('wa-pending-badge');
        if (badge) {
            badge.innerText = pendingCount;
            badge.style.display = pendingCount > 0 ? 'inline-block' : 'none';
        }
    } catch (e) {
        console.error("Failed to refresh WA badge", e);
    }
}

window.renderWhatsAppOrders = async function() {
    try {
        let orders = await window.DB.getAll('whatsapp_orders');
        const filterStatus = document.getElementById('wa-filter-status').value;
        
        if (filterStatus) {
            orders = orders.filter(o => o.status === filterStatus);
        }
        
        // Sort by created_at DESC (or id DESC)
        orders.sort((a, b) => b.id - a.id);
        
        const tbody = document.getElementById('wa-orders-body');
        if (!tbody) return;
        
        tbody.innerHTML = '';
        
        if (orders.length === 0) {
            tbody.innerHTML = '<tr><td colspan="10" style="text-align:center;">لا توجد طلبات.</td></tr>';
            return;
        }
        
        for (const order of orders) {
            const tr = document.createElement('tr');
            
            // Format status
            let statusBadge = '';
            if (order.status === 'pending') statusBadge = '<span class="status-badge status-pending">معلق</span>';
            else if (order.status === 'accepted') statusBadge = '<span class="status-badge status-completed">مقبول</span>';
            else if (order.status === 'rejected') statusBadge = '<span class="status-badge status-cancelled">مرفوض</span>';
            
            // Sender Type
            let senderType = order.sender_type === 'employee' ? '<span style="color:#3498db;font-weight:bold;">موظف</span>' : 'عميل';
            
            // Action buttons
            let actions = `
                <button class="action-btn" style="background:#2ecc71;color:white;" onclick="updateWAOrderStatus(${order.id}, 'accepted')" title="موافقة">✅</button>
                <button class="action-btn" style="background:#e74c3c;color:white;" onclick="updateWAOrderStatus(${order.id}, 'rejected')" title="رفض">❌</button>
                <button class="action-btn" style="background:#3498db;color:white;" onclick="showWAReplyModal('${order.customer_phone}')" title="مراسلة العميل">💬</button>
            `;
            
            if (order.status !== 'pending') {
                actions = `<button class="action-btn" style="background:#3498db;color:white;" onclick="showWAReplyModal('${order.customer_phone}')" title="مراسلة العميل">💬</button>`;
            }
            
            tr.innerHTML = `
                <td>${order.id}</td>
                <td>${order.created_at || 'غير متوفر'}</td>
                <td>${order.customer_name || 'غير معروف'}</td>
                <td style="direction:ltr;">${order.customer_phone}</td>
                <td>${senderType}</td>
                <td>${order.item_name || '-'}</td>
                <td>${order.quantity || '-'}</td>
                <td>${order.delivery_location || '-'}</td>
                <td>${statusBadge}</td>
                <td>${actions}</td>
            `;
            tbody.appendChild(tr);
        }
        
        refreshWABadge();
    } catch (e) {
        console.error("Error rendering WA orders", e);
    }
};

window.updateWAOrderStatus = async function(id, newStatus) {
    if (!confirm(`هل أنت متأكد من تغيير حالة الطلب؟`)) return;
    
    try {
        const order = await window.DB.getById('whatsapp_orders', id);
        if (order) {
            order.status = newStatus;
            await window.DB.update('whatsapp_orders', id, order);
            alert('تم تغيير الحالة بنجاح');
            renderWhatsAppOrders();
        }
    } catch (e) {
        console.error("Error updating WA order", e);
        alert('حدث خطأ');
    }
};

window.showWAReplyModal = function(phone) {
    document.getElementById('wa-reply-phone').value = phone;
    document.getElementById('wa-reply-text').value = '';
    document.getElementById('wa-reply-modal').style.display = 'flex';
};

window.sendWAReply = async function() {
    const phone = document.getElementById('wa-reply-phone').value;
    const msg = document.getElementById('wa-reply-text').value.trim();
    
    if (!msg) {
        alert('الرجاء كتابة رسالة');
        return;
    }
    
    document.getElementById('loading-overlay').style.display = 'flex';
    
    try {
        const res = await fetch('whatsapp_api.php?action=reply', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ phone: phone, message: msg })
        });
        
        const data = await res.json();
        if (data.success) {
            alert('تم إرسال الرسالة بنجاح');
            document.getElementById('wa-reply-modal').style.display = 'none';
        } else {
            alert('فشل الإرسال: ' + JSON.stringify(data.error));
        }
    } catch (e) {
        console.error(e);
        alert('حدث خطأ في الاتصال');
    } finally {
        document.getElementById('loading-overlay').style.display = 'none';
    }
};
