<?php
/**
 * Cashier Dashboard - نظام الكاشير مع تحديث فوري
 */

require_once 'config.php';
checkCashierAuth();

$cashier = getCurrentCashier();

// جلب الكباتن النشطين
$captains = $conn->query("SELECT id, name, phone FROM captains WHERE status = 'active' ORDER BY name");

$page_title = 'لوحة تحكم الكاشير';
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=yes">
    <title><?php echo $page_title; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Tajawal', sans-serif;
            background: #f8fafc;
            min-height: 100vh;
        }

        .cashier-app {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 20px;
            padding: 25px;
            color: white;
            margin-bottom: 25px;
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
        }

        .header h1 {
            font-size: 1.8rem;
            font-weight: 800;
            margin-bottom: 5px;
        }

        .header p {
            opacity: 0.9;
            margin-bottom: 0;
        }

        .date-badge {
            background: rgba(255,255,255,0.2);
            padding: 8px 15px;
            border-radius: 30px;
            font-size: 0.9rem;
            backdrop-filter: blur(5px);
        }

        .action-btn-header {
            background: rgba(255,255,255,0.2);
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 12px;
            transition: all 0.3s;
            cursor: pointer;
        }

        .action-btn-header:hover {
            background: rgba(255,255,255,0.3);
            transform: translateY(-2px);
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 15px;
            margin-bottom: 25px;
        }

        .stat-card {
            background: white;
            border-radius: 16px;
            padding: 20px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            transition: all 0.3s ease;
            cursor: pointer;
            border: 1px solid #e2e8f0;
            position: relative;
            overflow: hidden;
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
        }

        .stat-card.pending::before { background: #fbbf24; }
        .stat-card.accepted::before { background: #3b82f6; }
        .stat-card.ontheway::before { background: #F57C00; }
        .stat-card.delivered::before { background: #10b981; }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 30px rgba(0,0,0,0.1);
        }

        .stat-value {
            font-size: 2.2rem;
            font-weight: 800;
            line-height: 1.2;
        }

        .stat-label {
            color: #64748b;
            font-size: 0.9rem;
            font-weight: 500;
        }

        .stat-icon {
            position: absolute;
            bottom: 15px;
            left: 15px;
            font-size: 2.5rem;
            opacity: 0.2;
        }

        .status-tabs {
            display: flex;
            gap: 10px;
            overflow-x: auto;
            padding: 5px 0 15px;
            margin-bottom: 20px;
            -webkit-overflow-scrolling: touch;
        }

        .status-tab {
            padding: 12px 25px;
            border: none;
            background: white;
            border-radius: 30px;
            font-size: 1rem;
            font-weight: 700;
            color: #64748b;
            cursor: pointer;
            white-space: nowrap;
            transition: all 0.2s;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            border: 1px solid #e2e8f0;
        }

        .status-tab:hover {
            background: #f8fafc;
            transform: translateY(-2px);
        }

        .status-tab.active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        .status-tab.pending-tab.active { background: #fbbf24; border-color: #fbbf24; color: #000; }
        .status-tab.accepted-tab.active { background: #3b82f6; border-color: #3b82f6; }
        .status-tab.ontheway-tab.active { background: #F57C00; border-color: #F57C00; }
        .status-tab.delivered-tab.active { background: #10b981; border-color: #10b981; }

        .orders-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
            gap: 20px;
        }

        .order-card {
            background: white;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            transition: all 0.3s ease;
            border: 1px solid #e2e8f0;
            animation: slideIn 0.3s ease;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .order-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 30px rgba(0,0,0,0.1);
        }

        .order-card.updated {
            animation: highlight 0.5s ease;
        }

        @keyframes highlight {
            0% { background-color: rgba(245, 124, 0, 0.2); }
            100% { background-color: white; }
        }

        .order-header {
            padding: 15px 20px;
            background: #f8fafc;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #e2e8f0;
        }

        .order-id {
            font-weight: 800;
            font-size: 1.2rem;
            color: #1e293b;
        }

        .order-status {
            padding: 6px 12px;
            border-radius: 30px;
            font-size: 0.8rem;
            font-weight: 700;
        }

        .order-status.pending { background: #fef3c7; color: #92400e; }
        .order-status.accepted { background: #dbeafe; color: #1e40af; }
        .order-status.on_the_way { background: #fff3e0; color: #F57C00; }
        .order-status.delivered { background: #dcfce7; color: #166534; }

        .order-body {
            padding: 20px;
        }

        .customer-info {
            background: #f8fafc;
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 15px;
        }

        .info-row {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 8px;
            color: #475569;
        }

        .info-row i {
            width: 20px;
            color: #667eea;
        }

        .order-items {
            background: #ffffff;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            padding: 12px;
            margin: 15px 0;
            max-height: 120px;
            overflow-y: auto;
        }

        .item-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px dashed #e2e8f0;
            font-size: 0.9rem;
        }

        .item-row:last-child {
            border-bottom: none;
        }

        .item-portion {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            font-size: 0.7rem;
            padding: 2px 8px;
            border-radius: 20px;
            background: #f1f5f9;
            margin-right: 8px;
        }

        .customer-notes {
            background: #fff3e0;
            border-right: 3px solid #F57C00;
            padding: 10px 12px;
            border-radius: 8px;
            margin: 10px 0;
        }

        .notes-icon {
            color: #F57C00;
            font-size: 0.8rem;
        }

        .notes-title {
            font-weight: 600;
            font-size: 0.75rem;
            color: #F57C00;
            margin-bottom: 4px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .notes-text {
            margin: 0;
            font-size: 0.85rem;
            color: #5a4a2e;
            line-height: 1.4;
        }

        .order-total {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 0;
            border-top: 2px solid #e2e8f0;
            font-weight: 800;
            font-size: 1.1rem;
        }

        .total-price {
            color: #667eea;
            font-size: 1.3rem;
        }

        .captain-info {
            background: #f0f9ff;
            border-radius: 12px;
            padding: 12px;
            margin: 15px 0;
            border-right: 4px solid #3b82f6;
        }

        .captain-info i {
            color: #3b82f6;
            margin-left: 8px;
        }

        .order-actions {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }

        .action-btn {
            flex: 1;
            padding: 12px;
            border: none;
            border-radius: 12px;
            font-size: 0.95rem;
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            transition: all 0.3s;
        }

        .action-btn.accept {
            background: #667eea;
            color: white;
        }

        .action-btn.accept:hover {
            background: #5a67d8;
            transform: translateY(-2px);
        }

        .action-btn.view {
            background: #e2e8f0;
            color: #334155;
        }

        .action-btn.view:hover {
            background: #cbd5e0;
        }

        .modal-content {
            border-radius: 20px;
            border: none;
        }

        .modal-header {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border-radius: 20px 20px 0 0;
            padding: 20px;
        }

        .modal-header .btn-close {
            filter: brightness(0) invert(1);
        }

        .captain-select {
            padding: 12px;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            font-size: 1rem;
        }

        .notification {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: white;
            padding: 15px 25px;
            border-radius: 50px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            display: flex;
            align-items: center;
            gap: 12px;
            z-index: 9999;
            animation: slideDown 0.3s ease;
            border-right: 4px solid;
            font-weight: 600;
        }

        .notification.success { border-right-color: #10b981; color: #065f46; }
        .notification.info { border-right-color: #3b82f6; color: #1e40af; }
        .notification.warning { border-right-color: #F57C00; color: #c2410c; }

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translate(-50%, -20px);
            }
            to {
                opacity: 1;
                transform: translate(-50%, 0);
            }
        }

        .notification.fade-out {
            opacity: 0;
            transform: translate(-50%, -20px);
            transition: all 0.3s;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            background: white;
            border-radius: 20px;
        }

        .empty-state i {
            font-size: 5rem;
            color: #cbd5e1;
            margin-bottom: 20px;
        }

        .loading-spinner {
            text-align: center;
            padding: 50px;
            background: white;
            border-radius: 20px;
        }

        .spinner {
            width: 50px;
            height: 50px;
            border: 4px solid #e2e8f0;
            border-top-color: #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .update-indicator {
            position: fixed;
            bottom: 20px;
            right: 20px;
            width: 45px;
            height: 45px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
            box-shadow: 0 4px 15px rgba(102,126,234,0.4);
            opacity: 0;
            transition: opacity 0.3s ease;
            z-index: 9998;
            pointer-events: none;
        }

        .update-indicator.show {
            opacity: 0.8;
        }

        @media (max-width: 768px) {
            .cashier-app { padding: 10px; }
            .header { padding: 20px; }
            .header h1 { font-size: 1.3rem; }
            .stats-grid { grid-template-columns: repeat(2, 1fr); gap: 10px; }
            .stat-card { padding: 15px; }
            .stat-value { font-size: 1.6rem; }
            .orders-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
    <div class="cashier-app">
        <div class="header">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
                <div>
                    <h1><i class="bi bi-cash-register me-2"></i>نظام الكاشير</h1>
                    <p class="mb-0">
                        <i class="bi bi-person-circle me-1"></i>
                        مرحباً، <?php echo htmlspecialchars($cashier['name']); ?>
                    </p>
                </div>
                <div class="d-flex gap-2">
                    <span class="date-badge">
                        <i class="bi bi-calendar3 me-1"></i>
                        <?php echo date('Y-m-d'); ?>
                    </span>
                    <button class="action-btn-header" onclick="window.location.href='logout.php'">
                        <i class="bi bi-box-arrow-left"></i>
                    </button>
                </div>
            </div>
        </div>

        <div class="stats-grid">
            <div class="stat-card pending" onclick="filterOrders('pending')">
                <div class="stat-value" id="pending-count">0</div>
                <div class="stat-label">قيد الانتظار</div>
                <div class="stat-icon"><i class="bi bi-hourglass"></i></div>
            </div>
            <div class="stat-card accepted" onclick="filterOrders('accepted')">
                <div class="stat-value" id="accepted-count">0</div>
                <div class="stat-label">تم القبول</div>
                <div class="stat-icon"><i class="bi bi-check-circle"></i></div>
            </div>
            <div class="stat-card ontheway" onclick="filterOrders('on_the_way')">
                <div class="stat-value" id="ontheway-count">0</div>
                <div class="stat-label">في الطريق</div>
                <div class="stat-icon"><i class="bi bi-truck"></i></div>
            </div>
            <div class="stat-card delivered" onclick="filterOrders('delivered')">
                <div class="stat-value" id="delivered-count">0</div>
                <div class="stat-label">مكتمل</div>
                <div class="stat-icon"><i class="bi bi-check2-all"></i></div>
            </div>
        </div>

        <div class="status-tabs">
            <button class="status-tab pending-tab active" onclick="filterOrders('pending')">
                <i class="bi bi-hourglass me-1"></i>قيد الانتظار
            </button>
            <button class="status-tab accepted-tab" onclick="filterOrders('accepted')">
                <i class="bi bi-check-circle me-1"></i>تم القبول
            </button>
            <button class="status-tab ontheway-tab" onclick="filterOrders('on_the_way')">
                <i class="bi bi-truck me-1"></i>في الطريق
            </button>
            <button class="status-tab delivered-tab" onclick="filterOrders('delivered')">
                <i class="bi bi-check2-all me-1"></i>مكتمل
            </button>
        </div>

        <div class="orders-container" id="ordersContainer">
            <div class="loading-spinner">
                <div class="spinner"></div>
                <p class="text-muted">جاري تحميل الطلبات...</p>
            </div>
        </div>
    </div>

    <audio id="notificationSound" preload="auto">
        <source src="assets/sounds/notification.mp3" type="audio/mpeg">
    </audio>

    <div class="update-indicator" id="updateIndicator">
        <i class="bi bi-arrow-repeat"></i>
    </div>

    <div class="modal fade" id="acceptModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-check-circle me-2"></i>قبول الطلب وتعيين كابتن</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="accept_order_id">
                    <div class="mb-3">
                        <label class="form-label fw-bold">اختر الكابتن <span class="text-danger">*</span></label>
                        <select class="captain-select form-select" id="accept_captain_id" required>
                            <option value="">-- اختر الكابتن --</option>
                            <?php 
                            $captains->data_seek(0);
                            while ($cap = $captains->fetch_assoc()): 
                            ?>
                                <option value="<?php echo $cap['id']; ?>">
                                    <?php echo htmlspecialchars($cap['name']); ?> - <?php echo $cap['phone']; ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="button" class="btn btn-primary" onclick="acceptOrderWithCaptain()">قبول وتعيين</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="orderModal" tabindex="-1">
        <div class="modal-dialog modal-lg modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-info-circle me-2"></i>تفاصيل الطلب</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="orderModalBody">
                    <div class="text-center p-4">
                        <div class="spinner"></div>
                        <p class="mt-2">جاري تحميل التفاصيل...</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إغلاق</button>
                    <button type="button" class="btn btn-primary" onclick="printReceipt()"><i class="bi bi-printer"></i> طباعة</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    // ============================================
    // المتغيرات العامة
    // ============================================
    let currentFilter = 'pending';
    let updateInterval = null;
    let isLoading = false;
    let lastUpdateTime = new Date().toISOString().slice(0, 19).replace('T', ' ');
    let knownOrders = new Map();
    let isUpdating = false;
    let currentOrder = null;

    const ordersContainer = document.getElementById('ordersContainer');
    const updateIndicator = document.getElementById('updateIndicator');
    const notificationSound = document.getElementById('notificationSound');

    // ============================================
    // دوال مساعدة
    // ============================================
    function showUpdateIndicator() {
        updateIndicator.classList.add('show');
        setTimeout(() => updateIndicator.classList.remove('show'), 500);
    }

    function playSound() {
        if (notificationSound) {
            notificationSound.play().catch(e => console.log('صوت غير متاح'));
        }
    }

    function showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        let icon = type === 'success' ? 'check-circle' : (type === 'warning' ? 'exclamation-triangle' : 'info-circle');
        notification.innerHTML = `<i class="bi bi-${icon} fs-4"></i><span>${message}</span>`;
        document.body.appendChild(notification);
        setTimeout(() => {
            notification.classList.add('fade-out');
            setTimeout(() => notification.remove(), 300);
        }, 3000);
    }

    function formatMoney(amount) {
        return Number(amount).toLocaleString('ar-EG') + ' ريال';
    }

    function escapeHtml(text) {
        if (!text) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    function getTimeAgo(timestamp) {
        const now = new Date();
        const past = new Date(timestamp);
        const diffSeconds = Math.floor((now - past) / 1000);
        if (diffSeconds < 60) return 'منذ لحظات';
        if (diffSeconds < 3600) return `منذ ${Math.floor(diffSeconds / 60)} دقيقة`;
        if (diffSeconds < 86400) return `منذ ${Math.floor(diffSeconds / 3600)} ساعة`;
        return past.toLocaleDateString('ar-EG');
    }

    function getStatusText(status) {
        const texts = { 'pending': 'قيد الانتظار', 'accepted': 'تم القبول', 'on_the_way': 'في الطريق', 'delivered': 'مكتمل' };
        return texts[status] || status;
    }

    function getPortionColor(portionName) {
        if (!portionName || portionName === 'كامل') return '#64748b';
        const colors = { 'ربع': '#4CAF50', 'نص': '#2196F3', 'حبة': '#F57C00', 'صغير': '#FF9800', 'وسط': '#03A9F4', 'كبير': '#F44336', 'نفر': '#9C27B0' };
        for (let key in colors) {
            if (portionName.includes(key)) return colors[key];
        }
        return '#F57C00';
    }

    // ============================================
    // جلب الطلبات
    // ============================================
    async function loadOrders(status = 'pending', silent = false) {
        if (isLoading) return;
        isLoading = true;
        
        if (!silent) {
            ordersContainer.innerHTML = `<div class="loading-spinner"><div class="spinner"></div><p class="text-muted">جاري تحميل الطلبات...</p></div>`;
        }
        
        try {
            const response = await fetch(`api_handler.php?action=get_orders&status=${status}`);
            const data = await response.json();
            
            if (data.success) {
                if (data.stats) {
                    document.getElementById('pending-count').textContent = data.stats.pending_count || 0;
                    document.getElementById('accepted-count').textContent = data.stats.accepted_count || 0;
                    document.getElementById('ontheway-count').textContent = data.stats.ontheway_count || 0;
                    document.getElementById('delivered-count').textContent = data.stats.delivered_count || 0;
                }
                if (data.last_updated) lastUpdateTime = data.last_updated;
                displayOrders(data.orders);
                currentFilter = status;
            } else {
                console.error('خطأ:', data.message);
                if (!silent) {
                    ordersContainer.innerHTML = `<div class="empty-state"><i class="bi bi-exclamation-triangle"></i><h5>حدث خطأ</h5><p>${data.message || 'فشل تحميل الطلبات'}</p><button class="btn btn-primary mt-3" onclick="loadOrders('${status}')">إعادة المحاولة</button></div>`;
                }
            }
        } catch (error) {
            console.error('خطأ:', error);
            if (!silent) {
                ordersContainer.innerHTML = `<div class="empty-state"><i class="bi bi-wifi-off"></i><h5>خطأ في الاتصال</h5><p>تعذر الاتصال بالخادم</p><button class="btn btn-primary mt-3" onclick="loadOrders('${status}')">إعادة المحاولة</button></div>`;
            }
        } finally {
            isLoading = false;
        }
    }

    function displayOrders(orders) {
        if (!orders || orders.length === 0) {
            ordersContainer.innerHTML = `<div class="empty-state"><i class="bi bi-inbox"></i><h5>لا توجد طلبات</h5><p>لا توجد طلبات في قائمة ${getStatusText(currentFilter)}</p></div>`;
            return;
        }
        
        let html = '<div class="orders-grid">';
        
        orders.forEach(order => {
            const knownStatus = knownOrders.get(order.id);
            if (knownStatus && knownStatus !== order.status) {
                if (order.status === 'on_the_way') {
                    playSound();
                    showNotification(`الكابتن في طريقه للطلب #${order.id}`, 'warning');
                }
                knownOrders.set(order.id, order.status);
            } else if (!knownStatus) {
                knownOrders.set(order.id, order.status);
                if (order.status === 'pending') {
                    playSound();
                    showNotification(`طلب جديد #${order.id} من ${order.customer_name}`, 'info');
                }
            }
            
            let itemsHtml = '';
            if (order.items && order.items.length > 0) {
                itemsHtml = order.items.slice(0, 4).map(item => {
                    let portionHtml = '';
                    if (item.portion_name && item.portion_name !== 'كامل' && item.portion_name !== '') {
                        portionHtml = `<span class="item-portion" style="background: ${getPortionColor(item.portion_name)}20; color: ${getPortionColor(item.portion_name)};">
                            <i class="bi bi-tag"></i> ${escapeHtml(item.portion_name)}
                        </span>`;
                    }
                    return `<div class="item-row"><div><span>${item.quantity}x ${escapeHtml(item.meal_name)}</span>${portionHtml}</div><span>${formatMoney(item.price)}</span></div>`;
                }).join('');
                if (order.items.length > 4) itemsHtml += `<div class="item-row text-muted">+${order.items.length - 4} أصناف أخرى</div>`;
            }
            
            let notesHtml = '';
            if (order.notes && order.notes.trim() !== '') {
                notesHtml = `<div class="customer-notes"><div class="notes-title"><i class="bi bi-chat-text notes-icon"></i>ملاحظات العميل:</div><p class="notes-text">${escapeHtml(order.notes)}</p></div>`;
            }
            
            html += `<div class="order-card" id="order-${order.id}" data-order-id="${order.id}" data-status="${order.status}">
                <div class="order-header"><span class="order-id">#${order.id}</span><span class="order-status ${order.status}">${getStatusText(order.status)}</span></div>
                <div class="order-body">
                    <div class="customer-info">
                        <div class="info-row"><i class="bi bi-person-circle"></i><span>${escapeHtml(order.customer_name)}</span></div>
                        <div class="info-row"><i class="bi bi-telephone"></i><span dir="ltr">${order.customer_phone}</span></div>
                        <div class="info-row"><i class="bi bi-geo-alt"></i><span>${order.customer_address || 'لا يوجد عنوان'}</span></div>
                        <div class="info-row"><i class="bi bi-clock"></i><span>${getTimeAgo(order.created_at)}</span></div>
                    </div>
                    <div class="order-items">${itemsHtml}</div>
                    ${notesHtml}
                    <div class="order-total"><span>الإجمالي:</span><span class="total-price">${formatMoney(order.total)}</span></div>`;
            
            if (order.captain_name) {
                html += `<div class="captain-info"><div><i class="bi bi-person-badge"></i> <strong>الكابتن:</strong> ${escapeHtml(order.captain_name)}</div>${order.captain_phone ? `<div><i class="bi bi-telephone"></i> <strong>هاتف:</strong> ${order.captain_phone}</div>` : ''}</div>`;
            }
            
            if (order.status === 'pending') {
                html += `<div class="order-actions"><button class="action-btn accept" onclick="showAcceptModal(${order.id})"><i class="bi bi-check-lg"></i> قبول مع كابتن</button><button class="action-btn view" onclick="viewOrder(${order.id})"><i class="bi bi-eye"></i> عرض</button></div>`;
            } else {
                html += `<div class="order-actions"><button class="action-btn view" onclick="viewOrder(${order.id})"><i class="bi bi-eye"></i> عرض التفاصيل</button></div>`;
            }
            
            html += `</div></div>`;
        });
        
        html += '</div>';
        ordersContainer.innerHTML = html;
    }

    // ============================================
    // التحديث التلقائي
    // ============================================
    async function checkForUpdates() {
        if (isUpdating) return;
        isUpdating = true;
        
        try {
            const response = await fetch(`api_handler.php?action=check_updates&last_check=${encodeURIComponent(lastUpdateTime)}`);
            const data = await response.json();
            
            if (data.success && data.updated_orders && data.updated_orders.length > 0) {
                showUpdateIndicator();
                for (const order of data.updated_orders) {
                    const knownStatus = knownOrders.get(order.id);
                    if (knownStatus && knownStatus !== order.status) {
                        knownOrders.set(order.id, order.status);
                        if (order.status === 'on_the_way') {
                            playSound();
                            showNotification(`الكابتن ${order.captain_name || ''} في طريقه للطلب #${order.id}`, 'warning');
                        }
                        updateOrderCard(order.id, order.status);
                    } else if (!knownStatus && order.status === 'pending') {
                        knownOrders.set(order.id, order.status);
                        playSound();
                        showNotification(`طلب جديد #${order.id}`, 'info');
                    }
                }
                if (data.updated_orders.length > 0) loadOrders(currentFilter, true);
                if (data.server_time) lastUpdateTime = data.server_time;
            }
        } catch (error) {
            console.error('خطأ:', error);
        } finally {
            isUpdating = false;
        }
    }

    function updateOrderCard(orderId, status) {
        const card = document.getElementById(`order-${orderId}`);
        if (card) {
            const statusElement = card.querySelector('.order-status');
            if (statusElement) {
                statusElement.textContent = getStatusText(status);
                statusElement.className = `order-status ${status}`;
            }
            card.setAttribute('data-status', status);
            card.classList.add('updated');
            setTimeout(() => card.classList.remove('updated'), 500);
        }
    }

    // ============================================
    // دوال التحكم
    // ============================================
    function filterOrders(status) {
        document.querySelectorAll('.status-tab').forEach(tab => tab.classList.remove('active'));
        let activeTab;
        if (status === 'pending') activeTab = document.querySelector('.status-tab.pending-tab');
        else if (status === 'accepted') activeTab = document.querySelector('.status-tab.accepted-tab');
        else if (status === 'on_the_way') activeTab = document.querySelector('.status-tab.ontheway-tab');
        else if (status === 'delivered') activeTab = document.querySelector('.status-tab.delivered-tab');
        if (activeTab) activeTab.classList.add('active');
        loadOrders(status);
    }

    function showAcceptModal(orderId) {
        document.getElementById('accept_order_id').value = orderId;
        new bootstrap.Modal(document.getElementById('acceptModal')).show();
    }

    async function acceptOrderWithCaptain() {
        const orderId = document.getElementById('accept_order_id').value;
        const captainId = document.getElementById('accept_captain_id').value;
        
        if (!captainId) {
            showNotification('يجب اختيار كابتن', 'error');
            return;
        }
        
        try {
            const response = await fetch('api_handler.php?action=accept_order', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ order_id: orderId, captain_id: captainId })
            });
            const data = await response.json();
            
            if (data.success) {
                bootstrap.Modal.getInstance(document.getElementById('acceptModal')).hide();
                showNotification('تم قبول الطلب وتعيين الكابتن بنجاح', 'success');
                loadOrders(currentFilter, true);
            } else {
                showNotification(data.message || 'حدث خطأ', 'error');
            }
        } catch (error) {
            console.error('خطأ:', error);
            showNotification('حدث خطأ في الاتصال بالخادم', 'error');
        }
    }

    async function viewOrder(orderId) {
        const modalBody = document.getElementById('orderModalBody');
        modalBody.innerHTML = `<div class="text-center p-4"><div class="spinner"></div><p class="mt-2">جاري تحميل التفاصيل...</p></div>`;
        
        try {
            const response = await fetch(`get_order_details.php?id=${orderId}`);
            const data = await response.json();
            
            if (data.success && data.order) {
                displayOrderDetails(data.order);
            } else {
                modalBody.innerHTML = `<div class="text-center p-4 text-danger"><i class="bi bi-exclamation-triangle fs-1"></i><p>${data.message || 'حدث خطأ في تحميل التفاصيل'}</p></div>`;
            }
        } catch (error) {
            console.error('خطأ:', error);
            modalBody.innerHTML = `<div class="text-center p-4 text-danger"><i class="bi bi-wifi-off fs-1"></i><p>خطأ في الاتصال بالخادم</p></div>`;
        }
    }

    function displayOrderDetails(order) {
        const modalBody = document.getElementById('orderModalBody');
        currentOrder = order;
        
        let itemsHtml = '';
        if (order.items && order.items.length > 0) {
            order.items.forEach(item => {
                let portionHtml = '';
                if (item.portion_name && item.portion_name !== 'كامل' && item.portion_name !== '') {
                    portionHtml = `<span style="display:inline-block; margin-right:8px; font-size:0.8rem; color:${getPortionColor(item.portion_name)};"><i class="bi bi-tag"></i> ${escapeHtml(item.portion_name)}</span>`;
                }
                itemsHtml += `<div style="display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid #eee;"><div><strong>${item.quantity}x ${escapeHtml(item.meal_name)}</strong>${portionHtml}</div><div>${formatMoney(item.price)}</div></div>`;
            });
        }
        
        let notesHtml = '';
        if (order.notes && order.notes.trim() !== '') {
            notesHtml = `<div class="alert alert-warning mt-3" style="background: #fff3e0; border-right: 4px solid #F57C00;"><h6 class="mb-2"><i class="bi bi-chat-text"></i> ملاحظات العميل:</h6><p class="mb-0">${escapeHtml(order.notes)}</p></div>`;
        }
        
        let captainHtml = '';
        if (order.captain_name) {
            captainHtml = `<div class="alert alert-info mt-3" style="background: #e3f2fd; border-right: 4px solid #2196F3;"><h6 class="mb-2"><i class="bi bi-person-badge"></i> معلومات الكابتن:</h6><p class="mb-1"><strong>الاسم:</strong> ${escapeHtml(order.captain_name)}</p>${order.captain_phone ? `<p class="mb-0"><strong>الهاتف:</strong> <a href="tel:${order.captain_phone}">${order.captain_phone}</a></p>` : ''}</div>`;
        }
        
        modalBody.innerHTML = `<div class="p-3">
            <h6 class="border-bottom pb-2 mb-3">معلومات العميل</h6>
            <p><strong>الاسم:</strong> ${escapeHtml(order.customer_name)}</p>
            <p><strong>الهاتف:</strong> ${order.customer_phone}</p>
            <p><strong>العنوان:</strong> ${order.customer_address || 'لا يوجد'}</p>
            <h6 class="border-bottom pb-2 mb-3 mt-4">معلومات الطلب</h6>
            <p><strong>رقم الطلب:</strong> #${order.id}</p>
            <p><strong>التاريخ:</strong> ${new Date(order.created_at).toLocaleString('ar-EG')}</p>
            <p><strong>الحالة:</strong> <span class="badge ${order.status === 'pending' ? 'bg-warning' : (order.status === 'on_the_way' ? 'bg-info' : 'bg-success')}">${getStatusText(order.status)}</span></p>
            <h6 class="border-bottom pb-2 mb-3 mt-4">عناصر الطلب</h6>
            <div style="background: #f8f9fa; border-radius: 12px; padding: 10px;">${itemsHtml || '<p class="text-center">لا توجد عناصر</p>'}</div>
            <div class="mt-3 pt-2 border-top d-flex justify-content-between fw-bold fs-5"><span>الإجمالي الكلي:</span><span style="color: #F57C00;">${formatMoney(order.total)}</span></div>
            ${notesHtml}${captainHtml}
        </div>`;
        
        new bootstrap.Modal(document.getElementById('orderModal')).show();
    }

    function printReceipt() {
        if (!currentOrder) return;
        const order = currentOrder;
        const printWindow = window.open('', '_blank');
        printWindow.document.write(`<html dir="rtl"><head><title>فاتورة طلب #${order.id}</title><style>body{font-family:'Tajawal',sans-serif;padding:20px}.header{text-align:center;margin-bottom:20px}table{width:100%;border-collapse:collapse;margin:15px 0}th,td{padding:8px;text-align:right;border-bottom:1px solid #ddd}th{background:#f5f5f5}.total{font-size:1.2rem;font-weight:bold;text-align:left;margin-top:15px}.notes{background:#fff3e0;padding:10px;border-radius:8px;margin-top:15px}</style></head><body>
            <div class="header"><h2>مطعم ماكس</h2><p>فاتورة طلب #${order.id}</p><p>${new Date(order.created_at).toLocaleString('ar-EG')}</p></div>
            <p><strong>العميل:</strong> ${order.customer_name}</p><p><strong>الهاتف:</strong> ${order.customer_phone}</p><p><strong>العنوان:</strong> ${order.customer_address || 'لا يوجد'}</p>
            ${order.notes ? `<div class="notes"><strong>ملاحظات العميل:</strong><br>${order.notes}</div>` : ''}
            <table><thead><tr><th>الكمية</th><th>الصنف</th><th>القسم</th><th>السعر</th><th>الإجمالي</th></tr></thead><tbody>
            ${order.items.map(item => `<tr><td>${item.quantity}</td><td>${item.meal_name}</td><td>${item.portion_name && item.portion_name !== 'كامل' ? item.portion_name : '-'}</td><td>${formatMoney(item.price)}</td><td>${formatMoney(item.price * item.quantity)}</td></tr>`).join('')}
            </tbody></table><div class="total">الإجمالي الكلي: ${formatMoney(order.total)}</div>
            ${order.captain_name ? `<div><strong>الكابتن:</strong> ${order.captain_name} ${order.captain_phone ? `- ${order.captain_phone}` : ''}</div>` : ''}
        </body></html>`);
        printWindow.document.close();
        printWindow.print();
    }

    function startAutoUpdate() {
        if (updateInterval) clearInterval(updateInterval);
        updateInterval = setInterval(checkForUpdates, 5000);
        console.log('تم بدء التحديث التلقائي');
    }

    document.addEventListener('DOMContentLoaded', () => {
        loadOrders('pending');
        startAutoUpdate();
        document.addEventListener('visibilitychange', () => { if (!document.hidden) loadOrders(currentFilter, true); });
    });

    window.addEventListener('beforeunload', () => { if (updateInterval) clearInterval(updateInterval); });
    </script>
</body>
</html>