<?php
// تفعيل عرض الأخطاء للتطوير فقط - عطله في الإنتاج
// error_reporting(E_ALL);
// ini_set('display_errors', 1);

session_start();
require_once '../../config/database.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

try {
    $database = new Database();
    $db = $database->getConnection();
} catch (Exception $e) {
    die("خطأ في الاتصال بقاعدة البيانات: " . $e->getMessage());
}

$message = '';
$messageType = 'success';

// معالجة تحديث الحالة
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    try {
        $order_ids = $_POST['order_ids'] ?? [];
        $new_status = $_POST['new_status'] ?? '';
        $notes = $_POST['status_notes'] ?? '';
        
        if (empty($order_ids) || empty($new_status)) {
            throw new Exception('الرجاء اختيار طلبات وحالة جديدة');
        }
        
        $db->beginTransaction();
        
        $updated_count = 0;
        foreach ($order_ids as $order_id) {
            $query = "UPDATE orders SET status = ?, updated_at = NOW() WHERE id = ?";
            $stmt = $db->prepare($query);
            if ($stmt->execute([$new_status, $order_id])) {
                $updated_count++;
                
                // إضافة ملاحظة إذا وجدت
                if (!empty($notes)) {
                    $query = "UPDATE orders SET notes = CONCAT(IFNULL(notes, ''), '/n', ?) WHERE id = ?";
                    $stmt = $db->prepare($query);
                    $stmt->execute([date('Y-m-d H:i') . ': ' . $notes, $order_id]);
                }
            }
        }
        
        $db->commit();
        $message = "تم تحديث حالة {$updated_count} طلب بنجاح!";
        $messageType = 'success';
        
    } catch (Exception $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        $message = 'خطأ: ' . $e->getMessage();
        $messageType = 'error';
    }
}

// جلب الطلبات المشحونة
try {
    // محاولة جلب الطلبات مع معالجة أسماء الأعمدة المختلفة
    $query = "SELECT o.id, o.order_number, o.status, o.created_at, o.updated_at, 
              o.phone, o.address, o.total, o.tracking_number, o.shipping_company_id,
              CASE 
                WHEN o.first_name IS NOT NULL THEN CONCAT(o.first_name, ' ', COALESCE(o.last_name, ''))
                WHEN o.customer_name IS NOT NULL THEN o.customer_name
                ELSE 'غير محدد'
              END as customer_name,
              sc.name as shipping_company_name
              FROM orders o
              LEFT JOIN shipping_companies sc ON o.shipping_company_id = sc.id
              WHERE o.status IN ('shipped', 'processing', 'pending')
              ORDER BY o.created_at DESC";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // إذا فشل، جرب استعلام أبسط
    try {
        $query = "SELECT * FROM orders 
                  WHERE status IN ('shipped', 'processing', 'pending')
                  ORDER BY created_at DESC";
        $stmt = $db->prepare($query);
        $stmt->execute();
        $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // إضافة اسم العميل يدوياً
        foreach ($orders as &$order) {
            if (!isset($order['customer_name'])) {
                $order['customer_name'] = 'غير محدد';
            }
            $order['shipping_company_name'] = null;
        }
    } catch (Exception $e2) {
        die("خطأ في جلب الطلبات: " . $e2->getMessage() . "<br>الخطأ الأصلي: " . $e->getMessage());
    }
}

