<?php
session_start();
include 'layouts/dbconn.php';
date_default_timezone_set('Africa/Nairobi');

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

$user_id = $_SESSION['user_id'];

// Fetch user details
$sql_user_details = "SELECT u.*, ur.role_name FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
}

// Handle bulk operations
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'bulk_update_status':
                $shipment_ids = $_POST['shipment_ids'] ?? [];
                $new_status = $_POST['new_status'];
                $location = $_POST['location'] ?? '';
                $notes = $_POST['notes'] ?? '';
                
                if (empty($shipment_ids)) {
                    $message = "Please select at least one shipment.";
                    $message_type = "warning";
                    break;
                }
                
                $success_count = 0;
                $error_count = 0;
                
                foreach ($shipment_ids as $shipment_id) {
                    // Update shipment status
                    $update_sql = "UPDATE shipments SET status = ?, updated_by = ?, updated_at = CURRENT_TIMESTAMP WHERE shipment_id = ?";
                    $update_stmt = $conn->prepare($update_sql);
                    $update_stmt->bind_param("sii", $new_status, $user_id, $shipment_id);
                    
                    if ($update_stmt->execute()) {
                        // Add tracking event
                        $tracking_sql = "INSERT INTO tracking_events (shipment_id, event_type, event_status, event_description, location, created_by) 
                                        VALUES (?, ?, ?, ?, ?, ?)";
                        $tracking_stmt = $conn->prepare($tracking_sql);
                        $event_description = "Bulk status update: " . $new_status . ($notes ? " - " . $notes : "");
                        $tracking_stmt->bind_param("issssi", $shipment_id, $new_status, $new_status, $event_description, $location, $user_id);
                        $tracking_stmt->execute();
                        
                        $success_count++;
                    } else {
                        $error_count++;
                    }
                }
                
                $message = "Status updated for $success_count shipments.";
                if ($error_count > 0) {
                    $message .= " $error_count errors occurred.";
                }
                $message_type = $error_count > 0 ? "warning" : "success";
                break;
                
            case 'bulk_assign_driver':
                $shipment_ids = $_POST['shipment_ids'] ?? [];
                $driver_id = $_POST['driver_id'];
                
                if (empty($shipment_ids)) {
                    $message = "Please select at least one shipment.";
                    $message_type = "warning";
                    break;
                }
                
                $success_count = 0;
                
                foreach ($shipment_ids as $shipment_id) {
                    // Create delivery attempt record
                    $delivery_sql = "INSERT INTO delivery_attempts (shipment_id, attempt_number, status, delivered_by) 
                                    VALUES (?, 1, 'ASSIGNED', ?)";
                    $delivery_stmt = $conn->prepare($delivery_sql);
                    $delivery_stmt->bind_param("ii", $shipment_id, $driver_id);
                    
                    if ($delivery_stmt->execute()) {
                        // Update shipment status to OUT_FOR_DELIVERY if it's not already
                        $update_sql = "UPDATE shipments SET status = 'OUT_FOR_DELIVERY', updated_by = ?, updated_at = CURRENT_TIMESTAMP 
                                      WHERE shipment_id = ? AND status != 'DELIVERED'";
                        $update_stmt = $conn->prepare($update_sql);
                        $update_stmt->bind_param("ii", $user_id, $shipment_id);
                        $update_stmt->execute();
                        
                        $success_count++;
                    }
                }
                
                $message = "Driver assigned to $success_count shipments.";
                $message_type = "success";
                break;
                
            case 'bulk_generate_labels':
                $shipment_ids = $_POST['shipment_ids'] ?? [];
                
                if (empty($shipment_ids)) {
                    $message = "Please select at least one shipment.";
                    $message_type = "warning";
                    break;
                }
                
                // Generate PDF with shipping labels
                $ids_string = implode(',', array_map('intval', $shipment_ids));
                header("Location: generate_bulk_labels.php?ids=$ids_string");
                exit;
                break;
                
            case 'bulk_send_notifications':
                $shipment_ids = $_POST['shipment_ids'] ?? [];
                $notification_type = $_POST['notification_type'];
                $custom_message = $_POST['custom_message'] ?? '';
                
                if (empty($shipment_ids)) {
                    $message = "Please select at least one shipment.";
                    $message_type = "warning";
                    break;
                }
                
                $success_count = 0;
                
                foreach ($shipment_ids as $shipment_id) {
                    // Get shipment details for notification
                    $shipment_sql = "SELECT s.tracking_number, s.receiver_name, s.receiver_email, s.receiver_phone, s.status 
                                    FROM shipments s WHERE s.shipment_id = ?";
                    $shipment_stmt = $conn->prepare($shipment_sql);
                    $shipment_stmt->bind_param("i", $shipment_id);
                    $shipment_stmt->execute();
                    $shipment_data = $shipment_stmt->get_result()->fetch_assoc();
                    
                    if ($shipment_data) {
                        // Send notification based on type
                        switch ($notification_type) {
                            case 'status_update':
                                $subject = "Shipment Status Update - " . $shipment_data['tracking_number'];
                                $body = "Your shipment " . $shipment_data['tracking_number'] . " status has been updated to: " . $shipment_data['status'];
                                if ($custom_message) {
                                    $body .= "\n\nAdditional Information: " . $custom_message;
                                }
                                break;
                                
                            case 'delivery_reminder':
                                $subject = "Delivery Reminder - " . $shipment_data['tracking_number'];
                                $body = "This is a reminder about your upcoming delivery for shipment " . $shipment_data['tracking_number'];
                                if ($custom_message) {
                                    $body .= "\n\n" . $custom_message;
                                }
                                break;
                                
                            case 'custom':
                                $subject = "Important Update - " . $shipment_data['tracking_number'];
                                $body = $custom_message;
                                break;
                        }
                        
                        // Here you would integrate with your notification service (SMS/Email)
                        // For demo purposes, we'll just log it
                        $notification_sql = "INSERT INTO notifications (user_id, title, message, notification_type, reference_type, reference_id) 
                                           VALUES (?, ?, ?, 'shipment_update', 'shipment', ?)";
                        $notification_stmt = $conn->prepare($notification_sql);
                        $notification_stmt->bind_param("issi", $user_id, $subject, $body, $shipment_id);
                        
                        if ($notification_stmt->execute()) {
                            $success_count++;
                        }
                    }
                }
                
                $message = "Notifications sent for $success_count shipments.";
                $message_type = "success";
                break;
                
            case 'bulk_export':
                $shipment_ids = $_POST['shipment_ids'] ?? [];
                $export_format = $_POST['export_format'];
                
                if (empty($shipment_ids)) {
                    $message = "Please select at least one shipment.";
                    $message_type = "warning";
                    break;
                }
                
                $ids_string = implode(',', array_map('intval', $shipment_ids));
                header("Location: export_shipments.php?ids=$ids_string&format=$export_format");
                exit;
                break;
        }
    }
}

