<?php
// Include your database connection
include 'db.php'; // Make sure this file contains your $link variable


if (isset($_POST['trackingsub'])) {

// Get tracking number from URL or form submission
$tracking_number = isset($_GET['tracking_number']) ? $_GET['tracking_number'] : (isset($_POST['tracking_number']) ? $_POST['tracking_number'] : '');

// Fetch shipment details
$shipment = [];
$tracking_updates = [];

if (!empty($tracking_number)) {
    // Query for shipment details
    $shipment_query = "SELECT * FROM tracking WHERE tracking_number = ?";
    $stmt = mysqli_prepare($link, $shipment_query);
    mysqli_stmt_bind_param($stmt, "s", $tracking_number);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    if ($result && mysqli_num_rows($result) > 0) {
        $shipment = mysqli_fetch_assoc($result);
        
        // Query for tracking updates
        $updates_query = "SELECT * FROM track_update WHERE track_num = ? ORDER BY date ASC, time ASC";
        $stmt_updates = mysqli_prepare($link, $updates_query);
        mysqli_stmt_bind_param($stmt_updates, "s", $tracking_number);
        mysqli_stmt_execute($stmt_updates);
        $updates_result = mysqli_stmt_get_result($stmt_updates);
        
        if ($updates_result && mysqli_num_rows($updates_result) > 0) {
            while ($row = mysqli_fetch_assoc($updates_result)) {
                $tracking_updates[] = $row;
            }
        }
    }
}

// Calculate progress percentage
$progress = 100;
if (!empty($shipment)) {
    $status = ($shipment['status']);
    if ($status == 'Active') $progress = 25;
    elseif ($status == 'Arrived') $progress = 50;
    elseif ($status == 'Picked Up') $progress = 75;
    elseif ($status == 'Delivered') $progress = 100;
    elseif ($status == 'Pending' || 'Inactive') $progress = 0;
}

// Prepare location history for map
$location_history = [];
if (!empty($shipment['dispatch_location'])) {
    $location_history[] = [
        'name' => $shipment['dispatch_location'],
        'lat' => $shipment['latitude'], // You'll need to add latitude/longitude to your database
        'lng' => $shipment['longitude'], // Or use a geocoding service
        'date' => $shipment['dispatch_date'],
        'status' => 'Dispatched'
    ];
}

foreach ($tracking_updates as $update) {
    $location_history[] = [
        'name' => $update['current_location'],
        'lat' => $update['latitude'], // Add to your database
        'lng' => $update['longitude'], // Add to your database
        'date' => $update['date'] . ' ' . $update['time'],
        'status' => $update['status'],
        'description' => $update['note']
    ];
}

if (!empty($shipment['destination'])) {
    $location_history[] = [
        'name' => $shipment['destination'],
        'lat' => $shipment['latitude'], // Add to your database
        'lng' => $shipment['longitude'], // Add to your database
        'date' => $shipment['delivery_date'],
        'status' => 'Destination'
    ];
}

// JSON encode data for JavaScript
$shipment_json = !empty($shipment) ? json_encode($shipment) : '{}';
$tracking_updates_json = !empty($tracking_updates) ? json_encode($tracking_updates) : '[]';
$location_history_json = !empty($location_history) ? json_encode($location_history) : '[]';

}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <title><?php echo !empty($shipment) ? "Track Shipment - " . htmlspecialchars($shipment['tracking_number']) : "Track Shipment"; ?> | Global Freight</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Libre+Barcode+39&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.min.css" rel="stylesheet"/>
    <script src="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.min.js"></script>
    
    <!-- Print Stylesheet -->
    <style media="print">
        @page {
            size: A4;
            margin: 0.5cm;
        }
        
        body {
            font-family: 'Poppins', sans-serif;
            background: white !important;
            color: #333 !important;
            font-size: 12pt;
        }
        
        /* Hide elements not needed for print */
        header, footer, .no-print, button, .leaflet-container, 
        [x-data="{ shareOpen: false }"], .bg-gradient-to-r {
            display: none !important;
        }
        
        /* Receipt styling */
        .print-receipt {
            display: block !important;
            background: white;
            padding: 20px;
            margin: 0 auto;
            max-width: 100%;
            box-shadow: none;
        }
        
        .print-receipt-header {
            display: flex !important;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #ddd;
            padding-bottom: 15px;
            margin-bottom: 20px;
        }
        
        .print-receipt-body {
            margin-bottom: 20px;
        }
        
        .print-receipt-footer {
            border-top: 1px solid #ddd;
            padding-top: 15px;
            font-size: 10pt;
            color: #666;
            text-align: center;
        }
        
        .print-grid {
            display: grid !important;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        
        .print-section {
            margin-bottom: 15px;
        }
        
        .print-section-title {
            font-weight: bold;
            margin-bottom: 5px;
            font-size: 14pt;
        }
        
        .print-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 15px;
        }
        
        .print-table th, .print-table td {
            border: 1px solid #ddd;
            padding: 8px 12px;
            text-align: left;
        }
        
        .print-table th {
            background-color: #f8f8f8;
        }
        
        .print-barcode {
            display: block;
            text-align: center;
            margin: 20px auto;
            padding: 10px;
            background: white;
            border: 1px solid #ddd;
        }
        
        /* Timeline for print */
        .print-timeline {
            margin: 20px 0;
        }
        
        .print-timeline-item {
            display: flex;
            margin-bottom: 10px;
        }
        
        .print-timeline-date {
            width: 120px;
            font-weight: bold;
        }
        
        .print-qr {
            text-align: center;
            margin-top: 20px;
        }
        
        /* Show elements specifically for print */
        .print-only {
            display: block !important;
        }
        
        .divider {
            border-top: 1px dashed #ddd;
            margin: 15px 0;
        }
    </style>
    <style>
        body {
            font-family: 'Poppins', sans-serif;
            background-color: #f8fafc;
        }
        
        .hero-pattern {
            background-image: url("data:image/svg+xml,%3Csvg width='100' height='100' viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M11 18c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm48 25c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm-43-7c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm63 31c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM34 90c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm56-76c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM12 86c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm28-65c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm23-11c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-6 60c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm29 22c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zM32 63c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm57-13c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-9-21c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM60 91c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM35 41c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM12 60c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2z' fill='%239C92AC' fill-opacity='0.05' fill-rule='evenodd'/%3E%3C/svg%3E");
        }
        
        .tracking-status-dot {
            height: 12px;
            width: 12px;
            border-radius: 50%;
            display: inline-block;
        }
        
        .fade-in {
            animation: fadeIn 0.5s ease-in-out;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .status-timeline-item::before {
            content: "";
            position: absolute;
            left: 6px;
            top: 24px;
            bottom: -12px;
            width: 2px;
            background-color: #e5e7eb;
            z-index: 0;
        }
        
        .status-timeline-item:last-child::before {
            display: none;
        }
        
        .pulse {
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% {
                box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.7);
            }
            70% {
                box-shadow: 0 0 0 10px rgba(59, 130, 246, 0);
            }
            100% {
                box-shadow: 0 0 0 0 rgba(59, 130, 246, 0);
            }
        }
        
        .leaflet-container {
            border-radius: 0.5rem;
            z-index: 10;
        }
    </style>