// حالات الطلبات
$statuses = [
    'pending' => ['label' => 'في الانتظار', 'color' => 'yellow', 'icon' => 'clock'],
    'processing' => ['label' => 'قيد المعالجة', 'color' => 'blue', 'icon' => 'spinner'],
    'shipped' => ['label' => 'تم الشحن', 'color' => 'indigo', 'icon' => 'truck'],
    'out_for_delivery' => ['label' => 'في الطريق للتسليم', 'color' => 'purple', 'icon' => 'shipping-fast'],
    'delivered' => ['label' => 'تم التسليم', 'color' => 'green', 'icon' => 'check-circle'],
    'returned' => ['label' => 'مرتجع', 'color' => 'orange', 'icon' => 'undo'],
    'cancelled' => ['label' => 'ملغي', 'color' => 'red', 'icon' => 'times-circle']
];
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تحديث حالة الشحنات - Roz Skin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { font-family: 'Tajawal', sans-serif; }
        .barcode-highlight {
            animation: highlight 0.5s ease-in-out;
        }
        @keyframes highlight {
            0%, 100% { background-color: transparent; }
            50% { background-color: #fef3c7; }
        }
        .selected-row {
            background-color: #dbeafe !important;
            border-right: 4px solid #3b82f6;
        }
        .barcode-scanner-panel {
            position: fixed;
            bottom: 20px;
            left: 20px;
            background: white;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            padding: 24px;
            z-index: 50;
            min-width: 350px;
        }
        .status-badge {
            transition: all 0.3s ease;
        }
        .status-badge:hover {
            transform: scale(1.05);
        }
    </style>
</head>
<body class="bg-gradient-to-br from-gray-50 to-gray-100 min-h-screen">
    <div class="min-h-screen p-4 md:p-8">
        <!-- Header -->
        <div class="max-w-7xl mx-auto mb-8">
            <div class="bg-white rounded-2xl shadow-lg p-6 border border-gray-100">
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-4">
                        <a href="index.php" class="w-12 h-12 flex items-center justify-center rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-700 transition-all">
                            <i class="fas fa-arrow-right text-xl"></i>
                        </a>
                        <div>
                            <h1 class="text-3xl font-black text-gray-900">تحديث حالة الشحنات</h1>
                            <p class="text-sm text-gray-500 mt-1">امسح الباركود أو ابحث لتحديث حالة الطلبات</p>
                        </div>
                    </div>
                    <div class="flex items-center gap-3">
                        <button onclick="toggleBarcodePanel()" class="bg-gradient-to-r from-purple-600 to-purple-700 text-white px-6 py-3 rounded-xl hover:from-purple-700 hover:to-purple-800 transition-all font-bold shadow-lg flex items-center gap-2">
                            <i class="fas fa-barcode text-xl"></i>
                            <span>ماسح الباركود</span>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <?php if ($message): ?>
            <div class="max-w-7xl mx-auto mb-6">
                <div class="<?php echo $messageType === 'success' ? 'bg-green-50 border-green-500' : 'bg-red-50 border-red-500'; ?> border-r-4 p-5 rounded-xl shadow-sm">
                    <div class="flex items-center gap-3">
                        <i class="fas fa-<?php echo $messageType === 'success' ? 'check-circle text-green-500' : 'exclamation-circle text-red-500'; ?> text-xl"></i>
                        <p class="<?php echo $messageType === 'success' ? 'text-green-700' : 'text-red-700'; ?> font-medium"><?php echo $message; ?></p>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <form method="POST" id="statusUpdateForm" class="max-w-7xl mx-auto">
            <!-- لوحة التحكم السريع -->
            <div class="bg-white rounded-2xl shadow-lg border border-gray-100 p-6 mb-6">
                <div class="flex items-center gap-3 mb-6">
                    <div class="w-12 h-12 rounded-xl bg-gradient-to-br from-blue-500 to-blue-600 flex items-center justify-center">
                        <i class="fas fa-tasks text-white text-xl"></i>
                    </div>
                    <div class="flex-1">
                        <h2 class="text-2xl font-black text-gray-900">التحكم السريع</h2>
                        <p class="text-sm text-gray-500">حدد الحالة الجديدة للطلبات المحددة</p>
                    </div>
                    <div class="bg-gradient-to-r from-green-500 to-green-600 text-white px-6 py-3 rounded-xl font-bold shadow-lg">
                        <i class="fas fa-check-circle ml-2"></i>
                        المحدد: <span id="selectedCount">0</span>
                    </div>
                </div>

                <!-- الفحص الجماعي -->
                <div class="mb-6 bg-gradient-to-r from-purple-50 to-purple-100 rounded-xl p-4 border-2 border-purple-200">
                    <div class="flex items-center gap-3 mb-3">
                        <i class="fas fa-list-ol text-purple-600 text-xl"></i>
                        <h3 class="font-black text-gray-900">الفحص الجماعي للشحنات</h3>
                    </div>
                    <div class="flex gap-3">
                        <div class="flex-1">
                            <textarea id="bulkCheckInput" rows="3" 
                                      placeholder="أدخل أرقام الطلبات، أرقام الهواتف، أو أسماء العملاء (كل واحد في سطر أو افصل بفاصلة)&#10;مثال: 123, 01012345678, أحمد&#10;أو امسح عدة باركودات بسرعة"
                                      class="w-full px-4 py-3 border-2 border-purple-200 rounded-xl focus:border-purple-500 focus:ring-2 focus:ring-purple-200 transition-all outline-none resize-none"></textarea>
                        </div>
                        <button type="button" onclick="bulkCheck()" 
                                class="bg-gradient-to-r from-purple-600 to-purple-700 hover:from-purple-700 hover:to-purple-800 text-white px-6 py-3 rounded-xl font-bold shadow-lg transition-all flex items-center gap-2">
                            <i class="fas fa-check-double"></i>
                            <span>فحص وتحديد</span>
                        </button>
                    </div>
                    <p class="text-xs text-purple-700 mt-2">
                        <i class="fas fa-info-circle ml-1"></i>
                        يمكنك إدخال: أرقام طلبات، أرقام هواتف، أسماء عملاء، أو باركودات - وسيتم البحث عنها وتحديدها تلقائياً
                    </p>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <!-- البحث -->
                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-2">
                            <i class="fas fa-search text-blue-500 ml-1"></i>
                            البحث السريع
                        </label>
                        <input type="text" id="searchInput" placeholder="رقم الطلب، العميل، الهاتف..." 
                               class="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all outline-none">
                    </div>
                    
                    <!-- الحالة الجديدة -->
                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-2">
                            <i class="fas fa-exchange-alt text-green-500 ml-1"></i>
                            الحالة الجديدة
                        </label>
                        <select name="new_status" id="newStatus" required
                                class="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-green-500 focus:ring-2 focus:ring-green-200 transition-all outline-none font-bold">
                            <option value="">اختر الحالة</option>
                            <?php foreach ($statuses as $key => $status): ?>
                                <option value="<?php echo $key; ?>"><?php echo $status['label']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <!-- ملاحظات -->
                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-2">
                            <i class="fas fa-sticky-note text-yellow-500 ml-1"></i>
                            ملاحظات (اختياري)
                        </label>
                        <input type="text" name="status_notes" placeholder="ملاحظة على التحديث..." 
                               class="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-yellow-500 focus:ring-2 focus:ring-yellow-200 transition-all outline-none">
                    </div>
                </div>
                
                <div class="flex gap-3 mt-6">
                    <button type="submit" name="update_status" id="updateBtn" disabled
                            class="flex-1 bg-gradient-to-r from-green-600 to-green-700 hover:from-green-700 hover:to-green-800 text-white px-6 py-4 rounded-xl font-black text-lg shadow-xl transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2">
                        <i class="fas fa-check-double text-xl"></i>
                        <span>تحديث الحالة</span>
                    </button>
                    <button type="button" onclick="clearSelection()" 
                            class="bg-gray-200 text-gray-700 px-6 py-4 rounded-xl font-bold hover:bg-gray-300 transition-all">
                        <i class="fas fa-times ml-2"></i>
                        مسح التحديد
                    </button>
                </div>
            </div>

            <!-- جدول الطلبات -->
            <div class="bg-white rounded-2xl shadow-lg border border-gray-100 p-6">
                <div class="flex items-center justify-between mb-6">
                    <div class="flex items-center gap-3">
                        <div class="w-12 h-12 rounded-xl bg-gradient-to-br from-indigo-500 to-indigo-600 flex items-center justify-center">
                            <i class="fas fa-box text-white text-xl"></i>
                        </div>
                        <div>
                            <h2 class="text-2xl font-black text-gray-900">الطلبات المشحونة</h2>
                            <p class="text-sm text-gray-500">إجمالي: <?php echo count($orders); ?> طلب</p>
                        </div>
                    </div>
                    <div class="flex gap-2">
                        <button type="button" onclick="selectAll()" class="px-4 py-2 bg-blue-50 text-blue-600 rounded-xl hover:bg-blue-100 transition-all font-bold text-sm">
                            <i class="fas fa-check-double ml-1"></i> تحديد الكل
                        </button>
                        <button type="button" onclick="deselectAll()" class="px-4 py-2 bg-gray-50 text-gray-600 rounded-xl hover:bg-gray-100 transition-all font-bold text-sm">
                            <i class="fas fa-times ml-1"></i> إلغاء
                        </button>
                    </div>
                </div>

                <?php if (empty($orders)): ?>
                    <div class="text-center py-16">
                        <div class="w-24 h-24 mx-auto mb-6 rounded-full bg-gray-100 flex items-center justify-center">
                            <i class="fas fa-inbox text-5xl text-gray-400"></i>
                        </div>
                        <h3 class="text-xl font-bold text-gray-700 mb-2">لا توجد طلبات</h3>
                        <p class="text-gray-500">لا توجد طلبات مشحونة حالياً</p>
                    </div>
                <?php else: ?>
                    <div class="overflow-x-auto rounded-xl border border-gray-200">
                        <table class="w-full">
                            <thead class="bg-gradient-to-r from-gray-50 to-gray-100">
                                <tr>
                                    <th class="px-6 py-4 text-right">
                                        <input type="checkbox" id="selectAllCheckbox" onchange="toggleAll(this)" 
                                               class="w-5 h-5 rounded border-gray-300 text-blue-600 focus:ring-2 focus:ring-blue-500">
                                    </th>
                                    <th class="px-6 py-4 text-right text-sm font-black text-gray-700">رقم الطلب</th>
                                    <th class="px-6 py-4 text-right text-sm font-black text-gray-700">العميل</th>
                                    <th class="px-6 py-4 text-right text-sm font-black text-gray-700">الهاتف</th>
                                    <th class="px-6 py-4 text-right text-sm font-black text-gray-700">شركة الشحن</th>
                                    <th class="px-6 py-4 text-right text-sm font-black text-gray-700">رقم التتبع</th>
                                    <th class="px-6 py-4 text-right text-sm font-black text-gray-700">الحالة الحالية</th>
                                    <th class="px-6 py-4 text-right text-sm font-black text-gray-700">التاريخ</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-100">
                                <?php foreach ($orders as $order): 
                                    $status = $statuses[$order['status']] ?? ['label' => $order['status'], 'color' => 'gray', 'icon' => 'question'];
                                ?>
                                    <tr class="hover:bg-blue-50 transition-colors order-row" 
                                        data-order-id="<?php echo $order['id']; ?>"
                                        data-order-number="<?php echo $order['order_number'] ?? $order['id']; ?>"
                                        data-order-barcode="ORD<?php echo str_pad($order['id'], 6, '0', STR_PAD_LEFT); ?>"
                                        data-customer-name="<?php echo htmlspecialchars($order['customer_name'] ?? 'غير محدد'); ?>"
                                        data-phone="<?php echo htmlspecialchars($order['phone'] ?? ''); ?>">
                                        <td class="px-6 py-4">
                                            <input type="checkbox" name="order_ids[]" value="<?php echo $order['id']; ?>"
                                                   class="order-checkbox w-5 h-5 rounded border-gray-300 text-blue-600 focus:ring-2 focus:ring-blue-500"
                                                   onchange="updateCount()">
                                        </td>
                                        <td class="px-6 py-4">
                                            <span class="font-black text-blue-600 text-lg">#<?php echo $order['order_number'] ?? $order['id']; ?></span>
                                        </td>
                                        <td class="px-6 py-4">
                                            <div class="flex items-center gap-2">
                                                <div class="w-10 h-10 rounded-full bg-gradient-to-br from-purple-400 to-purple-600 flex items-center justify-center text-white font-bold">
                                                    <?php echo mb_substr($order['customer_name'] ?? 'غ', 0, 1); ?>
                                                </div>
                                                <span class="font-bold text-gray-900"><?php echo htmlspecialchars($order['customer_name'] ?? 'غير محدد'); ?></span>
                                            </div>
                                        </td>
                                        <td class="px-6 py-4">
                                            <?php if (!empty($order['phone'])): ?>
                                                <a href="https://wa.me/2<?php echo ltrim($order['phone'], '0'); ?>" target="_blank" 
                                                   class="text-green-600 hover:text-green-700 font-medium flex items-center gap-1">
                                                    <i class="fab fa-whatsapp"></i>
                                                    <span dir="ltr"><?php echo htmlspecialchars($order['phone']); ?></span>
                                                </a>
                                            <?php else: ?>
                                                <span class="text-gray-400">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="px-6 py-4">
                                            <span class="text-sm text-gray-700 font-medium">
                                                <?php echo !empty($order['shipping_company_name']) ? htmlspecialchars($order['shipping_company_name']) : '-'; ?>
                                            </span>
                                        </td>
                                        <td class="px-6 py-4">
                                            <span class="text-sm text-gray-600 font-mono">
                                                <?php echo !empty($order['tracking_number']) ? htmlspecialchars($order['tracking_number']) : '-'; ?>
                                            </span>
                                        </td>
                                        <td class="px-6 py-4">
                                            <span class="status-badge inline-flex items-center gap-2 px-4 py-2 rounded-full text-sm font-bold bg-<?php echo $status['color']; ?>-100 text-<?php echo $status['color']; ?>-800">
                                                <i class="fas fa-<?php echo $status['icon']; ?>"></i>
                                                <?php echo $status['label']; ?>
                                            </span>
                                        </td>
                                        <td class="px-6 py-4 text-sm text-gray-500">
                                            <?php echo date('Y-m-d', strtotime($order['created_at'])); ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </form>
    </div>

    <!-- Barcode Scanner Panel -->
    <div id="barcodeScannerPanel" class="barcode-scanner-panel hidden">
        <div class="flex items-center justify-between mb-4">
            <h3 class="font-black text-gray-900 flex items-center gap-2 text-xl">
                <i class="fas fa-barcode text-purple-600"></i>
                ماسح الباركود
            </h3>
            <button onclick="toggleBarcodePanel()" class="text-gray-400 hover:text-gray-600 transition-colors">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        
        <div class="space-y-4">
            <div class="flex items-center justify-between text-sm">
                <span class="text-gray-700 font-medium">الصوت:</span>
                <label class="relative inline-flex items-center cursor-pointer">
                    <input type="checkbox" id="soundToggle" checked class="sr-only peer">
                    <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-purple-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
                </label>
            </div>
            
            <div class="flex items-center justify-between text-sm">
                <span class="text-gray-700 font-medium">التحديد التلقائي:</span>
                <label class="relative inline-flex items-center cursor-pointer">
                    <input type="checkbox" id="autoSelectToggle" checked class="sr-only peer">
                    <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-purple-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
                </label>
            </div>
            
            <div class="pt-4 border-t border-gray-200">
                <div class="text-sm text-gray-600 mb-2 font-medium">الطلبات الممسوحة:</div>
                <div class="bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl p-4 text-center">
                    <span id="scannedCount" class="text-4xl font-black text-purple-600">0</span>
                    <span class="text-sm text-gray-600 mr-2">طلب</span>
                </div>
            </div>
            
            <div class="bg-blue-50 rounded-xl p-4 text-xs text-blue-700">
                <i class="fas fa-info-circle ml-1"></i>
                <span>امسح الباركود على الطلبات لتحديدها تلقائياً ثم اختر الحالة الجديدة</span>
            </div>
        </div>
    </div>

    <script src="../assets/js/barcode-scanner.js"></script>
    <script>
        let barcodeScanner;
        
        document.addEventListener('DOMContentLoaded', function() {
            // تهيئة ماسح الباركود
            barcodeScanner = new BarcodeScanner({
                onScan: function(barcode) {
                    console.log('Scanning:', barcode);
                    
                    let orderId = barcode;
                    let orderNumber = barcode;
                    
                    if (barcode.startsWith('ORD')) {
                        orderId = parseInt(barcode.substring(3));
                    }
                    
                    let row = document.querySelector(`tr[data-order-id="${orderId}"]`);
                    
                    if (!row) {
                        row = document.querySelector(`tr[data-order-number="${barcode}"]`);
                    }
                    
                    if (row) {
                        row.classList.add('barcode-highlight');
                        setTimeout(() => row.classList.remove('barcode-highlight'), 1000);
                        
                        row.classList.add('selected-row');
                        const checkbox = row.querySelector('.order-checkbox');
                        if (checkbox && !checkbox.checked) {
                            checkbox.checked = true;
                            updateCount();
                        }
                        
                        row.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        updateScannedCount();
                        
                        return true;
                    }
                    
                    return false;
                },
                playSound: true,
                autoSelect: true
            });

            // ربط التبديلات
            document.getElementById('soundToggle').addEventListener('change', function(e) {
                barcodeScanner.toggleSound(e.target.checked);
            });
            
            document.getElementById('autoSelectToggle').addEventListener('change', function(e) {
                barcodeScanner.toggleAutoSelect(e.target.checked);
            });
            
            // البحث اليدوي
            let searchTimeout;
            document.getElementById('searchInput').addEventListener('input', function(e) {
                const searchTerm = e.target.value.toLowerCase().trim();
                
                console.log('البحث عن:', searchTerm);
                
                if (searchTerm === '') {
                    document.querySelectorAll('.order-row').forEach(row => {
                        row.style.display = '';
                    });
                    return;
                }
                
                let foundRows = [];
                
                document.querySelectorAll('.order-row').forEach(row => {
                    const orderId = row.getAttribute('data-order-id') || '';
                    const orderNumber = row.getAttribute('data-order-number') || '';
                    const orderBarcode = (row.getAttribute('data-order-barcode') || '').toLowerCase();
                    const customerName = (row.getAttribute('data-customer-name') || '').toLowerCase();
                    const phone = row.getAttribute('data-phone') || '';
                    const rowText = row.textContent.toLowerCase();
                    
                    // البحث في كل الحقول
                    const matches = orderId.includes(searchTerm) || 
                                  orderNumber.toLowerCase().includes(searchTerm) ||
                                  orderBarcode.includes(searchTerm) ||
                                  customerName.includes(searchTerm) ||
                                  phone.includes(searchTerm) ||
                                  rowText.includes(searchTerm);
                    
                    if (matches) {
                        row.style.display = '';
                        foundRows.push(row);
                        console.log('تم العثور على:', orderNumber);
                    } else {
                        row.style.display = 'none';
                    }
                });
                
                console.log('عدد النتائج:', foundRows.length);
                
                // تحديد تلقائي إذا كانت نتيجة واحدة
                if (foundRows.length === 1) {
                    clearTimeout(searchTimeout);
                    searchTimeout = setTimeout(() => {
                        const row = foundRows[0];
                        const checkbox = row.querySelector('.order-checkbox');
                        
                        if (checkbox && !checkbox.checked) {
                            row.classList.add('barcode-highlight');
                            setTimeout(() => row.classList.remove('barcode-highlight'), 1000);
                            
                            row.classList.add('selected-row');
                            checkbox.checked = true;
                            
                            if (barcodeScanner) {
                                barcodeScanner.playSuccessSound();
                            }
                            
                            row.scrollIntoView({ behavior: 'smooth', block: 'center' });
                            updateCount();
                        }
                    }, 500);
                }
            });
        });
        
        function toggleBarcodePanel() {
            const panel = document.getElementById('barcodeScannerPanel');
            panel.classList.toggle('hidden');
        }
        
        function updateScannedCount() {
            const count = document.querySelectorAll('.order-checkbox:checked').length;
            document.getElementById('scannedCount').textContent = count;
        }
        
        function updateCount() {
            const count = document.querySelectorAll('.order-checkbox:checked').length;
            document.getElementById('selectedCount').textContent = count;
            document.getElementById('updateBtn').disabled = count === 0;
            updateScannedCount();
        }

        function toggleAll(checkbox) {
            document.querySelectorAll('.order-checkbox').forEach(cb => {
                if (cb.closest('tr').style.display !== 'none') {
                    cb.checked = checkbox.checked;
                    const row = cb.closest('tr');
                    if (cb.checked) {
                        row.classList.add('selected-row');
                    } else {
                        row.classList.remove('selected-row');
                    }
                }
            });
            updateCount();
        }

        function selectAll() {
            document.querySelectorAll('.order-checkbox').forEach(cb => {
                if (cb.closest('tr').style.display !== 'none') {
                    cb.checked = true;
                    cb.closest('tr').classList.add('selected-row');
                }
            });
            document.getElementById('selectAllCheckbox').checked = true;
            updateCount();
        }

        function deselectAll() {
            document.querySelectorAll('.order-checkbox').forEach(cb => {
                cb.checked = false;
                cb.closest('tr').classList.remove('selected-row');
            });
            document.getElementById('selectAllCheckbox').checked = false;
            updateCount();
        }
        
        function clearSelection() {
            deselectAll();
        }
        
        // الفحص الجماعي
        function bulkCheck() {
            const input = document.getElementById('bulkCheckInput').value.trim();
            
            if (!input) {
                alert('الرجاء إدخال أرقام الطلبات');
                return;
            }
            
            // تقسيم النص إلى أرقام (بالفاصلة أو سطر جديد أو مسافة)
            const orderNumbers = input
                .split(/[\n,\s]+/)
                .map(num => num.trim())
                .filter(num => num.length > 0);
            
            console.log('البحث عن الطلبات:', orderNumbers);
            
            let foundCount = 0;
            let notFoundCount = 0;
            const notFound = [];
            
            // البحث عن كل رقم
            orderNumbers.forEach(orderNum => {
                let row = null;
                
                // 1. البحث برقم الطلب (ID)
                row = document.querySelector(`tr[data-order-id="${orderNum}"]`);
                
                // 2. البحث برقم الطلب (order_number)
                if (!row) {
                    row = document.querySelector(`tr[data-order-number="${orderNum}"]`);
                }
                
                // 3. البحث بالباركود
                if (!row) {
                    const barcode = orderNum.startsWith('ORD') ? orderNum : `ORD${orderNum.padStart(6, '0')}`;
                    row = document.querySelector(`tr[data-order-barcode="${barcode}"]`);
                }
                
                // 4. البحث برقم الهاتف
                if (!row) {
                    // تنظيف رقم الهاتف (إزالة المسافات والرموز)
                    const cleanPhone = orderNum.replace(/[\s\-\(\)]/g, '');
                    
                    // البحث في كل الصفوف
                    document.querySelectorAll('.order-row').forEach(r => {
                        if (!row) {
                            const phone = r.getAttribute('data-phone') || '';
                            const cleanRowPhone = phone.replace(/[\s\-\(\)]/g, '');
                            
                            // مقارنة الأرقام (مع أو بدون 0 في البداية)
                            if (cleanRowPhone === cleanPhone || 
                                cleanRowPhone === '0' + cleanPhone ||
                                '0' + cleanRowPhone === cleanPhone ||
                                cleanRowPhone.endsWith(cleanPhone) ||
                                cleanPhone.endsWith(cleanRowPhone)) {
                                row = r;
                            }
                        }
                    });
                }
                
                // 5. البحث باسم العميل (إذا كان نص وليس رقم)
                if (!row && isNaN(orderNum)) {
                    document.querySelectorAll('.order-row').forEach(r => {
                        if (!row) {
                            const customerName = (r.getAttribute('data-customer-name') || '').toLowerCase();
                            if (customerName.includes(orderNum.toLowerCase())) {
                                row = r;
                            }
                        }
                    });
                }
                
                if (row && row.style.display !== 'none') {
                    // تم العثور على الطلب
                    const checkbox = row.querySelector('.order-checkbox');
                    if (checkbox && !checkbox.checked) {
                        checkbox.checked = true;
                        row.classList.add('selected-row');
                        
                        // تمييز مؤقت
                        row.classList.add('barcode-highlight');
                        setTimeout(() => row.classList.remove('barcode-highlight'), 1000);
                    }
                    foundCount++;
                } else {
                    notFoundCount++;
                    notFound.push(orderNum);
                }
            });
            
            // تحديث العداد
            updateCount();
            
            // صوت النجاح
            if (foundCount > 0 && barcodeScanner) {
                barcodeScanner.playSuccessSound();
            }
            
            // عرض النتيجة
            let message = `✅ تم العثور على ${foundCount} طلب`;
            if (notFoundCount > 0) {
                message += `\n⚠️ لم يتم العثور على ${notFoundCount} طلب`;
                if (notFound.length <= 10) {
                    message += `:\n${notFound.join(', ')}`;
                }
            }
            
            alert(message);
            
            // مسح الحقل
            document.getElementById('bulkCheckInput').value = '';
        }
        
        // اختصار لوحة المفاتيح للفحص الجماعي (Ctrl+Enter)
        document.getElementById('bulkCheckInput').addEventListener('keydown', function(e) {
            if (e.ctrlKey && e.key === 'Enter') {
                e.preventDefault();
                bulkCheck();
            }
        });
        
        // تأكيد قبل الإرسال
        document.getElementById('statusUpdateForm').addEventListener('submit', function(e) {
            const count = document.querySelectorAll('.order-checkbox:checked').length;
            const status = document.getElementById('newStatus').value;
            const statusText = document.getElementById('newStatus').selectedOptions[0].text;
            
            if (!confirm(`هل أنت متأكد من تحديث حالة ${count} طلب إلى "${statusText}"؟`)) {
                e.preventDefault();
            }
        });
    </script>
</body>
</html>