// Get shipments for bulk operations (with filters)
$status_filter = $_GET['status'] ?? '';
$service_filter = $_GET['service'] ?? '';
$date_from = $_GET['date_from'] ?? date('Y-m-d', strtotime('-7 days'));
$date_to = $_GET['date_to'] ?? date('Y-m-d');
$search = $_GET['search'] ?? '';

$where_conditions = ["DATE(s.booking_date) >= ? AND DATE(s.booking_date) <= ?"];
$params = [$date_from, $date_to];
$param_types = 'ss';

if (!empty($status_filter)) {
    $where_conditions[] = "s.status = ?";
    $params[] = $status_filter;
    $param_types .= 's';
}

if (!empty($service_filter)) {
    $where_conditions[] = "s.service_id = ?";
    $params[] = $service_filter;
    $param_types .= 'i';
}

if (!empty($search)) {
    $where_conditions[] = "(s.tracking_number LIKE ? OR s.sender_name LIKE ? OR s.receiver_name LIKE ?)";
    $search_param = '%' . $search . '%';
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $param_types .= 'sss';
}

$where_clause = 'WHERE ' . implode(' AND ', $where_conditions);

$shipments_sql = "SELECT 
    s.shipment_id,
    s.tracking_number,
    s.sender_name,
    s.receiver_name,
    s.receiver_city,
    s.receiver_country,
    s.status,
    s.booking_date,
    s.pieces,
    s.chargeable_weight,
    s.total_charges,
    st.service_name,
    ol.location_name as origin_location,
    dl.location_name as destination_location