</head>
<body class="min-h-screen hero-pattern">
    <!-- Header with Logo -->
    <header class="bg-white shadow-sm py-4">
        <div class="container mx-auto px-4 flex justify-between items-center">
            <div class="flex items-center">
                <a href="/" class="text-2xl font-bold text-[#582A72]">
                    <i class="fas fa-truck-fast mr-2"></i>Global Freight
                </a>
            </div>
            <nav class="hidden md:flex space-x-6">
                <a href="index.html" class="text-gray-600 hover:text-blue-600 transition-colors">Home</a>
                <a href="services.html" class="text-gray-600 hover:text-blue-600 transition-colors">Services</a>
                <a href="track.html" class="text-blue-600 font-medium">Track</a>
                <a href="contacts.html" class="text-gray-600 hover:text-blue-600 transition-colors">Contact</a>
            </nav>
            <button class="hidden text-gray-500 focus:outline-none">
                <i class="fas fa-bars text-xl"></i>
            </button>
        </div>
    </header>

    <main class="container mx-auto px-4 py-8">
        <div class="max-w-5xl mx-auto">
            <!-- Navigation Controls -->
            <div class="flex justify-between items-center mb-4">
            <a href="track.html" class="inline-flex items-center text-[#582A72] hover:text-[#582A72]/90 transition-colors">
    <i class="fas fa-arrow-left mr-2"></i>
    Back to Tracking
</a>
                
                <?php if (!empty($shipment)): ?>
                <div class="flex space-x-3">
                    <div x-data="{ shareOpen: false }" class="relative">
                        <button @click="shareOpen = !shareOpen" type="button" class="inline-flex items-center text-[#582A72] hover:text-[#582A72] transition-colors">
                            <i class="fas fa-share-alt mr-1"></i>
                            <span class="hidden sm:inline">Share</span>
                        </button>
                        
                        <div x-show="shareOpen" @click.away="shareOpen = false" class="absolute right-0 mt-2 w-60 bg-white rounded-lg shadow-lg p-3 z-50 text-sm fade-in">
                            <div class="text-gray-700 font-medium mb-2">Share tracking information</div>
                            <div class="flex space-x-3 mb-2">
                                <a href="mailto:?subject=Track%20Shipment%20<?php echo urlencode($shipment['tracking_number']); ?>&body=Track%20your%20shipment:%20<?php echo urlencode("$sitename/track.php?tracking_number=" . $shipment['tracking_number']); ?>" class="text-gray-600 hover:text-blue-600">
                                    <i class="fas fa-envelope text-xl"></i>
                                </a>
                                <a href="https://wa.me/?text=Track%20your%20shipment:%20<?php echo urlencode("$sitename/track.php?tracking_number=" . $shipment['tracking_number']); ?>" target="_blank" class="text-gray-600 hover:text-green-600">
                                    <i class="fab fa-whatsapp text-xl"></i>
                                </a>
                                <a href="https://twitter.com/intent/tweet?text=Track%20my%20shipment:%20<?php echo urlencode("$sitename/track.php?tracking_number=" . $shipment['tracking_number']); ?>" target="_blank" class="text-gray-600 hover:text-blue-400">
                                    <i class="fab fa-twitter text-xl"></i>
                                </a>
                                <a href="#" onclick="copyTrackingLink(); return false;" class="text-gray-600 hover:text-purple-600">
                                    <i class="fas fa-copy text-xl"></i>
                                </a>
                            </div>
                            <div class="flex items-center border rounded overflow-hidden">
                                <input type="text" readonly value="<?php echo "$sitename/track.php?tracking_number=" . htmlspecialchars($shipment['tracking_number']); ?>" id="tracking-url" class="w-full px-2 py-1 text-xs outline-none">
                                <button onclick="copyTrackingLink()" class="bg-blue-50 px-2 py-1 text-[#582A72] text-xs">Copy</button>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
            
            <?php if (!empty($shipment)): ?>
          <!-- Shipment Header -->
