<?php
require_once '../../config/database.php';
require_once '../../models/order.php';

session_start();

$database = new Database();
$db = $database->getConnection();
$order_model = new Order($db);

$all_orders = $order_model->getAllOrders();
$status_ar = [
    'pending' => 'في الانتظار',
    'processing' => 'قيد المعالجة',
    'shipped' => 'تم الشحن',
    'delivered' => 'تم التسليم',
    'cancelled' => 'ملغي'
];

// Get shipping companies
$query = "SELECT * FROM shipping_companies WHERE is_active = 1 ORDER BY name";
$stmt = $db->prepare($query);
$stmt->execute();
$shipping_companies = $stmt->fetchAll(PDO::FETCH_ASSOC);

$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['update_order_status'])) {
        $order_id = $_POST['order_id'];
        $status = $_POST['status'];
        if ($order_model->updateOrderStatus($order_id, $status)) {
            $message = 'تم تحديث حالة الطلب بنجاح!';
            $all_orders = $order_model->getAllOrders();
        } else {
            $message = 'حدث خطأ أثناء تحديث حالة الطلب';
        }
    } elseif (isset($_POST['assign_shipping'])) {
        $order_id = $_POST['order_id'];
        $company_id = $_POST['shipping_company_id'];
        $tracking = $_POST['tracking_number'] ?? '';
        
        $query = "UPDATE orders SET shipping_company_id = ?, tracking_number = ?, status = 'shipped', shipped_at = NOW() WHERE id = ?";
        $stmt = $db->prepare($query);
        if ($stmt->execute([$company_id, $tracking, $order_id])) {
            $message = 'تم تسليم الطلب لشركة الشحن بنجاح!';
            $all_orders = $order_model->getAllOrders();
        }
    }
}
?>
<!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&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;
            background-color: #fef3c7 !important;
        }
        @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: 12px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            padding: 16px;
            z-index: 40;
            min-width: 300px;
        }
    </style>
