<?php
/**
 * orders.php - إدارة الطلبات (مع تحديث تلقائي فعال)
 * @version 7.2.0
 */

require_once 'config.php';
checkAdminAuth();

// ============================================
// معالجة تحديث الطلب (AJAX)
// ============================================

// معالجة طلب AJAX لتحديث حالة الطلب
if (isset($_GET['ajax']) && $_GET['ajax'] == 'update_status') {
    header('Content-Type: application/json');
    
    $id = (int)$_POST['id'];
    $status = $conn->real_escape_string($_POST['status']);
    $captain_id = !empty($_POST['captain_id']) ? (int)$_POST['captain_id'] : 'NULL';
    
    $sql = "UPDATE orders SET status='$status', captain_id=" . $captain_id . ", updated_at = NOW() WHERE id=$id";
    
    if ($conn->query($sql)) {
        echo json_encode(['success' => true, 'message' => 'تم تحديث الطلب بنجاح']);
    } else {
        echo json_encode(['success' => false, 'message' => 'خطأ في تحديث الطلب: ' . $conn->error]);
    }
    exit;
}

// معالجة طلب AJAX لجلب جميع الطلبات (للتحديث الكامل)
if (isset($_GET['ajax']) && $_GET['ajax'] == 'get_all_orders') {
    header('Content-Type: application/json');
    
    $filter = isset($_GET['filter']) ? $_GET['filter'] : 'all';
    
    $sql = "
        SELECT o.*, 
               c.name as customer_name, 
               c.phone as customer_phone,
               c.address as customer_address,
               cp.name as captain_name,
               cp.phone as captain_phone,
               (SELECT COUNT(*) FROM order_items WHERE order_id = o.id) as items_count
        FROM orders o 
        JOIN customers c ON o.customer_id = c.id 
        LEFT JOIN captains cp ON o.captain_id = cp.id";
    
    if ($filter != 'all') {
        $sql .= " WHERE o.status = '" . $conn->real_escape_string($filter) . "'";
    }
    
    $sql .= " ORDER BY o.created_at DESC LIMIT 100";
    
    $result = $conn->query($sql);
    $orders = [];
    
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            // جلب أول وجبة مع القسم
            $first_item = $conn->query("
                SELECT m.name as meal_name, mp.name as portion_name, oi.quantity
                FROM order_items oi 
                JOIN meals m ON oi.meal_id = m.id 
                LEFT JOIN meal_portions mp ON oi.portion_id = mp.id 
                WHERE oi.order_id = {$row['id']} 
                LIMIT 3
            ");
            
            $items = [];
            if ($first_item) {
                while ($item = $first_item->fetch_assoc()) {
                    $items[] = $item;
                }
            }
            
            $row['preview_items'] = $items;
            $orders[] = $row;
        }
    }
    
    // جلب الإحصائيات
    $stats_sql = "SELECT 
                    COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending,
                    COUNT(CASE WHEN status = 'accepted' THEN 1 END) as accepted,
                    COUNT(CASE WHEN status = 'on_the_way' THEN 1 END) as on_the_way,
                    COUNT(CASE WHEN status = 'delivered' THEN 1 END) as delivered,
                    COUNT(*) as total
                  FROM orders";
    $stats_result = $conn->query($stats_sql);
    $stats = $stats_result->fetch_assoc();
    
    echo json_encode([
        'success' => true, 
        'orders' => $orders, 
        'stats' => $stats,
        'server_time' => date('Y-m-d H:i:s')
    ]);
    exit;
}

// ============================================
// معالجة تحديث الطلب (POST عادي)
// ============================================
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_order'])) {
    $id = (int)$_POST['id'];
    $status = $conn->real_escape_string($_POST['status']);
    $captain_id = !empty($_POST['captain_id']) ? (int)$_POST['captain_id'] : 'NULL';
    
    $sql = "UPDATE orders SET status='$status', captain_id=" . $captain_id . ", updated_at = NOW() WHERE id=$id";
    
    if ($conn->query($sql)) {
        $message = "تم تحديث الطلب بنجاح";
        $message_type = "success";
    } else {
        $message = "خطأ في تحديث الطلب";
        $message_type = "danger";
    }
}

// ============================================
// دوال مساعدة
// ============================================
function getStatusText($status) {
    $texts = [
        'pending' => 'قيد الانتظار',
        'accepted' => 'تم القبول',
        'preparing' => 'جاري التحضير',
        'ready' => 'جاهز',
        'on_the_way' => 'في الطريق',
        'delivered' => 'تم التوصيل',
        'cancelled' => 'ملغي'
    ];
    return $texts[$status] ?? $status;
}