<div class="bg-[#582A72] rounded-2xl p-6 md:p-8 mb-6 text-white relative overflow-hidden shadow-xl">
    <div class="absolute right-0 top-0 opacity-10">
        <i class="fas fa-truck-fast text-9xl transform -rotate-12 translate-x-10 -translate-y-10"></i>
    </div>
    
    <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6">
        <div>
            <h1 class="text-2xl md:text-3xl font-bold flex items-center">
                <i class="fas fa-box mr-2"></i>
                <?php echo htmlspecialchars($shipment['tracking_number']); ?>
            </h1>
            <p class="text-purple-100 mt-1">Status: <span class="font-semibold"><?php echo htmlspecialchars(ucfirst($shipment['status'])); ?></span></p>
        </div>
        <div class="mt-4 md:mt-0 bg-white bg-opacity-10 px-4 py-3 rounded-lg backdrop-blur-sm">
            <p class="text-sm text-purple-100">Estimated Delivery</p>
            <p class="text-xl font-semibold"><?php echo !empty($shipment['delivery_date']) ? htmlspecialchars($shipment['delivery_date']) : 'N/A'; ?></p>
        </div>
    </div>

    <!-- Progress Bar -->
    <div class="mb-4">
        <div class="flex justify-between items-center mb-2">
            <div class="flex items-center">
                <span class="text-xs font-semibold px-2 py-1 bg-purple-500 bg-opacity-30 rounded-full">
                    Shipment Progress
                </span>
            </div>
            <div>
                <span class="text-sm font-semibold"><?php echo $progress; ?>%</span>
            </div>
        </div>
        <div class="h-2 w-full bg-purple-200 bg-opacity-30 rounded-full overflow-hidden">
            <div class="h-full bg-white" style="width: <?php echo $progress; ?>%"></div>
        </div>
    </div>
    
    <!-- Quick Info -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mt-6">
        <div class="bg-white bg-opacity-10 rounded-lg p-3 backdrop-blur-sm">
            <p class="text-xs text-purple-100">Origin</p>
            <p class="font-medium flex items-center">
                <i class="fas fa-map-marker-alt mr-2 text-purple-200"></i>
                <?php echo !empty($shipment['dispatch_location']) ? htmlspecialchars($shipment['dispatch_location']) : 'N/A'; ?>
            </p>
        </div>
        <div class="bg-white bg-opacity-10 rounded-lg p-3 backdrop-blur-sm">
            <p class="text-xs text-purple-100">Current Location</p>
            <p class="font-medium flex items-center">
                <i class="fas fa-location-dot mr-2 text-purple-200 pulse"></i>
                <?php echo !empty($shipment['current_location']) ? htmlspecialchars($shipment['current_location']) : 'N/A'; ?>
            </p>
        </div>
        <div class="bg-white bg-opacity-10 rounded-lg p-3 backdrop-blur-sm">
            <p class="text-xs text-purple-100">Destination</p>
            <p class="font-medium flex items-center">
                <i class="fas fa-flag-checkered mr-2 text-purple-200"></i>
                <?php echo !empty($shipment['destination']) ? htmlspecialchars($shipment['destination']) : 'N/A'; ?>
            </p>
        </div>
    </div>