</head>
<body class="bg-gray-50">
    <div class="min-h-screen">
        <!-- Header -->
        <header class="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-20">
            <div class="flex items-center justify-between px-6 py-4">
                <div class="flex items-center space-x-4 space-x-reverse">
                    <a href="../index.php" class="text-gray-600 hover:text-gray-900">
                        <i class="fas fa-arrow-right"></i>
                    </a>
                    <h1 class="text-2xl font-bold text-gray-900">إدارة الطلبات</h1>
                </div>
                <div class="flex items-center gap-3">
                    <!-- Barcode Scanner Toggle -->
                    <button onclick="toggleBarcodePanel()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 flex items-center gap-2">
                        <i class="fas fa-barcode"></i>
                        <span>ماسح الباركود</span>
                    </button>
                    <!-- Search Input -->
                    <div class="relative">
                        <input type="text" id="searchInput" placeholder="بحث برقم الطلب أو اسم العميل..." 
                               class="border border-gray-300 rounded-lg px-4 py-2 pr-10 w-64 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <i class="fas fa-search absolute right-3 top-3 text-gray-400"></i>
                    </div>
                </div>
            </div>
        </header>

        <div class="p-6">
            <?php if ($message): ?>
                <div class="bg-green-50 border-r-4 border-green-400 p-4 mb-6">
                    <p class="text-sm text-green-700"><?php echo $message; ?></p>
                </div>
            <?php endif; ?>

            <!-- Statistics Cards -->
            <?php
                $stats = [
                    'total' => count($all_orders),
                    'pending' => count(array_filter($all_orders, fn($o) => $o['status'] === 'pending')),
                    'processing' => count(array_filter($all_orders, fn($o) => $o['status'] === 'processing')),
                    'delivered' => count(array_filter($all_orders, fn($o) => $o['status'] === 'delivered')),
                    'total_revenue' => array_sum(array_column($all_orders, 'total'))
                ];
            ?>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4 mb-6">
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">إجمالي الطلبات</p>
                            <p class="text-2xl font-bold text-gray-900"><?php echo $stats['total']; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-shopping-cart text-blue-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">في الانتظار</p>
                            <p class="text-2xl font-bold text-yellow-600"><?php echo $stats['pending']; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-yellow-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-clock text-yellow-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">قيد المعالجة</p>
                            <p class="text-2xl font-bold text-blue-600"><?php echo $stats['processing']; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-spinner text-blue-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">تم التسليم</p>
                            <p class="text-2xl font-bold text-green-600"><?php echo $stats['delivered']; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-check-circle text-green-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">إجمالي الإيرادات</p>
                            <p class="text-2xl font-bold text-purple-600">EGP <?php echo number_format($stats['total_revenue'], 0); ?></p>
                        </div>
                        <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-dollar-sign text-purple-600 text-xl"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Orders Table -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                <div class="px-6 py-5 border-b border-gray-200">
                    <h3 class="text-xl font-semibold text-gray-900">جميع الطلبات (<?php echo count($all_orders); ?>)</h3>
                </div>
                <div class="overflow-x-auto">
                    <?php if (!empty($all_orders)): ?>
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">رقم الطلب</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">العميل</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">الهاتف</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">العنوان</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">المبلغ</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">الحالة</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">التاريخ</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">الإجراءات</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                <?php foreach ($all_orders as $order): ?>
                                    <tr class="hover:bg-gray-50" data-order-id="<?php echo $order['id']; ?>" data-order-barcode="ORD<?php echo str_pad($order['id'], 6, '0', STR_PAD_LEFT); ?>">
                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                                            <div class="flex items-center gap-2">
                                                <input type="checkbox" class="order-checkbox rounded border-gray-300" value="<?php echo $order['id']; ?>">
                                                <span>#<?php echo $order['id']; ?></span>
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?php echo htmlspecialchars($order['first_name'] . ' ' . $order['last_name']); ?></td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            <a href="https://wa.me/2<?php echo ltrim($order['phone'], '0'); ?>" target="_blank" class="text-green-600 hover:text-green-700">
                                                <i class="fab fa-whatsapp ml-1"></i><?php echo htmlspecialchars($order['phone']); ?>
                                            </a>
                                        </td>
                                        <td class="px-6 py-4 text-sm text-gray-900 max-w-xs truncate" title="<?php echo htmlspecialchars($order['customer_address']); ?>">
                                            <?php echo htmlspecialchars($order['customer_address']); ?>
                                            <?php if (!empty($order['location_link'])): ?>
                                                <a href="<?php echo htmlspecialchars($order['location_link']); ?>" target="_blank" class="text-blue-600 hover:text-blue-700 mr-2">
                                                    <i class="fas fa-map-marker-alt"></i>
                                                </a>
                                            <?php endif; ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">EGP <?php echo number_format($order['total'], 2); ?></td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <?php
                                                $status_classes = [
                                                    'pending' => 'bg-yellow-100 text-yellow-800',
                                                    'processing' => 'bg-blue-100 text-blue-800',
                                                    'shipped' => 'bg-indigo-100 text-indigo-800',
                                                    'delivered' => 'bg-green-100 text-green-800',
                                                    'cancelled' => 'bg-red-100 text-red-800'
                                                ];
                                                $status_class = $status_classes[$order['status']] ?? 'bg-gray-100 text-gray-800';
                                            ?>
                                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium <?php echo $status_class; ?>">
                                                <?php echo $status_ar[$order['status']] ?? $order['status']; ?>
                                            </span>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo date('Y-m-d', strtotime($order['created_at'])); ?></td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm">
                                            <div class="flex items-center gap-2">
                                                <!-- Print Invoice -->
                                                <button onclick="printInvoice(<?php echo $order['id']; ?>)" class="text-purple-600 hover:text-purple-700" title="طباعة البوليصة">
                                                    <i class="fas fa-print"></i>
                                                </button>
                                                
                                                <!-- Ship Order -->
                                                <?php if ($order['status'] === 'processing'): ?>
                                                    <button onclick="showShippingModal(<?php echo $order['id']; ?>)" class="text-blue-600 hover:text-blue-700" title="تسليم للشحن">
                                                        <i class="fas fa-truck"></i>
                                                    </button>
                                                <?php endif; ?>
                                                
                                                <!-- Status Dropdown -->
                                                <form method="POST" class="inline-block">
                                                    <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
                                                    <select name="status" class="text-sm border-gray-300 rounded-md" onchange="this.form.submit()">
                                                        <?php foreach ($status_ar as $key => $value): ?>
                                                            <option value="<?php echo $key; ?>" <?php echo $order['status'] === $key ? 'selected' : ''; ?>><?php echo $value; ?></option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                    <input type="hidden" name="update_order_status" value="1">
                                                </form>
                                                
                                                <!-- Notes -->
                                                <?php if (!empty($order['notes'])): ?>
                                                    <button onclick="showNotes('<?php echo htmlspecialchars(addslashes($order['notes'])); ?>')" class="text-gray-600 hover:text-gray-700" title="عرض الملاحظات">
                                                        <i class="fas fa-sticky-note"></i>
                                                    </button>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php else: ?>
                        <div class="p-8 text-center text-gray-500">
                            <i class="fas fa-inbox text-4xl mb-4"></i>
                            <p>لا توجد طلبات حالياً</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Notes Modal -->
    <div id="notesModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center">
        <div class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4">
            <div class="flex items-center justify-between p-4 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-900">ملاحظات الطلب</h3>
                <button onclick="closeNotesModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="p-4">
                <p id="notesContent" class="text-gray-700"></p>
            </div>
            <div class="flex justify-end p-4 border-t border-gray-200">
                <button onclick="closeNotesModal()" class="bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300">
                    إغلاق
                </button>
            </div>
        </div>
    </div>

    <!-- Shipping Modal -->
    <div id="shippingModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center">
        <div class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4">
            <div class="flex items-center justify-between p-4 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-900">تسليم للشحن</h3>
                <button onclick="closeShippingModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <form method="POST" class="p-4 space-y-4">
                <input type="hidden" name="order_id" id="shipping_order_id">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">شركة الشحن</label>
                    <select name="shipping_company_id" required class="w-full border border-gray-300 rounded-lg px-3 py-2">
                        <option value="">اختر شركة الشحن</option>
                        <?php foreach ($shipping_companies as $company): ?>
                            <option value="<?php echo $company['id']; ?>"><?php echo htmlspecialchars($company['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">رقم التتبع (اختياري)</label>
                    <input type="text" name="tracking_number" class="w-full border border-gray-300 rounded-lg px-3 py-2" placeholder="TRK123456">
                </div>
                <div class="flex gap-2 pt-2">
                    <button type="submit" name="assign_shipping" class="flex-1 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                        <i class="fas fa-truck ml-1"></i>تسليم
                    </button>
                    <button type="button" onclick="closeShippingModal()" class="flex-1 bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300">
                        إلغاء
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Barcode Scanner Panel -->
    <div id="barcodeScannerPanel" class="barcode-scanner-panel hidden">
        <div class="flex items-center justify-between mb-3">
            <h3 class="font-bold text-gray-900 flex items-center gap-2">
                <i class="fas fa-barcode text-blue-600"></i>
                ماسح الباركود
            </h3>
            <button onclick="toggleBarcodePanel()" class="text-gray-400 hover:text-gray-600">
                <i class="fas fa-times"></i>
            </button>
        </div>
        
        <div class="space-y-3">
            <div class="flex items-center justify-between text-sm">
                <span class="text-gray-600">الصوت:</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-blue-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-blue-600"></div>
                </label>
            </div>
            
            <div class="flex items-center justify-between text-sm">
                <span class="text-gray-600">التحديد التلقائي:</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-blue-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-blue-600"></div>
                </label>
            </div>
            
            <div class="pt-3 border-t border-gray-200">
                <div class="text-sm text-gray-600 mb-2">العناصر المحددة:</div>
                <div class="bg-blue-50 rounded-lg p-3 text-center">
                    <span id="selectedCount" class="text-2xl font-bold text-blue-600">0</span>
                    <span class="text-sm text-gray-600 mr-1">طلب</span>
                </div>
            </div>
            
            <div class="flex gap-2">
                <button onclick="clearSelection()" class="flex-1 bg-gray-200 text-gray-700 px-3 py-2 rounded-lg hover:bg-gray-300 text-sm">
                    <i class="fas fa-times ml-1"></i>مسح التحديد
                </button>
                <button onclick="processSelected()" class="flex-1 bg-blue-600 text-white px-3 py-2 rounded-lg hover:bg-blue-700 text-sm">
                    <i class="fas fa-check ml-1"></i>معالجة
                </button>
            </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);
                    
                    // البحث عن الطلب بالباركود
                    // يمكن أن يكون الباركود: رقم الطلب مباشرة أو ORD000001
                    let orderId = barcode;
                    if (barcode.startsWith('ORD')) {
                        orderId = parseInt(barcode.substring(3));
                    }
                    
                    // البحث في الجدول
                    const row = document.querySelector(`tr[data-order-id="${orderId}"]`);
                    
                    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 = true;
                        }
                        
                        // التمرير للصف
                        row.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        
                        // تحديث العداد
                        updateSelectedCount();
                        
                        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);
            });
            
            // ربط الشيك بوكسات
            document.querySelectorAll('.order-checkbox').forEach(checkbox => {
                checkbox.addEventListener('change', function() {
                    const row = this.closest('tr');
                    if (this.checked) {
                        row.classList.add('selected-row');
                    } else {
                        row.classList.remove('selected-row');
                    }
                    updateSelectedCount();
                });
            });
            
            // البحث اليدوي
            let searchTimeout;
            document.getElementById('searchInput').addEventListener('input', function(e) {
                const searchTerm = e.target.value.toLowerCase().trim();
                
                // إذا كان البحث فارغ، إظهار كل الصفوف
                if (searchTerm === '') {
                    document.querySelectorAll('tbody tr').forEach(row => {
                        row.style.display = '';
                    });
                    return;
                }
                
                let foundRows = [];
                
                document.querySelectorAll('tbody tr').forEach(row => {
                    const text = row.textContent.toLowerCase();
                    const orderId = row.getAttribute('data-order-id');
                    const orderBarcode = row.getAttribute('data-order-barcode').toLowerCase();
                    
                    // البحث في النص أو رقم الطلب أو الباركود
                    const matches = text.includes(searchTerm) || 
                                  orderId === searchTerm || 
                                  orderBarcode.includes(searchTerm);
                    
                    if (matches) {
                        row.style.display = '';
                        foundRows.push(row);
                    } else {
                        row.style.display = 'none';
                    }
                });
                
                // إذا تم العثور على نتيجة واحدة فقط، تحديدها تلقائياً
                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' });
                            
                            // تحديث العداد
                            updateSelectedCount();
                        }
                    }, 500); // انتظار نصف ثانية للتأكد من انتهاء الكتابة
                }
            });
        });
        
        function toggleBarcodePanel() {
            const panel = document.getElementById('barcodeScannerPanel');
            panel.classList.toggle('hidden');
        }
        
        function updateSelectedCount() {
            const count = document.querySelectorAll('.order-checkbox:checked').length;
            document.getElementById('selectedCount').textContent = count;
        }
        
        function clearSelection() {
            document.querySelectorAll('.order-checkbox:checked').forEach(checkbox => {
                checkbox.checked = false;
                checkbox.closest('tr').classList.remove('selected-row');
            });
            barcodeScanner.clearSelection();
            updateSelectedCount();
        }
        
        function processSelected() {
            const selectedIds = Array.from(document.querySelectorAll('.order-checkbox:checked'))
                .map(cb => cb.value);
            
            if (selectedIds.length === 0) {
                alert('الرجاء تحديد طلبات أولاً');
                return;
            }
            
            // يمكنك هنا إضافة المعالجة المطلوبة
            // مثل: إنشاء مانيفست، طباعة، تغيير الحالة، إلخ
            if (confirm(`هل تريد معالجة ${selectedIds.length} طلب؟`)) {
                // إضافة الكود هنا
                console.log('Processing orders:', selectedIds);
                
                // مثال: إعادة توجيه لصفحة إنشاء مانيفست
                window.location.href = '../shipping/create-manifest.php?orders=' + selectedIds.join(',');
            }
        }
        
        function showNotes(notes) {
            document.getElementById('notesContent').textContent = notes;
            document.getElementById('notesModal').classList.remove('hidden');
        }

        function closeNotesModal() {
            document.getElementById('notesModal').classList.add('hidden');
        }

        function showShippingModal(orderId) {
            document.getElementById('shipping_order_id').value = orderId;
            document.getElementById('shippingModal').classList.remove('hidden');
        }

        function closeShippingModal() {
            document.getElementById('shippingModal').classList.add('hidden');
        }

        function printInvoice(orderId) {
            window.open('print_invoice.php?id=' + orderId, '_blank');
        }
    </script>
</body>
</html>