function getStatusIcon($status) {
    $icons = [
        'pending' => 'hourglass-split',
        'accepted' => 'check-circle',
        'preparing' => 'gear',
        'ready' => 'check-circle',
        'on_the_way' => 'truck',
        'delivered' => 'check2-circle',
        'cancelled' => 'x-circle'
    ];
    return $icons[$status] ?? 'question-circle';
}

// ============================================
// جلب البيانات الأولية
// ============================================

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

// جلب إحصائيات الطلبات
$stats_sql = "SELECT 
                COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending,
                COUNT(CASE WHEN status = 'accepted' THEN 1 END) as accepted,
                COUNT(CASE WHEN status = 'on_the_way' THEN 1 END) as on_the_way,
                COUNT(CASE WHEN status = 'delivered' THEN 1 END) as delivered,
                COUNT(*) as total
              FROM orders";
$stats_result = $conn->query($stats_sql);
$stats = $stats_result->fetch_assoc();

// استعلام الطلبات الأولي
$orders_query = "
    SELECT o.*, 
           c.name as customer_name, 
           c.phone as customer_phone,
           c.address as customer_address,
           cp.name as captain_name,
           cp.phone as captain_phone,
           (SELECT COUNT(*) FROM order_items WHERE order_id = o.id) as items_count
    FROM orders o 
    JOIN customers c ON o.customer_id = c.id 
    LEFT JOIN captains cp ON o.captain_id = cp.id
    ORDER BY o.created_at DESC
    LIMIT 100";

$orders = $conn->query($orders_query);

// جلب تفاصيل طلب محدد
$order_details = null;
$order_items = [];

if (isset($_GET['action']) && $_GET['action'] == 'view' && isset($_GET['id'])) {
    $order_id = (int)$_GET['id'];
    
    $order_result = $conn->query("
        SELECT o.*, 
               c.name as customer_name, 
               c.phone as customer_phone, 
               c.address as customer_address,
               cp.name as captain_name, 
               cp.phone as captain_phone
        FROM orders o 
        JOIN customers c ON o.customer_id = c.id 
        LEFT JOIN captains cp ON o.captain_id = cp.id
        WHERE o.id = $order_id
    ");
    
    if ($order_result && $order_result->num_rows > 0) {
        $order_details = $order_result->fetch_assoc();
        
        $items_result = $conn->query("
            SELECT oi.*, 
                   m.name as meal_name,
                   mp.name as portion_name
            FROM order_items oi 
            JOIN meals m ON oi.meal_id = m.id 
            LEFT JOIN meal_portions mp ON oi.portion_id = mp.id
            WHERE oi.order_id = $order_id
            ORDER BY oi.id ASC
        ");
        
        if ($items_result) {
            $order_items = $items_result->fetch_all(MYSQLI_ASSOC);
        }
    }
}

$page_title = 'إدارة الطلبات';
include 'includes/header.php';
?>

<style>
/* ============================================
   Mobile First Design - نظام الطلبات
   ============================================ */

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    background: #f5f7fb;
    font-family: 'Tajawal', sans-serif;
}

/* الهيدر العلوي */
.mobile-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 12px 16px;
    position: sticky;
    top: 0;
    z-index: 100;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.mobile-header h1 {
    font-size: 1.2rem;
    margin: 0;
    font-weight: 600;
}

.mobile-header .header-actions {
    display: flex;
    gap: 12px;
}

.mobile-header .header-btn {
    background: rgba(255,255,255,0.2);
    border: none;
    color: white;
    width: 36px;
    height: 36px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.1rem;
    cursor: pointer;
    transition: all 0.2s;
}

/* المحتوى الرئيسي */
.main-content-mobile {
    padding: 16px;
    max-width: 600px;
    margin: 0 auto;
}

/* بطاقات الإحصائيات */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    margin-bottom: 20px;
}

.stat-card-mobile {
    background: white;
    border-radius: 16px;
    padding: 14px 10px;
    text-align: center;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
    border: 1px solid #e9ecef;
    cursor: pointer;
    transition: all 0.2s;
}

.stat-number {
    font-size: 1.6rem;
    font-weight: 800;
    line-height: 1.2;
}

.stat-label {
    font-size: 0.7rem;
    color: #6c757d;
    margin-top: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
}