</div>
            
            
            
            
            
            <!-- Permit Required Notification -->
            <?php if (!empty($shipment['requires_permit'])): ?>
            <div x-data="{ showPermitModal: false }" class="mb-6">
                <!-- Notification Banner -->
                <div @click="showPermitModal = true" class="bg-amber-50 border-l-4 border-amber-500 p-4 rounded-lg shadow-md flex items-center justify-between cursor-pointer hover:bg-amber-100 transition-colors">
                    <div class="flex items-center">
                        <div class="bg-amber-500 rounded-full p-2 mr-4 flex-shrink-0">
                            <i class="fas fa-certificate text-white"></i>
                        </div>
                        <div>
                            <h3 class="font-semibold text-amber-800">Customs Clearance Document Required</h3>
                            <p class="text-amber-700 text-sm">This shipment requires a customs clearance document. Click for details.</p>
                        </div>
                    </div>
                    <div class="bg-amber-500 hover:bg-amber-600 text-white px-3 py-2 rounded-lg shadow transition-colors flex-shrink-0">
                        <span class="hidden sm:inline">Details</span>
                        <i class="fas fa-arrow-right ml-1 sm:ml-2"></i>
                    </div>
                </div>
                
                <!-- Modal Popup -->
                <div x-show="showPermitModal" 
                     class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4" 
                     x-transition:enter="transition ease-out duration-300"
                     x-transition:enter-start="opacity-0 transform scale-95"
                     x-transition:enter-end="opacity-100 transform scale-100"
                     x-transition:leave="transition ease-in duration-200"
                     x-transition:leave-start="opacity-100 transform scale-100"
                     x-transition:leave-end="opacity-0 transform scale-95"
                     style="display: none;">
                    <div @click.outside="showPermitModal = false" class="bg-white rounded-xl shadow-2xl w-full max-w-md relative">
                        <!-- Modal Header -->
                        <div class="bg-gradient-to-r from-amber-500 to-amber-600 text-white p-6">
                            <div class="flex justify-between items-center">
                                <h3 class="text-xl font-bold flex items-center">
                                    <i class="fas fa-certificate mr-2"></i>
                                    Customs Clearance Document
                                </h3>
                                <button @click="showPermitModal = false" class="text-white hover:text-gray-200 focus:outline-none">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                            <p class="mt-2 text-amber-100">Required for shipment #<?php echo htmlspecialchars($shipment['tracking_number']); ?></p>
                        </div>
                        
                        <!-- Modal Body -->
                        <div class="p-6">
                            <div class="bg-amber-50 border border-amber-200 rounded-lg p-4 mb-4">
                                <p class="text-amber-800">Your shipment to <strong><?php echo htmlspecialchars($shipment['destination']); ?></strong> requires a customs clearance document that must be purchased before delivery can be completed.</p>
                            </div>
                            
                            <h4 class="font-semibold text-gray-700 mb-2">Why is a permit needed?</h4>
                            <ul class="list-disc pl-5 mb-4 space-y-1 text-gray-600 text-sm">
                                <li>International destination requiring customs clearance</li>
                                <li>Package content may be subject to import regulations</li>
                                <li>Required documentation for cross-border shipping</li>
                            </ul>
                            
                            <div class="bg-gray-50 rounded-lg p-4 mb-4">
                                <h4 class="font-semibold text-gray-700 mb-2">Permit Options</h4>
                                <div class="space-y-2">
                                    <div class="flex justify-between">
                                        <span>Standard Processing (3-5 days)</span>
                                    </div>
                                    <div class="flex justify-between">
                                        <span>Express Processing (1-2 days)</span>
                                    </div>
                                    <div class="flex justify-between">
                                        <span>Premium Processing (Same day)</span>
                                    </div>
                                </div>
                                <p class="text-sm text-amber-700 mt-3 italic">
                                    <i class="fas fa-info-circle mr-1"></i>
                                    Please contact support for current pricing information
                                </p>
                            </div>
                            
                            <p class="text-sm text-gray-500 mb-4">Without the proper permit, your shipment may be held at customs or returned to the sender. Contact our support team immediately to arrange permit purchase.</p>
                            
                            <div class="space-y-3">
                                <a href="mailto:support@globalfreight.com?subject=Permit%20Request%20for%20Shipment%20<?php echo urlencode($shipment['tracking_number']); ?>" class="flex items-center justify-center w-full bg-amber-500 hover:bg-amber-600 text-white font-medium py-3 px-4 rounded-lg transition-colors">
                                    <i class="fas fa-envelope mr-2"></i>
                                    Request Permit via Email
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php endif; ?>
                        
            <!-- Main Content Area -->
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <!-- Left Column -->
                <div class="lg:col-span-2 space-y-6">
                    <!-- Map Section -->
                    <div class="bg-white rounded-xl shadow-md overflow-hidden">
                        <div class="p-4 bg-gray-50 border-b">
                            <h3 class="font-semibold text-gray-800 flex items-center">
                                <i class="fas fa-map-location-dot mr-2 text-blue-600"></i>
                                Shipment Route
                            </h3>
                        </div>
                        <div id="map" class="w-full h-[400px]" style="min-height: 400px; z-index: 1;"></div>
                    </div>
                                  
                    <!-- Location Information -->
                    <div class="bg-white rounded-xl shadow-md overflow-hidden">
                        <div class="p-4 bg-gray-50 border-b">
                            <h3 class="font-semibold text-gray-800 flex items-center">
                                <i class="fas fa-location-dot mr-2 text-blue-600"></i>
                                Location Information
                            </h3>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 p-4">
                            <div>
                                <p class="text-sm text-gray-600">Origin</p>
                                <p class="font-medium flex items-center">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                                    </svg>
                                    <?php echo !empty($shipment['dispatch_location']) ? htmlspecialchars($shipment['dispatch_location']) : 'N/A'; ?>
                                </p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-600">Current Location</p>
                                <p class="font-medium flex items-center">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                                    </svg>
                                    <?php echo !empty($shipment['current_location']) ? htmlspecialchars($shipment['current_location']) : 'N/A'; ?>
                                </p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-600">Destination</p>
                                <p class="font-medium flex items-center">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                                    </svg>
                                    <?php echo !empty($shipment['destination']) ? htmlspecialchars($shipment['destination']) : 'N/A'; ?>
                                </p>
                            </div>
                        </div>
                    </div>

                    <!-- Interactive Timeline -->
                    <div class="bg-white rounded-xl shadow-md overflow-hidden" x-data="{ showAll: false }">
                        <div class="p-4 bg-gray-50 border-b flex justify-between items-center">
                            <h3 class="font-semibold text-gray-800 flex items-center">
                                <i class="fas fa-clock-rotate-left mr-2 text-blue-600"></i>
                                Shipment Timeline
                            </h3>
                            <?php if (count($tracking_updates) > 3): ?>
                            <button @click="showAll = !showAll" type="button" class="text-blue-600 hover:text-blue-800 text-sm flex items-center">
                                <span x-text="showAll ? 'Show Less' : 'Show All'"></span>
                                <i class="fas ml-1" :class="showAll ? 'fa-chevron-up' : 'fa-chevron-down'"></i>
                            </button>
                            <?php endif; ?>
                        </div>
                        
                        <div class="p-6">
                            <div class="relative">
                                <!-- Timeline Line -->
                                <div class="absolute left-5 top-0 ml-px h-full w-0.5 bg-gray-200"></div>

                                <!-- Timeline Items -->
                                <div class="space-y-6">
                                    <!-- Origin point -->
                                    <div class="relative pl-10">
                                        <span class="absolute left-5 top-1 -ml-3 h-6 w-6 rounded-full border-2 border-blue-600 bg-white flex items-center justify-center">
                                            <i class="fas fa-warehouse text-xs text-blue-600"></i>
                                        </span>
                                        <div class="bg-blue-50 rounded-lg p-4">
                                            <div class="flex justify-between">
                                                <h4 class="font-medium text-blue-800">Dispatched from Origin</h4>
                                                <span class="text-sm text-gray-500"><?php echo !empty($shipment['dispatch_date']) ? htmlspecialchars($shipment['dispatch_date']) : 'N/A'; ?></span>
                                            </div>
                                            <p class="text-gray-600 mt-1"><?php echo !empty($shipment['dispatch_location']) ? htmlspecialchars($shipment['dispatch_location']) : 'N/A'; ?></p>
                                        </div>
                                    </div>

                                    <!-- Tracking updates -->
                                    <?php foreach ($tracking_updates as $index => $update): ?>
                                    <div class="relative pl-10" x-show="showAll || <?php echo $index; ?> < 3 || 'delivered' === '<?php echo strtolower($shipment['status']); ?>'">
                                        <span class="absolute left-5 top-1 -ml-3 h-6 w-6 rounded-full border-2 
                                            <?php echo strtolower($update['status']) == 'on hold' ? 'border-amber-400' : 'border-blue-400'; ?> 
                                            bg-white flex items-center justify-center">
                                            <i class="fas fa-circle text-xs <?php echo strtolower($update['status']) == 'on hold' ? 'text-amber-400' : 'text-blue-400'; ?>"></i>
                                        </span>

                                        <div class="<?php echo strtolower($update['status']) == 'on hold' ? 'bg-amber-50' : 'bg-gray-50'; ?> rounded-lg p-4">
                                            <div class="flex flex-col sm:flex-row sm:justify-between sm:items-start mb-1">
                                                <h4 class="font-medium">
                                                    <?php echo !empty($update['current_location']) ? htmlspecialchars($update['current_location']) : 'Location not specified'; ?>
                                                </h4>
                                                <span class="text-sm text-gray-500">
                                                    <?php echo !empty($update['date']) ? htmlspecialchars($update['date']) : 'N/A'; ?>
                                                    <?php if (!empty($update['time'])): ?>
                                                    - <?php echo htmlspecialchars($update['time']); ?>
                                                    <?php endif; ?>
                                                </span>
                                            </div>
                                            
                                            <div class="flex items-center mb-2">
                                                <span class="px-2 py-1 text-xs rounded-full 
                                                    <?php echo strtolower($update['status']) == 'on hold' ? 'bg-amber-100 text-amber-800' : 'bg-blue-100 text-blue-800'; ?>">
                                                    <?php echo !empty($update['status']) ? htmlspecialchars(ucfirst($update['status'])) : 'Status Update'; ?>
                                                </span>
                                            </div>
                                            
                                            <?php if (!empty($update['note'])): ?>
                                            <p class="text-gray-600 mt-1"><?php echo htmlspecialchars($update['note']); ?></p>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                    
                                    <!-- Destination (projected) -->
                                    <div class="relative pl-10">
                                        <span class="absolute left-5 top-1 -ml-3 h-6 w-6 rounded-full border-2 
                                            <?php echo strtolower($shipment['status']) == 'delivered' ? 'border-green-500' : 'border-gray-300'; ?> 
                                            bg-white flex items-center justify-center">
                                            <i class="fas fa-flag-checkered text-xs <?php echo strtolower($shipment['status']) == 'delivered' ? 'text-green-500' : 'text-gray-400'; ?>"></i>
                                        </span>
                                        <div class="<?php echo strtolower($shipment['status']) == 'delivered' ? 'bg-green-50' : 'bg-gray-50'; ?> rounded-lg p-4">
                                            <div class="flex justify-between">
                                                <h4 class="font-medium">
                                                    <?php echo strtolower($shipment['status']) == 'delivered' ? 'Delivered to Destination' : 'Delivery at Destination'; ?>
                                                </h4>
                                                <span class="text-sm text-gray-500">
                                                    <?php echo !empty($shipment['delivery_date']) ? htmlspecialchars($shipment['delivery_date']) : 'N/A'; ?>
                                                    <?php if (!empty($shipment['delivery_time'])): ?>
                                                    - <?php echo htmlspecialchars($shipment['delivery_time']); ?>
                                                    <?php endif; ?>
                                                </span>
                                            </div>
                                            <p class="text-gray-600 mt-1"><?php echo !empty($shipment['destination']) ? htmlspecialchars($shipment['destination']) : 'N/A'; ?></p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Package Details -->
                    <div class="bg-white rounded-xl shadow-md overflow-hidden">
                        <div class="p-4 bg-gray-50 border-b">
                            <h3 class="font-semibold text-gray-800 flex items-center">
                                <i class="fas fa-box mr-2 text-blue-600"></i>
                                Package Details
                            </h3>
                        </div>
                        <div class="p-4" x-data="{ showDetails: false }">
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-y-4 gap-x-6">
                                <div>
                                    <p class="text-sm text-gray-500">Description</p>
                                    <p class="font-medium"><?php echo !empty($shipment['pdesc']) ? htmlspecialchars($shipment['pdesc']) : 'N/A'; ?></p>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-500">Shipping Mode</p>
                                    <p class="font-medium flex items-center">
                                        <?php 
                                        $ship_mode = !empty($shipment['ship_mode']) ? strtolower($shipment['ship_mode']) : '';
                                        $mode_icon = '';
                                        $mode_text = '';
                                        
                                        switch ($ship_mode) {
                                            case 'air':
                                                $mode_icon = 'fa-plane';
                                                $mode_text = 'Air';
                                                break;
                                            case 'sea':
                                                $mode_icon = 'fa-ship';
                                                $mode_text = 'Sea';
                                                break;
                                            case 'land':
                                                $mode_icon = 'fa-truck';
                                                $mode_text = 'Land';
                                                break;
                                            default:
                                                $mode_icon = 'fa-box';
                                                $mode_text = 'N/A';
                                        }
                                        ?>
                                        <i class="fas <?php echo $mode_icon; ?> mr-2"></i>
                                        <?php echo $mode_text; ?>
                                    </p>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-500">Weight</p>
                                    <p class="font-medium"><?php echo !empty($shipment['weight']) ? htmlspecialchars($shipment['weight']) : 'N/A'; ?></p>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-500">Quantity</p>
                                    <p class="font-medium"><?php echo !empty($shipment['quantity']) ? htmlspecialchars($shipment['quantity']) : 'N/A'; ?></p>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-500">Carrier</p>
                                    <p class="font-medium"><?php echo !empty($shipment['carrier']) ? htmlspecialchars($shipment['carrier']) : 'N/A'; ?></p>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-500">Carrier Reference</p>
                                    <p class="font-medium"><?php echo !empty($shipment['carrier_ref']) ? htmlspecialchars($shipment['carrier_ref']) : 'N/A'; ?></p>
                                </div>
                            </div>
                            
                            <div class="mt-4">
                                <button type="button" @click="showDetails = !showDetails" class="text-blue-600 hover:text-blue-800 text-sm flex items-center">
                                    <span x-text="showDetails ? 'Hide Additional Details' : 'Show Additional Details'"></span>
                                    <i class="fas ml-1" :class="showDetails ? 'fa-chevron-up' : 'fa-chevron-down'"></i>
                                </button>
                                
                                <div x-show="showDetails" x-collapse class="bg-gray-50 mt-3 p-4 rounded-lg">
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-y-4 gap-x-6">
                                        <div>
                                            <p class="text-sm text-gray-500">Payment Mode</p>
                                            <p class="font-medium"><?php echo !empty($shipment['payment_mode']) ? htmlspecialchars(ucfirst($shipment['payment_mode'])) : 'N/A'; ?></p>
                                        </div>
                                        <div>
                                            <p class="text-sm text-gray-500">Total Freight Cost</p>
                                            <p class="font-medium"><?php echo !empty($shipment['total_f']) ? '$' . htmlspecialchars($shipment['total_f']) : 'N/A'; ?></p>
                                        </div>
                                        <div class="md:col-span-2">
                                            <p class="text-sm text-gray-500">Estimated Timeline</p>
                                            <div class="mt-1">
                                                <p class="font-medium">Dispatch: <?php echo !empty($shipment['dispatch_date']) ? htmlspecialchars($shipment['dispatch_date']) : 'N/A'; ?></p>
                                                <p class="font-medium">Delivery: <?php echo !empty($shipment['delivery_date']) ? htmlspecialchars($shipment['delivery_date']) : 'N/A'; ?></p>
                                            </div>
                                        </div>
                                        
                                        <div class="md:col-span-2">
    <p class="text-sm text-gray-500">Package Image</p>
    <div class="mt-1">
        <?php if (!empty($shipment['image'])): ?>
            <img src='uploads/<?php echo htmlspecialchars($shipment['image']); ?>' alt='Package image'>
        <?php else: ?>
            <div class="bg-gray-200 text-gray-500 p-4">No image available</div>
        <?php endif; ?>
    </div>
