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

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

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

// إنشاء جداول Manifests إذا لم تكن موجودة
$db->exec("CREATE TABLE IF NOT EXISTS shipping_manifests (
    id INT AUTO_INCREMENT PRIMARY KEY,
    manifest_number VARCHAR(50) UNIQUE NOT NULL,
    shipping_company_id INT,
    delegate_name VARCHAR(255),
    total_orders INT DEFAULT 0,
    total_amount DECIMAL(10, 2) DEFAULT 0,
    shipping_cost DECIMAL(10, 2) DEFAULT 0,
    net_amount DECIMAL(10, 2) DEFAULT 0,
    notes TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    created_by INT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$db->exec("CREATE TABLE IF NOT EXISTS manifest_orders (
    id INT AUTO_INCREMENT PRIMARY KEY,
    manifest_id INT NOT NULL,
    order_id INT NOT NULL,
    FOREIGN KEY (manifest_id) REFERENCES shipping_manifests(id) ON DELETE CASCADE,
    FOREIGN KEY (order_id) REFERENCES orders(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

// جلب الطلبات الجاهزة للشحن
$query = "SELECT o.*, 
          CONCAT(o.first_name, ' ', o.last_name) as customer_name,
          (SELECT COUNT(*) FROM order_items WHERE order_id = o.id) as items_count
          FROM orders o
          WHERE o.status IN ('pending', 'processing')
          ORDER BY o.created_at DESC";
$stmt = $db->prepare($query);
$stmt->execute();
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

// جلب شركات الشحن
$query = "SELECT * FROM shipping_companies WHERE is_active = 1 ORDER BY name";
$stmt = $db->prepare($query);
$stmt->execute();
$companies = $stmt->fetchAll(PDO::FETCH_ASSOC);

$message = '';
$manifest_id = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $selected_orders = $_POST['orders'] ?? [];
        $company_id = !empty($_POST['company_id']) ? $_POST['company_id'] : null;
        $delegate_name = $_POST['delegate_name'] ?? '';
        $notes = $_POST['notes'] ?? '';
        
        if (empty($selected_orders)) {
            $message = 'الرجاء اختيار طلبات على الأقل';
        } else {
            $db->beginTransaction();
            
            // حساب الإجماليات
            $total_amount = 0;
            $total_orders = count($selected_orders);
            
            foreach ($selected_orders as $order_id) {
                $stmt = $db->prepare("SELECT total FROM orders WHERE id = ?");
                $stmt->execute([$order_id]);
                $order = $stmt->fetch(PDO::FETCH_ASSOC);
                $total_amount += $order['total'];
            }
            
            // تكلفة الشحن (افتراضية 30 جنيه للطلب)
            $shipping_cost = $total_orders * 30;
            $net_amount = $total_amount - $shipping_cost;
            
            // رقم المانيفست
            $manifest_number = 'MAN-' . date('Ymd') . '-' . rand(1000, 9999);
            
            // إنشاء المانيفست
            $stmt = $db->prepare("
                INSERT INTO shipping_manifests 
                (manifest_number, shipping_company_id, delegate_name, total_orders, 
                 total_amount, shipping_cost, net_amount, notes, created_by)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $manifest_number, $company_id, $delegate_name, $total_orders,
                $total_amount, $shipping_cost, $net_amount, $notes, $_SESSION['user_id']
            ]);
            
            $manifest_id = $db->lastInsertId();
            
            // إضافة الطلبات للمانيفست
            foreach ($selected_orders as $order_id) {
                $stmt = $db->prepare("INSERT INTO manifest_orders (manifest_id, order_id) VALUES (?, ?)");
                $stmt->execute([$manifest_id, $order_id]);
                
                // تحديث حالة الطلب
                $stmt = $db->prepare("UPDATE orders SET status = 'shipped' WHERE id = ?");
                $stmt->execute([$order_id]);
            }
            
            $db->commit();
            
            // التحويل لصفحة الطباعة
            header("Location: print-manifest.php?id=" . $manifest_id);
            exit;
        }
    } catch (Exception $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        $message = 'خطأ: ' . $e->getMessage();
        error_log("Manifest creation error: " . $e->getMessage());
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إنشاء مانيفست شحن</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">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        'tajawal': ['Tajawal', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <style>
        body { 
            font-family: 'Tajawal', sans-serif;
        }
        .card-hover {
            transition: all 0.3s ease;
        }
        .card-hover:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        }
        .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;
        }
        .barcode-scanner-panel {
            position: fixed;
            bottom: 20px;
            left: 20px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
            padding: 20px;
            z-index: 50;
            min-width: 320px;
        }
    </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="../orders/index.php" 
                           class="w-10 h-10 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"></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="hidden md:flex items-center gap-2 text-sm text-gray-500">
                        <i class="fas fa-calendar-alt"></i>
                        <span><?php echo date('Y/m/d'); ?></span>
                    </div>
                </div>
            </div>
        </div>

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

        <form method="POST" class="max-w-7xl mx-auto">
            <!-- معلومات المانيفست -->
            <div class="bg-white rounded-2xl shadow-lg border border-gray-100 p-6 md:p-8 mb-6 card-hover">
                <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-info-circle text-white text-xl"></i>
                    </div>
                    <div>
                        <h2 class="text-2xl font-black text-gray-900">معلومات المانيفست</h2>
                        <p class="text-sm text-gray-500">أدخل بيانات شركة الشحن والمندوب</p>
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-2">
                            <i class="fas fa-truck text-blue-500 ml-1"></i>
                            شركة الشحن
                        </label>
                        <select name="company_id" 
                                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 font-medium">
                            <option value="">اختر شركة الشحن</option>
                            <?php foreach ($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-bold text-gray-700 mb-2">
                            <i class="fas fa-user text-green-500 ml-1"></i>
                            اسم المندوب
                        </label>
                        <input type="text" name="delegate_name" 
                               class="w-full px-4 py-2 border rounded-lg"
                               placeholder="اسم مندوب الشحن">
                    </div>
                    
                    <div class="md:col-span-2">
                        <label class="block text-sm font-bold mb-2">ملاحظات</label>
                        <textarea name="notes" rows="2" 
                                  class="w-full px-4 py-2 border rounded-lg"
                                  placeholder="ملاحظات إضافية..."></textarea>
                    </div>
                </div>
            </div>

            <!-- الطلبات -->
            <div class="bg-white rounded-2xl shadow-lg border border-gray-100 p-6 md:p-8 card-hover">
                <div class="flex items-center gap-3 mb-6">
                    <div class="w-12 h-12 rounded-xl bg-gradient-to-br from-purple-500 to-purple-600 flex items-center justify-center">
                        <i class="fas fa-box 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="flex items-center gap-3">
                        <!-- Search Input -->
                        <div class="relative">
                            <input type="text" id="searchInput" placeholder="بحث برقم الطلب..." 
                                   class="border-2 border-gray-200 rounded-xl px-4 py-2 pr-10 w-48 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-sm">
                            <i class="fas fa-search absolute right-3 top-3 text-gray-400"></i>
                        </div>
                        <button type="button" onclick="toggleBarcodePanel()" 
                                class="px-4 py-2 bg-purple-50 text-purple-600 rounded-xl hover:bg-purple-100 transition-all font-bold text-sm">
                            <i class="fas fa-barcode ml-1"></i> ماسح الباركود
                        </button>
                        <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 class="px-4 py-2 bg-gradient-to-r from-green-500 to-green-600 text-white rounded-xl font-bold text-sm">
                            <i class="fas fa-check-circle ml-1"></i>
                            المحدد: <span id="selected-count">0</span>
                        </div>
                    </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="select-all" 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>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-100">
                                <?php foreach ($orders as $order): ?>
                                    <tr class="hover:bg-blue-50 transition-colors" 
                                        data-order-id="<?php echo $order['id']; ?>" 
                                        data-order-number="<?php echo $order['order_number']; ?>"
                                        data-order-barcode="ORD<?php echo str_pad($order['id'], 6, '0', STR_PAD_LEFT); ?>">
                                        <td class="px-6 py-4">
                                            <input type="checkbox" name="orders[]" 
                                                   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">#<?php echo $order['order_number']; ?></span>
                                        </td>
                                        <td class="px-6 py-4">
                                            <div class="flex items-center gap-2">
                                                <div class="w-8 h-8 rounded-full bg-gradient-to-br from-purple-400 to-purple-600 flex items-center justify-center text-white font-bold text-sm">
                                                    <?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">
                                            <span class="font-medium text-gray-700" dir="ltr"><?php echo htmlspecialchars($order['phone']); ?></span>
                                        </td>
                                        <td class="px-6 py-4">
                                            <span class="text-sm text-gray-600"><?php echo htmlspecialchars(substr($order['address'], 0, 30)); ?>...</span>
                                        </td>
                                        <td class="px-6 py-4">
                                            <span class="font-black text-green-600 text-lg"><?php echo number_format($order['total'], 0); ?> ج.م</span>
                                        </td>
                                        <td class="px-6 py-4">
                                            <span class="px-3 py-1.5 text-xs font-bold rounded-full bg-gradient-to-r from-yellow-400 to-yellow-500 text-yellow-900">
                                                <?php 
                                                $statuses = [
                                                    'pending' => 'قيد الانتظار',
                                                    'processing' => 'قيد المعالجة'
                                                ];
                                                echo $statuses[$order['status']] ?? $order['status'];
                                                ?>
                                            </span>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Submit Button -->
            <?php if (!empty($orders)): ?>
                <div class="max-w-7xl mx-auto mt-8">
                    <button type="submit" 
                            class="w-full bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white px-8 py-5 rounded-2xl font-black text-xl shadow-xl hover:shadow-2xl transform hover:scale-[1.02] transition-all duration-200 flex items-center justify-center gap-3">
                        <i class="fas fa-file-invoice text-2xl"></i>
                        <span>إنشاء المانيفست وطباعته</span>
                        <i class="fas fa-arrow-left"></i>
                    </button>
                </div>
            <?php endif; ?>
        </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-lg">
                <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-3xl 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-3 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;
                    
                    // إذا كان الباركود بصيغة ORD000001
                    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();
                
                // إذا كان البحث فارغ، إظهار كل الصفوف
                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 orderNumber = row.getAttribute('data-order-number');
                    const orderBarcode = row.getAttribute('data-order-barcode').toLowerCase();
                    
                    // البحث في النص أو رقم الطلب أو الباركود
                    const matches = text.includes(searchTerm) || 
                                  orderId === searchTerm || 
                                  (orderNumber && orderNumber.toLowerCase().includes(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' });
                            
                            // تحديث العداد
                            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 checked = document.querySelectorAll('.order-checkbox:checked').length;
            document.getElementById('selected-count').textContent = checked;
            updateScannedCount();
        }

        function toggleAll(checkbox) {
            document.querySelectorAll('.order-checkbox').forEach(cb => {
                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 => {
                cb.checked = true;
                cb.closest('tr').classList.add('selected-row');
            });
            document.getElementById('select-all').checked = true;
            updateCount();
        }

        function deselectAll() {
            document.querySelectorAll('.order-checkbox').forEach(cb => {
                cb.checked = false;
                cb.closest('tr').classList.remove('selected-row');
            });
            document.getElementById('select-all').checked = false;
            updateCount();
        }
    </script>
</body>
</html>