.stat-card-mobile.pending .stat-number { color: #ffc107; }
.stat-card-mobile.accepted .stat-number { color: #0dcaf0; }
.stat-card-mobile.ontheway .stat-number { color: #0d6efd; }
.stat-card-mobile.delivered .stat-number { color: #198754; }

/* شريط التحكم */
.control-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    flex-wrap: wrap;
    gap: 10px;
    background: white;
    padding: 10px 16px;
    border-radius: 50px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}

.orders-count {
    background: #e9ecef;
    padding: 6px 12px;
    border-radius: 30px;
    font-size: 0.75rem;
    font-weight: 600;
    color: #495057;
}

.auto-refresh-toggle {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 0.75rem;
    color: #6c757d;
}

.auto-refresh-toggle .switch {
    position: relative;
    display: inline-block;
    width: 44px;
    height: 24px;
}

.auto-refresh-toggle .switch input {
    opacity: 0;
    width: 0;
    height: 0;
}

.auto-refresh-toggle .slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    transition: 0.2s;
    border-radius: 24px;
}

.auto-refresh-toggle .slider:before {
    position: absolute;
    content: "";
    height: 20px;
    width: 20px;
    left: 2px;
    bottom: 2px;
    background-color: white;
    transition: 0.2s;
    border-radius: 50%;
}

.auto-refresh-toggle input:checked + .slider {
    background-color: #667eea;
}

.auto-refresh-toggle input:checked + .slider:before {
    transform: translateX(20px);
}

.refresh-btn {
    background: #e9ecef;
    border: none;
    width: 36px;
    height: 36px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #495057;
    font-size: 1rem;
    cursor: pointer;
    transition: all 0.2s;
}

.timer-indicator {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 0.7rem;
    color: #6c757d;
    background: #f8f9fa;
    padding: 4px 8px;
    border-radius: 30px;
}

/* بطاقات الطلبات */
.orders-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.order-card-mobile {
    background: white;
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0,0,0,0.05);
    transition: all 0.2s;
    border: 1px solid #e9ecef;
}

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

@keyframes cardFlash {
    0% { background-color: rgba(102, 126, 234, 0.2); }
    100% { background-color: white; }
}

.card-header-mobile {
    padding: 14px 16px;
    background: #f8f9fa;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #e9ecef;
}

.order-id {
    font-weight: 700;
    font-size: 1rem;
    color: #667eea;
}

.order-time {
    font-size: 0.7rem;
    color: #6c757d;
}

.card-body-mobile {
    padding: 14px 16px;
}

.info-row-mobile {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 10px;
    font-size: 0.85rem;
    color: #495057;
}

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

.items-preview {
    background: #f8f9fa;
    border-radius: 12px;
    padding: 10px;
    margin: 12px 0;
    font-size: 0.8rem;
}

.item-preview {
    display: flex;
    justify-content: space-between;
    padding: 6px 0;
    border-bottom: 1px dashed #e9ecef;
}

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

.portion-tag {
    display: inline-flex;
    align-items: center;
    gap: 3px;
    font-size: 0.65rem;
    padding: 2px 6px;
    border-radius: 20px;
    background: #e9ecef;
    margin-right: 6px;
}

.customer-notes-mobile {
    background: #fff8e7;
    border-right: 3px solid #ffc107;
    padding: 8px 12px;
    border-radius: 10px;
    margin: 10px 0;
    font-size: 0.75rem;
    color: #856404;
}

.order-total-mobile {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 10px;
    margin-top: 8px;
    border-top: 1px solid #e9ecef;
    font-weight: 600;
    font-size: 0.9rem;
}

.total-amount {
    color: #667eea;
    font-size: 1.1rem;
    font-weight: 700;
}

.status-badge-mobile {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 5px 12px;
    border-radius: 30px;
    font-size: 0.7rem;
    font-weight: 600;
}

.status-badge-mobile.pending { background: #fff3cd; color: #856404; }
.status-badge-mobile.accepted { background: #cff4fc; color: #055160; }
.status-badge-mobile.on_the_way { background: #cfe2ff; color: #084298; }
.status-badge-mobile.delivered { background: #d1e7dd; color: #0f5132; }

.action-buttons {
    display: flex;
    gap: 10px;
    margin-top: 12px;
}

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

.action-btn-mobile.primary {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
}

.action-btn-mobile.secondary {
    background: #e9ecef;
    color: #495057;
}

.action-btn-mobile.warning {
    background: #ffc107;
    color: #000;
}

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

/* مودال */
.modal-mobile {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,0.5);
    z-index: 1000;
    display: none;
    align-items: flex-end;
}

.modal-mobile.active {
    display: flex;
}

.modal-content-mobile {
    background: white;
    border-radius: 24px 24px 0 0;
    width: 100%;
    max-height: 85vh;
    overflow-y: auto;
    animation: slideUp 0.3s ease;
}

@keyframes slideUp {
    from { transform: translateY(100%); }
    to { transform: translateY(0); }
}

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

.modal-body-mobile {
    padding: 16px;
}

.modal-close {
    position: absolute;
    top: 12px;
    left: 12px;
    background: rgba(255,255,255,0.2);
    border: none;
    width: 36px;
    height: 36px;
    border-radius: 50%;
    color: white;
    font-size: 1.2rem;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}

/* رسائل التنبيه */
.toast-message {
    position: fixed;
    bottom: 20px;
    left: 16px;
    right: 16px;
    background: white;
    padding: 12px 16px;
    border-radius: 60px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.15);
    display: flex;
    align-items: center;
    gap: 10px;
    z-index: 1100;
    animation: slideUp 0.3s ease;
    border-right: 4px solid;
}

.toast-message.success { border-right-color: #198754; }
.toast-message.danger { border-right-color: #dc3545; }
.toast-message.warning { border-right-color: #ffc107; }
.toast-message.info { border-right-color: #0dcaf0; }

/* مؤشر التحديث */
.update-indicator {
    position: fixed;
    bottom: 80px;
    right: 16px;
    width: 44px;
    height: 44px;
    background: #667eea;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 1.2rem;
    opacity: 0;
    transition: opacity 0.3s;
    z-index: 1050;
    box-shadow: 0 4px 12px rgba(102,126,234,0.4);
}

.update-indicator.show {
    opacity: 1;
    animation: pulse 0.5s ease;
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
}

/* شاشات أكبر */
@media (min-width: 768px) {
    .stats-grid {
        grid-template-columns: repeat(4, 1fr);
        gap: 15px;
    }
    
    .main-content-mobile {
        max-width: 1200px;
        padding: 24px;
    }
    
    .orders-list {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
        gap: 20px;
    }
}
</style>

<!-- الهيدر -->
<div class="mobile-header">
    <h1><i class="bi bi-cart"></i> الطلبات</h1>
    <div class="header-actions">
        <button class="header-btn" onclick="window.location.href='dashboard.php'">
            <i class="bi bi-house-door"></i>
        </button>
    </div>
</div>

<div class="main-content-mobile">
    <?php if (isset($_GET['action']) && $_GET['action'] == 'view' && $order_details): ?>
    <!-- عرض تفاصيل الطلب -->
    <div class="d-flex justify-content-between align-items-center mb-3">
        <a href="orders.php" class="btn btn-sm btn-outline-secondary">
            <i class="bi bi-arrow-right"></i> عودة
        </a>
        <span class="fw-bold">طلب #<?php echo $order_details['id']; ?></span>
    </div>
    
    <!-- بطاقة معلومات العميل -->
    <div class="order-card-mobile mb-3">
        <div class="card-header-mobile">
            <span><i class="bi bi-person"></i> معلومات العميل</span>
            <span class="status-badge-mobile <?php echo $order_details['status']; ?>">
                <i class="bi bi-<?php echo getStatusIcon($order_details['status']); ?>"></i>
                <?php echo getStatusText($order_details['status']); ?>
            </span>
        </div>
        <div class="card-body-mobile">
            <div class="info-row-mobile">
                <i class="bi bi-person-circle"></i>
                <span><?php echo e($order_details['customer_name']); ?></span>
            </div>
            <div class="info-row-mobile">
                <i class="bi bi-telephone"></i>
                <span dir="ltr"><?php echo e($order_details['customer_phone']); ?></span>
            </div>
            <div class="info-row-mobile">
                <i class="bi bi-geo-alt"></i>
                <span><?php echo e($order_details['customer_address'] ?: 'لا يوجد عنوان'); ?></span>
            </div>
        </div>
    </div>
    
    <!-- ملاحظات العميل -->
    <?php if (!empty($order_details['notes'])): ?>
    <div class="customer-notes-mobile mb-3">
        <i class="bi bi-chat-text"></i>
        <strong>ملاحظات العميل:</strong>
        <p class="mb-0 mt-1"><?php echo nl2br(e($order_details['notes'])); ?></p>
    </div>
    <?php endif; ?>
    
    <!-- عناصر الطلب -->
    <div class="order-card-mobile mb-3">
        <div class="card-header-mobile">
            <span><i class="bi bi-basket"></i> عناصر الطلب</span>
        </div>
        <div class="card-body-mobile">
            <?php 
            $subtotal = 0;
            foreach ($order_items as $item): 
                $price = $item['price'];
                $total = $price * $item['quantity'];
                $subtotal += $total;
                $portion_name = $item['portion_name'] ?: 'كامل';
            ?>
            <div class="item-preview">
                <div>
                    <strong><?php echo $item['quantity']; ?>x <?php echo e($item['meal_name']); ?></strong>
                    <?php if ($portion_name != 'كامل'): ?>
                    <span class="portion-tag half">
                        <i class="bi bi-tag"></i> <?php echo e($portion_name); ?>
                    </span>
                    <?php endif; ?>
                </div>
                <div><?php echo number_format($total, 2); ?> ريال</div>
            </div>
            <?php endforeach; ?>
            
            <div class="order-total-mobile mt-2">
                <span>المجموع الفرعي</span>
                <span><?php echo number_format($subtotal, 2); ?> ريال</span>
            </div>
            <?php if ($order_details['discount_amount'] > 0): ?>
            <div class="order-total-mobile text-success">
                <span>التخفيض</span>
                <span>-<?php echo number_format($order_details['discount_amount'], 2); ?> ريال</span>
            </div>
            <?php endif; ?>
            <div class="order-total-mobile">
                <span><strong>الإجمالي الكلي</strong></span>
                <span class="total-amount"><?php echo number_format($order_details['total'], 2); ?> ريال</span>
            </div>
        </div>
    </div>
    
    <!-- معلومات الكابتن -->
    <?php if ($order_details['captain_name']): ?>
    <div class="order-card-mobile mb-3">
        <div class="card-header-mobile">
            <span><i class="bi bi-truck"></i> معلومات الكابتن</span>
        </div>
        <div class="card-body-mobile">
            <div class="info-row-mobile">
                <i class="bi bi-person-badge"></i>
                <span><?php echo e($order_details['captain_name']); ?></span>
            </div>
            <div class="info-row-mobile">
                <i class="bi bi-telephone"></i>
                <span dir="ltr"><?php echo e($order_details['captain_phone']); ?></span>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- أزرار الإجراءات -->
    <div class="action-buttons">
        <button class="action-btn-mobile warning" onclick="openUpdateModal(<?php echo $order_details['id']; ?>, '<?php echo $order_details['status']; ?>', <?php echo $order_details['captain_id'] ?: 'null'; ?>)">
            <i class="bi bi-pencil"></i> تحديث
        </button>
        <button class="action-btn-mobile primary" onclick="window.print()">
            <i class="bi bi-printer"></i> طباعة
        </button>
    </div>
    
    <?php else: ?>
    
    <!-- بطاقات الإحصائيات -->
    <div class="stats-grid">
        <div class="stat-card-mobile pending" onclick="filterOrders('pending')">
            <div class="stat-number" id="stat-pending"><?php echo $stats['pending'] ?? 0; ?></div>
            <div class="stat-label"><i class="bi bi-hourglass-split"></i> قيد الانتظار</div>
        </div>
        <div class="stat-card-mobile accepted" onclick="filterOrders('accepted')">
            <div class="stat-number" id="stat-accepted"><?php echo $stats['accepted'] ?? 0; ?></div>
            <div class="stat-label"><i class="bi bi-check-circle"></i> تم القبول</div>
        </div>
        <div class="stat-card-mobile ontheway" onclick="filterOrders('on_the_way')">
            <div class="stat-number" id="stat-ontheway"><?php echo $stats['on_the_way'] ?? 0; ?></div>
            <div class="stat-label"><i class="bi bi-truck"></i> في الطريق</div>
        </div>
        <div class="stat-card-mobile delivered" onclick="filterOrders('delivered')">
            <div class="stat-number" id="stat-delivered"><?php echo $stats['delivered'] ?? 0; ?></div>
            <div class="stat-label"><i class="bi bi-check2-circle"></i> مكتمل</div>
        </div>
    </div>
    
    <!-- شريط التحكم -->
    <div class="control-bar">
        <div class="orders-count">
            <i class="bi bi-receipt"></i> <span id="totalOrders"><?php echo $orders->num_rows; ?></span> طلب
        </div>
        <div class="auto-refresh-toggle">
            <label class="switch">
                <input type="checkbox" id="autoRefreshToggle" checked>
                <span class="slider"></span>
            </label>
            <span>تحديث تلقائي</span>
        </div>
        <div class="timer-indicator" id="timerIndicator">
            <i class="bi bi-hourglass-split"></i>
            <span id="timerSeconds">30</span> ث
        </div>
        <button class="refresh-btn" id="manualRefreshBtn">
            <i class="bi bi-arrow-clockwise"></i>
        </button>
    </div>
    
    <!-- قائمة الطلبات -->
    <div class="orders-list" id="ordersList">
        <!-- سيتم ملء القائمة بواسطة JavaScript -->
        <div style="text-align: center; padding: 40px;">
            <div class="spinner-border text-primary"></div>
            <p class="mt-2 text-muted">جاري تحميل الطلبات...</p>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- مودال تحديث الطلب -->
<div class="modal-mobile" id="updateModal">
    <div class="modal-content-mobile">
        <div class="modal-header-mobile">
            <button class="modal-close" onclick="closeUpdateModal()"><i class="bi bi-x-lg"></i></button>
            <h5 class="mb-0 text-center">تحديث حالة الطلب</h5>
        </div>
        <div class="modal-body-mobile">
            <form id="updateOrderForm">
                <input type="hidden" name="id" id="update_id">
                <div class="mb-3">
                    <label class="form-label">حالة الطلب</label>
                    <select class="form-control" name="status" id="update_status" required>
                        <option value="pending">⏳ قيد الانتظار</option>
                        <option value="accepted">✅ تم القبول</option>
                        <option value="on_the_way">🚚 في الطريق</option>
                        <option value="delivered">🎉 تم التوصيل</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">تعيين كابتن</label>
                    <select class="form-control" name="captain_id" id="update_captain">
                        <option value="">-- بدون كابتن --</option>
                        <?php 
                        $captains->data_seek(0);
                        while ($captain = $captains->fetch_assoc()): ?>
                        <option value="<?php echo $captain['id']; ?>">
                            <?php echo e($captain['name']); ?> - <?php echo e($captain['phone']); ?>
                        </option>
                        <?php endwhile; ?>
                    </select>
                </div>
                <div class="action-buttons">
                    <button type="button" class="action-btn-mobile secondary" onclick="closeUpdateModal()">إلغاء</button>
                    <button type="submit" class="action-btn-mobile primary">تحديث</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- مؤشر التحديث -->
<div class="update-indicator" id="updateIndicator">
    <i class="bi bi-arrow-repeat"></i>
</div>

<script>
// ============================================
// متغيرات عامة
// ============================================
let autoRefreshEnabled = true;
let refreshInterval = null;
let timerSeconds = 30;
let currentFilter = 'all';
let isUpdating = false;

const updateIndicator = document.getElementById('updateIndicator');
const timerSecondsSpan = document.getElementById('timerSeconds');
const autoRefreshToggle = document.getElementById('autoRefreshToggle');
const ordersList = document.getElementById('ordersList');

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

function getStatusIcon(status) {
    const icons = {
        'pending': 'hourglass-split',
        'accepted': 'check-circle',
        'on_the_way': 'truck',
        'delivered': 'check2-circle'
    };
    return icons[status] || 'question-circle';
}

function getStatusBadgeClass(status) {
    return status;
}

function showToast(message, type = 'success') {
    const toast = document.createElement('div');
    toast.className = `toast-message ${type}`;
    const icon = type === 'success' ? 'check-circle-fill' : (type === 'warning' ? 'exclamation-triangle-fill' : 'info-circle-fill');
    toast.innerHTML = `<i class="bi bi-${icon}"></i><span>${message}</span>`;
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 3000);
}

function playNotificationSound() {
    const audio = new Audio();
    audio.src = 'assets/sounds/notification.mp3';
    audio.play().catch(e => console.log('صوت غير متاح'));
}

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 renderOrders(orders, stats) {
    if (!ordersList) return;
    
    if (!orders || orders.length === 0) {
        ordersList.innerHTML = `
            <div class="empty-state">
                <i class="bi bi-inbox"></i>
                <h4>لا توجد طلبات</h4>
                <p>لم يتم إضافة أي طلبات بعد</p>
            </div>
        `;
        return;
    }
    
    let html = '';
    
    orders.forEach(order => {
        // عرض معاينة العناصر
        let itemsHtml = '';
        if (order.preview_items && order.preview_items.length > 0) {
            itemsHtml = '<div class="items-preview">';
            order.preview_items.forEach(item => {
                itemsHtml += `
                    <div class="item-preview">
                        <div>
                            ${item.quantity}x ${escapeHtml(item.meal_name)}
                            ${item.portion_name && item.portion_name != 'كامل' ? 
                                `<span class="portion-tag half"><i class="bi bi-tag"></i> ${escapeHtml(item.portion_name)}</span>` : ''}
                        </div>
                    </div>
                `;
            });
            if (order.items_count > 3) {
                itemsHtml += `<div class="text-muted text-center small mt-1">+${order.items_count - 3} أصناف أخرى</div>`;
            }
            itemsHtml += '</div>';
        }
        
        // ملاحظات العميل
        let notesHtml = '';
        if (order.notes && order.notes.trim() !== '') {
            notesHtml = `
                <div class="customer-notes-mobile">
                    <i class="bi bi-chat-text"></i>
                    ${escapeHtml(order.notes.substring(0, 60))}
                </div>
            `;
        }
        
        html += `
            <div class="order-card-mobile" id="order-card-${order.id}" data-order-id="${order.id}" data-status="${order.status}">
                <div class="card-header-mobile">
                    <span class="order-id">#${order.id}</span>
                    <span class="order-time">${new Date(order.created_at).toLocaleTimeString('ar-EG', {hour:'2-digit', minute:'2-digit'})}</span>
                </div>
                <div class="card-body-mobile">
                    <div class="info-row-mobile">
                        <i class="bi bi-person-circle"></i>
                        <span>${escapeHtml(order.customer_name)}</span>
                    </div>
                    <div class="info-row-mobile">
                        <i class="bi bi-telephone"></i>
                        <span dir="ltr">${escapeHtml(order.customer_phone)}</span>
                    </div>
                    ${itemsHtml}
                    ${notesHtml}
                    <div class="order-total-mobile">
                        <span>المجموع:</span>
                        <span class="total-amount">${formatMoney(order.total)}</span>
                    </div>
                    <div class="mt-2">
                        <span class="status-badge-mobile ${order.status}">
                            <i class="bi bi-${getStatusIcon(order.status)}"></i>
                            ${getStatusText(order.status)}
                        </span>
                        ${order.captain_name ? 
                            `<span class="badge bg-info ms-2"><i class="bi bi-person-badge"></i> ${escapeHtml(order.captain_name)}</span>` : ''}
                    </div>
                    <div class="action-buttons mt-2">
                        <button class="action-btn-mobile secondary" onclick="viewOrderDetails(${order.id})">
                            <i class="bi bi-eye"></i> عرض
                        </button>
                        <button class="action-btn-mobile warning" onclick="openUpdateModal(${order.id}, '${order.status}', ${order.captain_id || 'null'})">
                            <i class="bi bi-pencil"></i> تحديث
                        </button>
                    </div>
                </div>
            </div>
        `;
    });
    
    ordersList.innerHTML = html;
    
    // تحديث الإحصائيات
    if (stats) {
        document.getElementById('stat-pending').textContent = stats.pending || 0;
        document.getElementById('stat-accepted').textContent = stats.accepted || 0;
        document.getElementById('stat-ontheway').textContent = stats.on_the_way || 0;
        document.getElementById('stat-delivered').textContent = stats.delivered || 0;
        document.getElementById('totalOrders').textContent = stats.total || 0;
    }
}

// ============================================
// تحميل الطلبات
// ============================================
async function loadOrders(silent = false) {
    if (isUpdating && !silent) return;
    if (!silent) isUpdating = true;
    
    try {
        const url = `orders.php?ajax=get_all_orders&filter=${currentFilter}&t=${Date.now()}`;
        const response = await fetch(url);
        const data = await response.json();
        
        if (data.success) {
            // حفظ الحالات القديمة للطلبات
            const oldStatuses = new Map();
            document.querySelectorAll('.order-card-mobile').forEach(card => {
                const id = card.getAttribute('data-order-id');
                const status = card.getAttribute('data-status');
                if (id && status) oldStatuses.set(id, status);
            });
            
            // عرض الطلبات الجديدة
            renderOrders(data.orders, data.stats);
            
            // التحقق من الطلبات الجديدة والمتغيرة
            if (data.orders) {
                let newOrdersCount = 0;
                let onWayCount = 0;
                
                data.orders.forEach(order => {
                    const oldStatus = oldStatuses.get(String(order.id));
                    if (!oldStatus) {
                        // طلب جديد
                        newOrdersCount++;
                        if (order.status === 'pending') {
                            playNotificationSound();
                        }
                    } else if (oldStatus !== order.status) {
                        // تغيرت الحالة
                        if (order.status === 'on_the_way') {
                            onWayCount++;
                            playNotificationSound();
                        }
                        // تمييز البطاقة المتغيرة
                        setTimeout(() => {
                            const card = document.getElementById(`order-card-${order.id}`);
                            if (card) card.classList.add('updated');
                            setTimeout(() => card?.classList.remove('updated'), 500);
                        }, 100);
                    }
                });
                
                // إشعارات
                if (newOrdersCount > 0) {
                    showToast(`📦 ${newOrdersCount} طلب جديد`, 'info');
                }
                if (onWayCount > 0) {
                    showToast(`🚚 ${onWayCount} طلب في الطريق`, 'warning');
                }
            }
        } else {
            console.error('خطأ في تحميل الطلبات');
        }
    } catch (error) {
        console.error('خطأ في الاتصال:', error);
    } finally {
        if (!silent) isUpdating = false;
    }
}

// ============================================
// دالة التحديث الدوري
// ============================================
function updateTimer() {
    if (!autoRefreshEnabled) return;
    
    if (timerSeconds <= 0) {
        timerSeconds = 30;
        if (timerSecondsSpan) timerSecondsSpan.textContent = timerSeconds;
        
        // إظهار مؤشر التحديث
        updateIndicator.classList.add('show');
        
        // تحميل الطلبات
        loadOrders(true).finally(() => {
            setTimeout(() => updateIndicator.classList.remove('show'), 500);
        });
    } else {
        timerSeconds--;
        if (timerSecondsSpan) timerSecondsSpan.textContent = timerSeconds;
    }
}

function startAutoRefresh() {
    if (refreshInterval) clearInterval(refreshInterval);
    autoRefreshEnabled = true;
    timerSeconds = 30;
    if (timerSecondsSpan) timerSecondsSpan.textContent = timerSeconds;
    refreshInterval = setInterval(updateTimer, 1000);
    console.log('تم بدء التحديث التلقائي (كل 30 ثانية)');
}

function stopAutoRefresh() {
    if (refreshInterval) {
        clearInterval(refreshInterval);
        refreshInterval = null;
    }
    autoRefreshEnabled = false;
    if (timerSecondsSpan) timerSecondsSpan.textContent = '--';
    console.log('تم إيقاف التحديث التلقائي');
}

// ============================================
// دوال التحكم
// ============================================
function viewOrderDetails(orderId) {
    window.location.href = `orders.php?action=view&id=${orderId}`;
}

function filterOrders(status) {
    currentFilter = status;
    loadOrders();
}

function openUpdateModal(id, status, captainId) {
    document.getElementById('update_id').value = id;
    document.getElementById('update_status').value = status;
    document.getElementById('update_captain').value = captainId || '';
    document.getElementById('updateModal').classList.add('active');
}

function closeUpdateModal() {
    document.getElementById('updateModal').classList.remove('active');
}

// ============================================
// تحديث الطلب عبر AJAX
// ============================================
document.getElementById('updateOrderForm')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    formData.append('ajax', 'update_status');
    
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> جاري...';
    submitBtn.disabled = true;
    
    try {
        const response = await fetch('orders.php?ajax=update_status', {
            method: 'POST',
            body: formData
        });
        const data = await response.json();
        
        if (data.success) {
            showToast(data.message, 'success');
            closeUpdateModal();
            // تحديث القائمة فوراً
            loadOrders();
        } else {
            showToast(data.message, 'danger');
        }
    } catch (error) {
        console.error('Error:', error);
        showToast('حدث خطأ في الاتصال', 'danger');
    } finally {
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    }
});

// ============================================
// تهيئة الصفحة
// ============================================
document.addEventListener('DOMContentLoaded', function() {
    const manualRefreshBtn = document.getElementById('manualRefreshBtn');
    
    // تحميل الطلبات الأولية
    loadOrders();
    
    // بدء التحديث التلقائي
    if (autoRefreshToggle && autoRefreshToggle.checked) {
        startAutoRefresh();
    }
    
    // التحكم في مفتاح التحديث التلقائي
    if (autoRefreshToggle) {
        autoRefreshToggle.addEventListener('change', function() {
            if (this.checked) {
                startAutoRefresh();
            } else {
                stopAutoRefresh();
            }
        });
    }
    
    // زر التحديث اليدوي
    if (manualRefreshBtn) {
        manualRefreshBtn.addEventListener('click', function() {
            timerSeconds = 30;
            if (timerSecondsSpan) timerSecondsSpan.textContent = timerSeconds;
            updateIndicator.classList.add('show');
            loadOrders().finally(() => {
                setTimeout(() => updateIndicator.classList.remove('show'), 500);
            });
            showToast('جاري تحديث الطلبات...', 'info');
        });
    }
    
    // تحديث عند عودة الصفحة
    document.addEventListener('visibilitychange', function() {
        if (!document.hidden && autoRefreshToggle?.checked) {
            loadOrders(true);
        }
    });
});

window.addEventListener('beforeunload', function() {
    if (refreshInterval) clearInterval(refreshInterval);
});
</script>

<?php include 'includes/footer.php'; ?>