FROM shipments s
LEFT JOIN service_types st ON s.service_id = st.service_id
LEFT JOIN locations ol ON s.origin_location_id = ol.location_id
LEFT JOIN locations dl ON s.destination_location_id = dl.location_id
$where_clause
ORDER BY s.booking_date DESC
LIMIT 100";

$shipments_stmt = $conn->prepare($shipments_sql);
$shipments_stmt->bind_param($param_types, ...$params);
$shipments_stmt->execute();
$shipments_result = $shipments_stmt->get_result();

// Get dropdown data
$services_sql = "SELECT service_id, service_name FROM service_types WHERE is_active = 1 ORDER BY service_name";
$services_result = $conn->query($services_sql);

$drivers_sql = "SELECT driver_id, first_name, last_name FROM drivers WHERE status = 'ACTIVE' ORDER BY first_name, last_name";
$drivers_result = $conn->query($drivers_sql);

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Bulk Operations')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        .bulk-actions-panel {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            display: none;
        }
        
        .bulk-actions-panel.show {
            display: block;
            animation: fadeIn 0.3s ease;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .action-card {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            transition: all 0.2s ease;
        }
        
        .action-card:hover {
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .shipment-row {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 0.5rem;
            transition: all 0.2s ease;
        }
        
        .shipment-row:hover {
            background: #f8fafc;
        }
        
        .shipment-row.selected {
            background: #eff6ff;
            border-color: #3b82f6;
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .status-draft { background: #f3f4f6; color: #374151; }
        .status-booked { background: #dbeafe; color: #1d4ed8; }
        .status-collected { background: #d1fae5; color: #059669; }
        .status-in_transit { background: #fef3c7; color: #d97706; }
        .status-out_for_delivery { background: #e0e7ff; color: #5b21b6; }
        .status-delivered { background: #dcfce7; color: #166534; }
        .status-returned { background: #fee2e2; color: #991b1b; }
        .status-cancelled { background: #fecaca; color: #7f1d1d; }
        
        .filters-section {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .selection-info {
            background: #eff6ff;
            border: 1px solid #bfdbfe;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Bulk Operations</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="shipments.php">Shipments</a></li>
                                        <li class="breadcrumb-item active">Bulk Operations</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Alert Messages -->
                    <?php if ($message): ?>
                    <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
                        <?php echo $message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <!-- Filters Section -->
                    <div class="filters-section">
                        <h5 class="mb-3">Filter Shipments</h5>
                        <form method="GET" class="row g-3">
                            <div class="col-md-3">
                                <label class="form-label">Search</label>
                                <input type="text" class="form-control" name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="Tracking number, sender, receiver...">
                            </div>
                            
                            <div class="col-md-2">
                                <label class="form-label">Status</label>
                                <select class="form-select" name="status">
                                    <option value="">All Status</option>
                                    <option value="DRAFT" <?php echo $status_filter === 'DRAFT' ? 'selected' : ''; ?>>Draft</option>
                                    <option value="BOOKED" <?php echo $status_filter === 'BOOKED' ? 'selected' : ''; ?>>Booked</option>
                                    <option value="COLLECTED" <?php echo $status_filter === 'COLLECTED' ? 'selected' : ''; ?>>Collected</option>
                                    <option value="IN_TRANSIT" <?php echo $status_filter === 'IN_TRANSIT' ? 'selected' : ''; ?>>In Transit</option>
                                    <option value="OUT_FOR_DELIVERY" <?php echo $status_filter === 'OUT_FOR_DELIVERY' ? 'selected' : ''; ?>>Out for Delivery</option>
                                    <option value="DELIVERED" <?php echo $status_filter === 'DELIVERED' ? 'selected' : ''; ?>>Delivered</option>
                                </select>
                            </div>
                            
                            <div class="col-md-2">
                                <label class="form-label">Service</label>
                                <select class="form-select" name="service">
                                    <option value="">All Services</option>
                                    <?php while($service = $services_result->fetch_assoc()): ?>
                                    <option value="<?php echo $service['service_id']; ?>" <?php echo $service_filter == $service['service_id'] ? 'selected' : ''; ?>>
                                        <?php echo $service['service_name']; ?>
                                    </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-2">
                                <label class="form-label">Date From</label>
                                <input type="date" class="form-control" name="date_from" value="<?php echo $date_from; ?>">
                            </div>
                            
                            <div class="col-md-2">
                                <label class="form-label">Date To</label>
                                <input type="date" class="form-control" name="date_to" value="<?php echo $date_to; ?>">
                            </div>
                            
                            <div class="col-md-1">
                                <label class="form-label">&nbsp;</label>
                                <button type="submit" class="btn btn-primary d-block w-100">Filter</button>
                            </div>
                        </form>
                    </div>

                    <!-- Selection Info -->
                    <div class="selection-info" id="selectionInfo" style="display: none;">
                        <div class="d-flex justify-content-between align-items-center">
                            <span><span id="selectedCount">0</span> shipments selected</span>
                            <div class="d-flex gap-2">
                                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="clearSelection()">Clear Selection</button>
                                <button type="button" class="btn btn-primary btn-sm" onclick="showBulkActions()">Bulk Actions</button>
                            </div>
                        </div>
                    </div>

                    <!-- Bulk Actions Panel -->
                    <div class="bulk-actions-panel" id="bulkActionsPanel">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5>Bulk Actions</h5>
                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="hideBulkActions()">Close</button>
                        </div>
                        
                        <div class="row">
                            <!-- Status Update -->
                            <div class="col-md-6">
                                <div class="action-card">
                                    <h6><i class="bx bx-refresh"></i> Update Status</h6>
                                    <form method="POST" onsubmit="return submitBulkAction(this)">
                                        <input type="hidden" name="action" value="bulk_update_status">
                                        <div class="mb-3">
                                            <select class="form-select" name="new_status" required>
                                                <option value="">Select New Status</option>
                                                <option value="BOOKED">Booked</option>
                                                <option value="COLLECTED">Collected</option>
                                                <option value="IN_TRANSIT">In Transit</option>
                                                <option value="OUT_FOR_DELIVERY">Out for Delivery</option>
                                                <option value="DELIVERED">Delivered</option>
                                                <option value="RETURNED">Returned</option>
                                            </select>
                                        </div>
                                        <div class="mb-3">
                                            <input type="text" class="form-control" name="location" placeholder="Location (optional)">
                                        </div>
                                        <div class="mb-3">
                                            <textarea class="form-control" name="notes" rows="2" placeholder="Notes (optional)"></textarea>
                                        </div>
                                        <button type="submit" class="btn btn-primary btn-sm w-100">Update Status</button>
                                    </form>
                                </div>
                            </div>
                            
                            <!-- Assign Driver -->
                            <div class="col-md-6">
                                <div class="action-card">
                                    <h6><i class="bx bx-user"></i> Assign Driver</h6>
                                    <form method="POST" onsubmit="return submitBulkAction(this)">
                                        <input type="hidden" name="action" value="bulk_assign_driver">
                                        <div class="mb-3">
                                            <select class="form-select" name="driver_id" required>
                                                <option value="">Select Driver</option>
                                                <?php while($driver = $drivers_result->fetch_assoc()): ?>
                                                <option value="<?php echo $driver['driver_id']; ?>">
                                                    <?php echo $driver['first_name'] . ' ' . $driver['last_name']; ?>
                                                </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <button type="submit" class="btn btn-success btn-sm w-100">Assign Driver</button>
                                    </form>
                                </div>
                            </div>
                            
                            <!-- Send Notifications -->
                            <div class="col-md-6">
                                <div class="action-card">
                                    <h6><i class="bx bx-bell"></i> Send Notifications</h6>
                                    <form method="POST" onsubmit="return submitBulkAction(this)">
                                        <input type="hidden" name="action" value="bulk_send_notifications">
                                        <div class="mb-3">
                                            <select class="form-select" name="notification_type" required>
                                                <option value="">Select Type</option>
                                                <option value="status_update">Status Update</option>
                                                <option value="delivery_reminder">Delivery Reminder</option>
                                                <option value="custom">Custom Message</option>
                                            </select>
                                        </div>
                                        <div class="mb-3">
                                            <textarea class="form-control" name="custom_message" rows="3" placeholder="Custom message (optional)"></textarea>
                                        </div>
                                        <button type="submit" class="btn btn-info btn-sm w-100">Send Notifications</button>
                                    </form>
                                </div>
                            </div>
                            
                            <!-- Export/Generate -->
                            <div class="col-md-6">
                                <div class="action-card">
                                    <h6><i class="bx bx-download"></i> Export & Generate</h6>
                                    <div class="d-grid gap-2">
                                        <form method="POST" onsubmit="return submitBulkAction(this)" class="mb-2">
                                            <input type="hidden" name="action" value="bulk_generate_labels">
                                            <button type="submit" class="btn btn-warning btn-sm w-100">
                                                <i class="bx bx-label"></i> Generate Labels
                                            </button>
                                        </form>
                                        
                                        <form method="POST" onsubmit="return submitBulkAction(this)" class="mb-2">
                                            <input type="hidden" name="action" value="bulk_export">
                                            <input type="hidden" name="export_format" value="excel">
                                            <button type="submit" class="btn btn-outline-success btn-sm w-100">
                                                <i class="bx bx-file-doc"></i> Export to Excel
                                            </button>
                                        </form>
                                        
                                        <form method="POST" onsubmit="return submitBulkAction(this)">
                                            <input type="hidden" name="action" value="bulk_export">
                                            <input type="hidden" name="export_format" value="csv">
                                            <button type="submit" class="btn btn-outline-primary btn-sm w-100">
                                                <i class="bx bx-file"></i> Export to CSV
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Shipments List -->
                    <div class="row">
                        <div class="col-12">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="selectAll" onchange="toggleSelectAll()">
                                    <label class="form-check-label" for="selectAll">Select All</label>
                                </div>
                                <small class="text-muted">Showing <?php echo $shipments_result->num_rows; ?> shipments</small>
                            </div>

                            <?php if ($shipments_result->num_rows > 0): ?>
                                <?php while($shipment = $shipments_result->fetch_assoc()): ?>
                                <div class="shipment-row" data-shipment-id="<?php echo $shipment['shipment_id']; ?>">
                                    <div class="row align-items-center">
                                        <div class="col-md-1">
                                            <div class="form-check">
                                                <input class="form-check-input shipment-checkbox" type="checkbox" 
                                                       value="<?php echo $shipment['shipment_id']; ?>" 
                                                       onchange="updateSelection()">
                                            </div>
                                        </div>
                                        <div class="col-md-2">
                                            <strong><?php echo $shipment['tracking_number']; ?></strong>
                                            <br><small class="text-muted"><?php echo date('M j, Y', strtotime($shipment['booking_date'])); ?></small>
                                        </div>
                                        <div class="col-md-3">
                                            <div><?php echo htmlspecialchars($shipment['sender_name']); ?></div>
                                            <small class="text-muted">to <?php echo htmlspecialchars($shipment['receiver_name']); ?></small>
                                        </div>
                                        <div class="col-md-2">
                                            <div><?php echo htmlspecialchars($shipment['origin_location']); ?></div>
                                            <small class="text-muted">to <?php echo htmlspecialchars($shipment['destination_location']); ?></small>
                                        </div>
                                        <div class="col-md-1">
                                            <span class="status-badge status-<?php echo strtolower(str_replace(' ', '_', $shipment['status'])); ?>">
                                                <?php echo ucfirst(strtolower(str_replace('_', ' ', $shipment['status']))); ?>
                                            </span>
                                        </div>
                                        <div class="col-md-1">
                                            <small><?php echo $shipment['pieces']; ?> pcs</small>
                                            <br><small><?php echo $shipment['chargeable_weight']; ?> kg</small>
                                        </div>
                                        <div class="col-md-1">
                                            <strong>KES <?php echo number_format($shipment['total_charges']); ?></strong>
                                        </div>
                                        <div class="col-md-1">
                                            <a href="view_shipment.php?id=<?php echo $shipment['shipment_id']; ?>" class="btn btn-outline-primary btn-sm">
                                                <i class="bx bx-eye"></i>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <div class="text-center py-5">
                                    <div class="mb-3">
                                        <i class="bx bx-package" style="font-size: 4rem; color: #64748b;"></i>
                                    </div>
                                    <h5 class="text-muted">No shipments found</h5>
                                    <p class="text-muted">Try adjusting your filters or date range.</p>
                                    <a href="bulk_operations.php" class="btn btn-primary">Reset Filters</a>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <script>
        let selectedShipments = [];

        function toggleSelectAll() {
            const selectAllCheckbox = document.getElementById('selectAll');
            const checkboxes = document.querySelectorAll('.shipment-checkbox');
            
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAllCheckbox.checked;
            });
            
            updateSelection();
        }

        function updateSelection() {
            const checkboxes = document.querySelectorAll('.shipment-checkbox:checked');
            selectedShipments = Array.from(checkboxes).map(cb => cb.value);
            
            const count = selectedShipments.length;
            document.getElementById('selectedCount').textContent = count;
            
            const selectionInfo = document.getElementById('selectionInfo');
            const selectAllCheckbox = document.getElementById('selectAll');
            
            if (count > 0) {
                selectionInfo.style.display = 'block';
                
                // Update select all checkbox state
                const totalCheckboxes = document.querySelectorAll('.shipment-checkbox').length;
                if (count === totalCheckboxes) {
                    selectAllCheckbox.checked = true;
                    selectAllCheckbox.indeterminate = false;
                } else {
                    selectAllCheckbox.checked = false;
                    selectAllCheckbox.indeterminate = true;
                }
            } else {
                selectionInfo.style.display = 'none';
                selectAllCheckbox.checked = false;
                selectAllCheckbox.indeterminate = false;
            }
            
            // Update row styling
            document.querySelectorAll('.shipment-row').forEach(row => {
                const checkbox = row.querySelector('.shipment-checkbox');
                if (checkbox.checked) {
                    row.classList.add('selected');
                } else {
                    row.classList.remove('selected');
                }
            });
        }

        function clearSelection() {
            document.querySelectorAll('.shipment-checkbox').forEach(checkbox => {
                checkbox.checked = false;
            });
            document.getElementById('selectAll').checked = false;
            updateSelection();
        }

        function showBulkActions() {
            if (selectedShipments.length === 0) {
                alert('Please select at least one shipment.');
                return;
            }
            
            document.getElementById('bulkActionsPanel').classList.add('show');
            document.getElementById('bulkActionsPanel').scrollIntoView({ 
                behavior: 'smooth', 
                block: 'start' 
            });
        }

        function hideBulkActions() {
            document.getElementById('bulkActionsPanel').classList.remove('show');
        }

        function submitBulkAction(form) {
            if (selectedShipments.length === 0) {
                alert('Please select at least one shipment.');
                return false;
            }

            // Add selected shipment IDs to form
            selectedShipments.forEach(shipmentId => {
                const hiddenInput = document.createElement('input');
                hiddenInput.type = 'hidden';
                hiddenInput.name = 'shipment_ids[]';
                hiddenInput.value = shipmentId;
                form.appendChild(hiddenInput);
            });

            // Show confirmation dialog
            const action = form.querySelector('input[name="action"]').value;
            const actionNames = {
                'bulk_update_status': 'update status for',
                'bulk_assign_driver': 'assign driver to',
                'bulk_send_notifications': 'send notifications to',
                'bulk_generate_labels': 'generate labels for',
                'bulk_export': 'export'
            };

            const actionName = actionNames[action] || 'perform action on';
            const confirmMessage = `Are you sure you want to ${actionName} ${selectedShipments.length} selected shipments?`;

            return confirm(confirmMessage);
        }

        // Enhanced search functionality
        document.addEventListener('DOMContentLoaded', function() {
            // Auto-submit search on Enter
            document.querySelector('input[name="search"]').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    this.closest('form').submit();
                }
            });

            // Quick status filters
            const statusFilter = document.querySelector('select[name="status"]');
            if (statusFilter) {
                statusFilter.addEventListener('change', function() {
                    if (this.value !== '') {
                        this.closest('form').submit();
                    }
                });
            }

            // Date range validation
            const dateFrom = document.querySelector('input[name="date_from"]');
            const dateTo = document.querySelector('input[name="date_to"]');
            
            if (dateFrom && dateTo) {
                dateFrom.addEventListener('change', function() {
                    if (dateTo.value && this.value > dateTo.value) {
                        dateTo.value = this.value;
                    }
                });
                
                dateTo.addEventListener('change', function() {
                    if (dateFrom.value && this.value < dateFrom.value) {
                        dateFrom.value = this.value;
                    }
                });
            }
        });

        // Keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            // Ctrl+A to select all
            if ((e.ctrlKey || e.metaKey) && e.key === 'a' && e.target.tagName !== 'INPUT' && e.target.tagName !== 'TEXTAREA') {
                e.preventDefault();
                document.getElementById('selectAll').checked = true;
                toggleSelectAll();
            }
            
            // Escape to clear selection
            if (e.key === 'Escape') {
                clearSelection();
                hideBulkActions();
            }
            
            // Ctrl+B for bulk actions
            if ((e.ctrlKey || e.metaKey) && e.key === 'b') {
                e.preventDefault();
                showBulkActions();
            }
        });

        // Auto-refresh every 30 seconds for status updates
        setInterval(function() {
            // Only refresh if no selections are made to avoid losing user's work
            if (selectedShipments.length === 0) {
                location.reload();
            }
        }, 30000);

        // Progress tracking for bulk operations
        function showProgress(message) {
            const progressDiv = document.createElement('div');
            progressDiv.className = 'alert alert-info';
            progressDiv.innerHTML = `
                <div class="d-flex align-items-center">
                    <div class="spinner-border spinner-border-sm me-2" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    ${message}
                </div>
            `;
            
            document.querySelector('.container-fluid').insertBefore(progressDiv, document.querySelector('.selection-info'));
            
            setTimeout(() => {
                progressDiv.remove();
            }, 5000);
        }

        // Enhanced form submission with progress
        document.querySelectorAll('form').forEach(form => {
            form.addEventListener('submit', function() {
                const action = this.querySelector('input[name="action"]')?.value;
                if (action && action.startsWith('bulk_')) {
                    const actionMessages = {
                        'bulk_update_status': 'Updating shipment status...',
                        'bulk_assign_driver': 'Assigning driver to shipments...',
                        'bulk_send_notifications': 'Sending notifications...',
                        'bulk_generate_labels': 'Generating shipping labels...',
                        'bulk_export': 'Preparing export...'
                    };
                    
                    if (actionMessages[action]) {
                        showProgress(actionMessages[action]);
                    }
                }
            });
        });

        // Quick action buttons
        function quickStatusUpdate(status) {
            const selected = document.querySelectorAll('.shipment-checkbox:checked');
            if (selected.length === 0) {
                alert('Please select shipments first.');
                return;
            }
            
            if (confirm(`Update ${selected.length} shipments to ${status}?`)) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="bulk_update_status">
                    <input type="hidden" name="new_status" value="${status}">
                    ${Array.from(selected).map(cb => 
                        `<input type="hidden" name="shipment_ids[]" value="${cb.value}">`
                    ).join('')}
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }

        // Add quick action buttons to the page
        document.addEventListener('DOMContentLoaded', function() {
            const selectionInfo = document.getElementById('selectionInfo');
            const quickActions = document.createElement('div');
            quickActions.className = 'mt-2';
            quickActions.innerHTML = `
                <small class="text-muted">Quick Actions:</small>
                <div class="btn-group ms-2" role="group">
                    <button type="button" class="btn btn-outline-success btn-sm" onclick="quickStatusUpdate('COLLECTED')">Mark Collected</button>
                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="quickStatusUpdate('IN_TRANSIT')">In Transit</button>
                    <button type="button" class="btn btn-outline-warning btn-sm" onclick="quickStatusUpdate('OUT_FOR_DELIVERY')">Out for Delivery</button>
                    <button type="button" class="btn btn-outline-info btn-sm" onclick="quickStatusUpdate('DELIVERED')">Delivered</button>
                </div>
            `;
            selectionInfo.appendChild(quickActions);
        });
    </script>

    <!-- Print Styles -->
    <style media="print">
        .bulk-actions-panel, .filters-section, .selection-info, .btn, .page-title-right {
            display: none !important;
        }
        
        .shipment-row {
            break-inside: avoid;
            margin-bottom: 10px;
            border: 1px solid #000;
        }
        
        @page {
            margin: 1cm;
        }
    </style>

    <script src="assets/js/app.js"></script>
</body>
</html>