</div>


<section class="services-area">
    <div class="auto-container">
        <div class="print-receipt-container" style="text-align: center; margin: 20px 0;">
            <a href="invoice/receipt.php?tracking_number=<?php echo $shipment['tracking_number']; ?>" 
               style="
                   background-color: #0a295c;
                   color: white;
                   padding: 12px 24px;
                   text-decoration: none;
                   border-radius: 4px;
                   font-weight: 600;
                   font-size: 16px;
                   display: inline-block;
                   transition: all 0.3s ease;
                   box-shadow: 0 2px 5px rgba(0,0,0,0.2);
                   border: 1px solid #0a295c;
                   text-transform: uppercase;
                   letter-spacing: 0.5px;
               "
               onmouseover="this.style.backgroundColor='#0d3a7a'; this.style.transform='translateY(-2px)'; this.style.boxShadow='0 4px 8px rgba(0,0,0,0.3)';"
               onmouseout="this.style.backgroundColor='#0a295c'; this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 5px rgba(0,0,0,0.2)';"
               class="print-receipt-btn">
               Print Receipt
            </a>
        </div>
    </div>
</section>
                                        
                                        
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Right Column -->
                <div class="lg:col-span-1 space-y-6">
                    <!-- Track Another Shipment -->
                    <div class="bg-white rounded-xl shadow-md overflow-hidden">
                        <div class="p-4 bg-blue-50 border-b">
                            <h3 class="font-semibold text-gray-800 flex items-center">
                                <i class="fas fa-search mr-2 text-[#582A72]"></i>
                                Track Another Shipment
                            </h3>
                        </div>
                        <div class="p-4">
                            <form action='track.php'  method="POST" class="space-y-3">
                               
                                <div>
                                    <label for="quick-tracking-number" class="block text-sm text-gray-500 mb-1">Tracking Number</label>
                                    <div class="relative">
                                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                            <i class="fas fa-search text-gray-400"></i>
                                        </div>
                                        <input type="text" id="quick-tracking-number" name="tracking_number" placeholder="Enter tracking number" 
                                            class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none transition-all">
                                    </div>
                                </div>
                                <button type="submit" name='trackingsub' class="w-full bg-[#582A72] hover:bg-[#582A72] text-white font-medium py-2 px-4 rounded-lg transition-colors flex items-center justify-center">
                                    <i class="fas fa-search mr-2"></i> Track
                                </button>
                            </form>
                        </div>
                    </div>
                    
                    <!-- Receiver Information -->
                    <div class="bg-white rounded-xl shadow-md overflow-hidden">
                        <div class="p-4 bg-gray-50 border-b">
                            <h3 class="font-semibold text-gray-800 flex items-center">
                                <i class="fas fa-user mr-2 text-[#582A72]"></i>
                                Receiver Information
                            </h3>
                        </div>
                        <div class="p-4 space-y-3">
                            <div>
                                <p class="text-sm text-gray-600">Name</p>
                                <p class="font-medium"><?php echo !empty($shipment['receiver_name']) ? htmlspecialchars($shipment['receiver_name']) : 'N/A'; ?></p>
                            </div>
                            <div>
                            <p class="text-sm text-gray-600">Email</p>
                            <p class="font-medium">
                                <?php if (!empty($shipment['receiver_email'])): ?>
                                    <?php 
                                        $email_parts = explode('@', $shipment['receiver_email']);
                                        $hidden_email = substr($email_parts[0], 0, 3) . '***' . (isset($email_parts[1]) ? '@' . $email_parts[1] : '');
                                        echo htmlspecialchars($hidden_email);
                                    ?>
                                <?php else: ?>
                                    N/A
                                <?php endif; ?>
                            </p>
                        </div>

                            <div>
                                <p class="text-sm text-gray-600">Contact</p>
                                <p class="font-medium">
                                    <?php if (!empty($shipment['receiver_contact'])): ?>
                                        <?php 
                                        $contact = $shipment['receiver_contact'];
                                        $hidden_contact = substr($contact, 0, 3) . '***' . substr($contact, -4);
                                        echo htmlspecialchars($hidden_contact);
                                        ?>
                                    <?php else: ?>
                                        N/A
                                    <?php endif; ?>
                                </p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-600">Delivery Address</p>
                                <p class="font-medium"><?php echo !empty($shipment['receiver_address']) ? htmlspecialchars($shipment['receiver_address']) : 'N/A'; ?></p>
                            </div>
                        </div>
                    </div>

                    <!-- Sender Information -->
                    <div class="bg-white rounded-xl shadow-md overflow-hidden">
                        <div class="p-4 bg-gray-50 border-b">
                            <h3 class="font-semibold text-gray-800 flex items-center">
                                <i class="fas fa-user mr-2 text-[#582A72]"></i>
                                Sender Information
                            </h3>
                        </div>
                        <div class="p-4 space-y-3">
                            <div>
                                <p class="text-sm text-gray-600">Name</p>
                                <p class="font-medium"><?php echo !empty($shipment['sender_name']) ? htmlspecialchars($shipment['sender_name']) : 'N/A'; ?></p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-600">Email</p>
                                <p class="font-medium">
                                    <?php if (!empty($shipment['sender_email'])): ?>
                                        <?php 
                                        $email_parts = explode('@', $shipment['sender_email']);
                                        $hidden_email = substr($email_parts[0], 0, 3) . '***' . (isset($email_parts[1]) ? '@' . $email_parts[1] : '');
                                        echo htmlspecialchars($hidden_email);
                                        ?>
                                    <?php else: ?>
                                        N/A
                                    <?php endif; ?>
                                </p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-600">Sender Address</p>
                                <p class="font-medium"><?php echo !empty($shipment['sender_address']) ? htmlspecialchars($shipment['sender_address']) : 'N/A'; ?></p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <?php else: ?>
            <!-- No shipment found -->
            <div class="bg-white rounded-xl shadow-md overflow-hidden text-center p-8">
                <div class="text-blue-600 mb-4">
                    <i class="fas fa-box-open text-5xl"></i>
                </div>
                <h3 class="text-xl font-semibold mb-2">Shipment Not Found</h3>
                <p class="text-gray-600 mb-6">The tracking number you entered doesn't match any shipments in our system.</p>
                <a href="track.html" class="inline-flex items-center bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-lg transition-colors">
                    <i class="fas fa-search mr-2"></i> Try Another Tracking Number
                </a>
            </div>
            <?php endif; ?>
        </div>
    </main>

    <script>
    // Function to copy tracking link
    function copyTrackingLink() {
        var copyText = document.getElementById("tracking-url");
        copyText.select();
        copyText.setSelectionRange(0, 99999);
        document.execCommand("copy");
        
        // Show feedback
        var originalText = document.querySelector("button.bg-blue-50").innerText;
        document.querySelector("button.bg-blue-50").innerText = "Copied!";
        setTimeout(function() {
            document.querySelector("button.bg-blue-50").innerText = originalText;
        }, 2000);
    }
    
    // Function to handle printing the receipt
    function printShippingReceipt() {
        // Make sure the print-only elements are visible before printing
        document.querySelector('.print-receipt').style.display = 'block';
        
        // Create a timestamp for the barcode if it's missing
        const barcodeElements = document.querySelectorAll('.print-barcode div');
        if (barcodeElements.length > 0) {
            if (!barcodeElements[0].textContent.trim()) {
                const trackingNumber = '<?php echo !empty($shipment) ? $shipment["tracking_number"] : ""; ?>';
                barcodeElements[0].textContent = '*' + trackingNumber + '*';
                barcodeElements[1].textContent = trackingNumber;
            }
        }
        
        // Add a slight delay before triggering print to ensure everything is rendered
        setTimeout(function() {
            window.print();
            
            // After printing, hide the print-only elements again
            setTimeout(function() {
                document.querySelector('.print-receipt').style.display = 'none';
            }, 1000);
        }, 300);
    }
    
    document.addEventListener('DOMContentLoaded', function() {
        // Only initialize map if element exists and we have shipment data
        const mapContainer = document.getElementById('map');
        if (mapContainer && <?php echo !empty($shipment) ? 'true' : 'false'; ?>) {
            console.log('Map container found, initializing map...');
            
            // Add a slight delay to ensure the DOM is fully rendered
            setTimeout(function() {
                try {
                    // Initialize the map with better styling
                    var map = L.map('map', {
                        zoomControl: true,
                        scrollWheelZoom: false,
                        attributionControl: true
                    }).setView([0, 0], 2);
                    
                    console.log('Map object created');
                    
                    // Use a reliable tile provider with retries
                    var tileLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
                        maxZoom: 19,
                        errorTileUrl: 'https://cdn.jsdelivr.net/gh/leaflet/Leaflet@1.9.4/dist/images/marker-icon.png'
                    });
                    
                    // Handle tile error
                    tileLayer.on('tileerror', function(error) {
                        console.warn('Tile could not be loaded:', error);
                    });
                    
                    // Add the tile layer to the map
                    tileLayer.addTo(map);
                    
                    console.log('Tile layer added');

                    // Get tracking updates and shipment info from PHP
                    var shipment = <?php echo $shipment_json; ?>;
                    var trackingUpdates = <?php echo $tracking_updates_json; ?>;
                    var locationHistory = <?php echo $location_history_json; ?>;
                    
                    console.log('Shipment data loaded:', shipment.tracking_number);
                    console.log('Tracking updates count:', trackingUpdates.length);
                    console.log('Location history:', locationHistory);

                    // Force a resize event to ensure the map renders properly
                    setTimeout(function() {
                        console.log('Triggering map resize');
                        map.invalidateSize();
                    }, 200);

                    // Custom Origin Icon
                    var originIcon = L.divIcon({
                        className: 'custom-div-icon',
                        html: `<div style="background-color: #2563EB; color: white; width: 30px; height: 30px; border-radius: 50%; display: flex; align-items: center; justify-content: center; box-shadow: 0 0 0 5px rgba(37, 99, 235, 0.2);"><i class="fas fa-warehouse" style="font-size: 14px;"></i></div>`,
                        iconSize: [30, 30],
                        iconAnchor: [15, 15]
                    });

                    // Custom Destination Icon
                    var destinationIcon = L.divIcon({
                        className: 'custom-div-icon',
                        html: `<div style="background-color: #059669; color: white; width: 30px; height: 30px; border-radius: 50%; display: flex; align-items: center; justify-content: center; box-shadow: 0 0 0 5px rgba(5, 150, 105, 0.2);"><i class="fas fa-flag-checkered" style="font-size: 14px;"></i></div>`,
                        iconSize: [30, 30],
                        iconAnchor: [15, 15]
                    });

                    // Custom Waypoint Icon
                    var waypointIcon = L.divIcon({
                        className: 'custom-div-icon',
                        html: `<div style="background-color: #4F46E5; color: white; width: 26px; height: 26px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: bold;">•</div>`,
                        iconSize: [26, 26],
                        iconAnchor: [13, 13]
                    });

                    // Custom Current Location Icon
                    var currentLocationIcon = L.divIcon({
                        className: 'custom-div-icon',
                        html: `<div style="background-color: #DC2626; color: white; width: 30px; height: 30px; border-radius: 50%; display: flex; align-items: center; justify-content: center; box-shadow: 0 0 0 5px rgba(220, 38, 38, 0.2);"><i class="fas fa-truck" style="font-size: 14px;"></i></div>`,
                        iconSize: [30, 30],
                        iconAnchor: [15, 15]
                    });

                    var markers = [];
                    var routePoints = [];
                    
                    // Process location history to add markers and route points
                    locationHistory.forEach(function(location, index) {
                        // Skip if lat/lng are zeros or not provided
                        if ((!location.lat && !location.lng) || 
                            (location.lat === 0 && location.lng === 0)) {
                            console.log('Skipping location with missing coordinates:', location.name);
                            return;
                        }
                        
                        var coords = [location.lat, location.lng];
                        routePoints.push(coords);
                        
                        console.log('Adding location:', location.name, coords);
                        
                        // Determine which icon to use
                        var markerIcon;
                        if (index === 0) {
                            markerIcon = originIcon;
                        } else if (index === locationHistory.length - 1) {
                            markerIcon = destinationIcon;
                        } else if (location.name === shipment.current_location) {
                            markerIcon = currentLocationIcon;
                        } else {
                            markerIcon = waypointIcon;
                        }
                        
                        // Create marker
                        var marker = L.marker(coords, {icon: markerIcon}).addTo(map);
                        
                        // Create popup content
                        var popupContent = `<div class="p-2">
                            <strong>${location.name || 'Location'}</strong><br>
                            <span class="text-sm">${location.status || 'Status Update'}</span><br>
                            <span class="text-xs">${location.date || 'Date unknown'}</span>`;
                        
                        if (location.description) {
                            popupContent += `<p class="text-sm mt-1">${location.description}</p>`;
                        }
                        
                        popupContent += `</div>`;
                        
                        marker.bindPopup(popupContent);
                        markers.push(marker);
                    });

                    // Draw route line if we have enough points
                    if (routePoints.length >= 2) {
                        console.log('Drawing route with points:', routePoints);
                        
                        // Main route line
                        var route = L.polyline(routePoints, {
                            color: '#3B82F6',
                            weight: 4,
                            opacity: 0.7
                        }).addTo(map);
                        
                        // Create bounds and fit map to the route
                        var bounds = L.latLngBounds(routePoints);
                        map.fitBounds(bounds, {
                            padding: [50, 50]
                        });
                    } else {
                        console.log('Not enough points for route:', routePoints.length);
                        
                        // Center on a default location if we don't have a route
                        map.setView([40.7128, -74.006], 4);
                    }
                    
                    // Make sure map is visible
                    map.invalidateSize();
                    
                } catch (error) {
                    console.error('Error initializing map:', error);
                    mapContainer.innerHTML = '<div class="p-4 text-red-600 text-center">' +
                        '<p class="font-semibold mb-2">Map Loading Error</p>' +
                        '<p>There was a problem loading the shipment map. Please try refreshing the page.</p>' +
                        '<p class="text-xs mt-2 text-gray-600">Technical details: ' + error.message + '</p>' +
                        '</div>';
                }
            }, 300); // Delay map initialization slightly
        } else {
            console.log('Map container not found or no shipment data');
        }
    });
    </script>
    
    <!-- Footer -->
    <footer class="bg-gray-800 text-white py-10 mt-16">
        <div class="container mx-auto px-4">
            <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
                <div>
                    <h3 class="text-xl font-bold mb-4">Global Freight</h3>
                    <p class="text-gray-400 mb-4">Reliable shipping solutions for businesses and individuals worldwide.</p>
                    <div class="flex space-x-4">
                        <a href="#" class="text-gray-400 hover:text-white transition-colors">
                            <i class="fab fa-facebook-f"></i>
                        </a>
                        <a href="#" class="text-gray-400 hover:text-white transition-colors">
                            <i class="fab fa-twitter"></i>
                        </a>
                        <a href="#" class="text-gray-400 hover:text-white transition-colors">
                            <i class="fab fa-instagram"></i>
                        </a>
                        <a href="#" class="text-gray-400 hover:text-white transition-colors">
                            <i class="fab fa-linkedin-in"></i>
                        </a>
                    </div>
                </div>
                
                <div>
                    <h3 class="font-semibold mb-4">Services</h3>
                    <ul class="space-y-2">
                        <li><a href="#" class="text-gray-400 hover:text-white transition-colors">Express Shipping</a></li>
                        <li><a href="#" class="text-gray-400 hover:text-white transition-colors">International Delivery</a></li>
                        <li><a href="#" class="text-gray-400 hover:text-white transition-colors">Freight Services</a></li>
                        <li><a href="#" class="text-gray-400 hover:text-white transition-colors">Bulk Shipping</a></li>
                    </ul>
                </div>
                
                <div>
                    <h3 class="font-semibold mb-4">Contact Info</h3>
                    <address class="not-italic text-gray-400 space-y-2">
                        <p><i class="fas fa-envelope mr-2 text-gray-300"></i> support@globalfreight.com</p>
                    </address>
                </div>
            </div>
            
            <div class="border-t border-gray-700 mt-8 pt-8 flex flex-col md:flex-row justify-between items-center">
                <p class="text-gray-400">&copy; <?php echo date('Y'); ?> Global Freight. All rights reserved.</p>
            </div>
        </div>
    </footer>
</body>
</html>