<?php
// Start the session
session_start();

// Check if user is logged in
if (!isset($_SESSION["username"]) || empty($_SESSION["username"])) {
    // User is not logged in, redirect to login page
    $_SESSION["error_message"] = "Please log in to access the dashboard.";
    header("Location: admin_login.php");
    exit();
}

// If we reach here, the user is logged in
$username = $_SESSION["username"];

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

require 'src/Exception.php';
require 'src/PHPMailer.php';
require 'src/SMTP.php';
require '../db.php'; // Database connection

// Function to generate receipt HTML
function generateReceiptHTML($shipment_data) {
    return '
    <div class="receipt-container">
        <div class="receipt" id="receipt-content">
            <!-- Premium Header -->
            <div class="receipt-header">
                <div class="header-decoration"></div>
                <div class="company-branding">
                    <div class="logo-container">
                        <i class="fas fa-dove logo-main"></i>
                    </div>
                    <div class="company-info">
                        <h1>Gooselyte Express</h1>
                        <p class="company-tagline">Excellence in Global Logistics</p>
                        <p class="receipt-title">Premium Shipping Documentation</p>
                    </div>
                </div>
                <div class="header-watermark">CONFIDENTIAL</div>
            </div>
            
            <!-- Receipt Body -->
            <div class="receipt-body">
                <!-- Document Summary -->
                <div class="document-summary">
                    <div class="summary-card">
                        <h3><i class="fas fa-file-contract"></i> Document Summary</h3>
                        <div class="summary-grid">
                            <div>
                                <span class="summary-label">Reference Number</span>
                                <span class="summary-value">GG-' . strtoupper(uniqid()) . '</span>
                            </div>
                            <div>
                                <span class="summary-label">Issued On</span>
                                <span class="summary-value">' . date('F j, Y') . '</span>
                            </div>
                            <div>
                                <span class="summary-label">Document Type</span>
                                <span class="summary-value">Shipping Manifest</span>
                            </div>
                            <div>
                                <span class="summary-label">Status</span>
                                <span class="summary-value badge-processing">' . htmlspecialchars($shipment_data['status']) . '</span>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Tracking Section -->
                <div class="tracking-section">
                    <div class="tracking-info">
                        <h3><i class="fas fa-map-marked-alt"></i> Shipment Tracking</h3>
                        <div class="tracking-details">
                            <div class="tracking-number-container">
                                <span class="tracking-label">Tracking Identifier:</span>
                                <span class="tracking-number">' . htmlspecialchars($shipment_data['tracking_number']) . '</span>
                                <span class="copy-tracking" onclick="navigator.clipboard.writeText(\'' . htmlspecialchars($shipment_data['tracking_number']) . '\')">
                                    <i class="fas fa-copy"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="qr-section">
                        <div class="qr-code-placeholder">
                            <img src="stamp.png" width="200" style="transform: translateX(-10px); opacity: 0.95;">
                        </div>
                    </div>
                </div>
                
                <!-- Shipment Details -->
                <div class="shipment-details">
                    <div class="section-header">
                        <h3><i class="fas fa-shipping-fast"></i> Consignment Details</h3>
                        <div class="section-divider"></div>
                    </div>
                    
                    <div class="details-grid">
                        <!-- Sender Details -->
                        <div class="detail-card card-sender">
                            <div class="card-header">
                                <i class="fas fa-user-tie"></i>
                                <h4>Consignor Information</h4>
                            </div>
                            <div class="card-body">
                                <div class="detail-row">
                                    <span class="detail-label">Full Name:</span>
                                    <span class="detail-value">' . htmlspecialchars($shipment_data['sender_name']) . '</span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Origin:</span>
                                    <span class="detail-value">' . htmlspecialchars($shipment_data['origin']) . '</span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Contact:</span>
                                    <span class="detail-value">' . htmlspecialchars($shipment_data['sender_phone']) . '</span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Receiver Details -->
                        <div class="detail-card card-receiver">
                            <div class="card-header">
                                <i class="fas fa-user"></i>
                                <h4>Consignee Information</h4>
                            </div>
                            <div class="card-body">
                                <div class="detail-row">
                                    <span class="detail-label">Full Name:</span>
                                    <span class="detail-value">' . htmlspecialchars($shipment_data['receiver_name']) . '</span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Destination:</span>
                                    <span class="detail-value">' . htmlspecialchars($shipment_data['destination']) . '</span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Delivery Address:</span>
                                    <span class="detail-value">' . htmlspecialchars($shipment_data['receiver_address']) . '</span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Contact:</span>
                                    <span class="detail-value">' . htmlspecialchars($shipment_data['receiver_phone']) . '</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Package Specifications -->
                <div class="package-specs">
                    <div class="section-header">
                        <h3><i class="fas fa-box-open"></i> Package Specifications</h3>
                        <div class="section-divider"></div>
                    </div>
                    
                    <table class="specs-table">
                        <thead>
                            <tr>
                                <th><i class="fas fa-map-marker-alt"></i> Origin</th>
                                <th><i class="fas fa-map-pin"></i> Destination</th>
                                <th><i class="fas fa-calendar-check"></i> Expected Departure Date</th>
                                <th><i class="fas fa-boxes"></i> Quantity</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>' . htmlspecialchars($shipment_data['origin']) . '</td>
                                <td>' . htmlspecialchars($shipment_data['destination']) . '</td>
                                <td>' . htmlspecialchars($shipment_data['departure_date']) . '</td>
                                <td>' . htmlspecialchars($shipment_data['quantity']) . '</td>
                            </tr>
                        </tbody>
                    </table>
                    <table class="specs-table">
                        <thead>
                            <tr>
                                <th><i class="fas fa-tag"></i> Type</th>
                                <th><i class="fas fa-weight-hanging"></i> Weight</th>
                                <th><i class="fas fa-ruler-combined"></i> Dimensions</th>
                                <th><i class="fas fa-money-bill-wave"></i> Shipping Cost</th>
                                <th><i class="fas fa-calendar-check"></i> Expected Delivery</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>' . htmlspecialchars($shipment_data['shipment_type']) . '</td>
                                <td>' . htmlspecialchars($shipment_data['weight']) . ' kg</td>
                                <td>Standard</td>
                                <td>$' . htmlspecialchars($shipment_data['value']) . '</td>
                                <td>' . htmlspecialchars($shipment_data['delivery_date']) . '</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                
                <!-- Service Information -->
                <div class="service-info">
                    <div class="section-header">
                        <h3><i class="fas fa-concierge-bell"></i> Service Information</h3>
                        <div class="section-divider"></div>
                    </div>
                    
                    <div class="service-grid">
                        <div class="service-card">
                            <i class="fas fa-shield-alt"></i>
                            <h5>Security Level</h5>
                            <p>Standard Verification</p>
                        </div>
                        <div class="service-card">
                            <i class="fas fa-stopwatch"></i>
                            <h5>Delivery Speed</h5>
                            <p>Express (2-3 business days)</p>
                        </div>
                        <div class="service-card">
                            <i class="fas fa-hand-holding-usd"></i>
                            <h5>Insurance</h5>
                            <p>Basic Coverage</p>
                        </div>
                        <div class="service-card">
                            <i class="fas fa-bell"></i>
                            <h5>Notifications</h5>
                            <p>Email & SMS Updates</p>
                        </div>
                    </div>
                </div>
                
                <!-- Additional Notes -->
                ' . (!empty($shipment_data['note']) ? '
                <div class="notes-section">
                    <div class="section-header">
                        <h3><i class="fas fa-clipboard"></i> Special Instructions</h3>
                        <div class="section-divider"></div>
                    </div>
                    <div class="notes-content">
                        <p>' . htmlspecialchars($shipment_data['note']) . '</p>
                    </div>
                </div>' : '') . '
                
                <!-- Terms Acceptance -->
                <div class="terms-section">
                    <div class="terms-content">
                        <i class="fas fa-file-signature"></i>
                        <p>By submitting this shipment, the consignor acknowledges and agrees to all terms and conditions outlined in the Gooselyte Express service agreement. This includes but is not limited to liability limitations, prohibited items, and customs regulations.</p>
                    </div>
                </div>
            </div>
            
            <!-- Elegant Footer -->
            <div class="receipt-footer">
                <div class="footer-content">
                    <div class="footer-brand">
                        <i class="fas fa-dove"></i>
                        <span>Gooselyte Express</span>
                    </div>
                    <div class="footer-meta">
                        <p>This document serves as your official receipt and shipment confirmation. Please retain for your records.</p>
                        <div class="footer-contacts">
                            <a href="https://gooselyte.com" class="contact-link">
                                <i class="fas fa-globe"></i> gooselyte.com
                            </a>
                            <a href="mailto:contact@gooselyte.com" class="contact-link">
                                <i class="fas fa-envelope"></i> contact@gooselyte.com
                            </a>
                            <a href="tel:+447387266821" class="contact-link">
                                <i class="fas fa-phone-alt"></i> +44 738 7266 821
                            </a>
                        </div>
                    </div>
                </div>
                <div class="footer-social">
                    <span>Our Partners:</span>
                    <div class="social-icons">
                        <a href="#"><i class="fab fa-cc-paypal fa-3x"></i></a>
                        <a href="#"><i class="fab fa-cc-visa fa-3x"></i></a>
                        <a href="#"><i class="fab fa-cc-mastercard fa-3x"></i></a>
                        <a href="#"><i class="fab fa-cc-amex fa-3x"></i></a>
                    </div>
                </div>
                <div class="footer-legal">
                    <p>© ' . date('Y') . ' Gooselyte Express. All rights reserved. All shipments are subject to our Terms of Service and Privacy Policy.</p>
                </div>
            </div>
        </div>
    </div>
    <style>
        /* All the CSS styles from your original receipt */
        :root {
            --primary: #2C3E50;
            --secondary: #3498DB;
            --accent: #E74C3C;
            --light: #ECF0F1;
            --dark: #2C3E50;
            --text: #34495E;
            --muted: #7F8C8D;
            --success: #27AE60;
            --warning: #F39C12;
            --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.12);
            --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1);
            --shadow-lg: 0 10px 25px rgba(0, 0, 0, 0.1);
            --border-radius: 8px;
            --border-radius-lg: 12px;
            --transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: "Crimson Pro", "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
        }

        .receipt-container {
            margin: 40px auto;
            width: 900px;
            background: white;
            border-radius: var(--border-radius-lg);
            overflow: hidden;
            box-shadow: var(--shadow-lg);
            position: relative;
            border: 1px solid rgba(0, 0, 0, 0.05);
        }

        /* Premium Header Styles */
        .receipt-header {
            background: linear-gradient(135deg, var(--primary), var(--dark));
            color: white;
            padding: 40px 30px 30px;
            text-align: center;
            position: relative;
            overflow: hidden;
        }

        .header-decoration {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 5px;
            background: linear-gradient(90deg, var(--accent), var(--secondary));
        }

        .company-branding {
            display: flex;
            flex-direction: column;
            align-items: center;
            position: relative;
            z-index: 2;
        }

        .logo-container {
            width: 80px;
            height: 80px;
            background: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 20px;
            box-shadow: var(--shadow-sm);
        }

        .logo-main {
            font-size: 36px;
            color: var(--secondary);
        }

        .company-info h1 {
            font-size: 32px;
            font-weight: 600;
            margin-bottom: 5px;
            letter-spacing: 0.5px;
        }

        .company-tagline {
            font-size: 14px;
            opacity: 0.9;
            margin-bottom: 10px;
            font-style: italic;
        }

        .receipt-title {
            font-size: 16px;
            text-transform: uppercase;
            letter-spacing: 2px;
            margin-top: 15px;
            opacity: 0.8;
        }

        .header-watermark {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 120px;
            font-weight: 900;
            opacity: 0.05;
            color: white;
            pointer-events: none;
            user-select: none;
        }

        /* Receipt Body Styles */
        .receipt-body {
            padding: 40px;
            background: white;
        }

        /* Document Summary */
        .document-summary {
            margin-bottom: 30px;
        }

        .summary-card {
            background: var(--light);
            padding: 20px;
            border-radius: var(--border-radius);
            border-left: 4px solid var(--secondary);
        }

        .summary-card h3 {
            color: var(--primary);
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 18px;
        }

        .summary-card h3 i {
            color: var(--accent);
        }

        .summary-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 15px;
        }

        .summary-label {
            display: block;
            font-size: 12px;
            color: var(--muted);
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 3px;
        }

        .summary-value {
            display: block;
            font-size: 16px;
            color: var(--dark);
            font-weight: 500;
        }

        .badge-processing {
            display: inline-block;
            padding: 3px 8px;
            background: var(--warning);
            color: white;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }

        /* Tracking Section */
        .tracking-section {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: white;
            padding: 20px;
            border-radius: var(--border-radius);
            margin-bottom: 30px;
            box-shadow: var(--shadow-sm);
            border: 1px solid rgba(0, 0, 0, 0.05);
        }

        .tracking-info h3 {
            color: var(--primary);
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 18px;
        }

        .tracking-info h3 i {
            color: var(--secondary);
        }

        .tracking-number-container {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 10px;
        }

        .tracking-label {
            font-size: 14px;
            color: var(--muted);
        }

        .tracking-number {
            font-size: 20px;
            font-weight: 600;
            color: var(--secondary);
            letter-spacing: 1px;
        }

        .copy-tracking {
            cursor: pointer;
            color: var(--secondary);
            transition: var(--transition);
        }

        .copy-tracking:hover {
            color: var(--accent);
        }

        .tracking-meta {
            display: flex;
            gap: 15px;
            font-size: 13px;
            color: var(--muted);
        }

        .tracking-meta i {
            margin-right: 5px;
        }

        .qr-section {
            text-align: center;
        }

        .qr-code-placeholder {
            width: 100px;
            height: 100px;
            background: var(--light);
            border-radius: var(--border-radius);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 5px;
            color: var(--secondary);
            font-size: 40px;
        }

        .qr-caption {
            font-size: 12px;
            color: var(--muted);
        }

        /* Section Header */
        .section-header {
            margin: 30px 0 20px;
            position: relative;
        }

        .section-header h3 {
            color: var(--primary);
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 18px;
        }

        .section-header h3 i {
            color: var(--accent);
        }

        .section-divider {
            height: 1px;
            background: linear-gradient(90deg, transparent, rgba(0, 0, 0, 0.1), transparent);
            margin-top: 10px;
        }

        /* Shipment Details */
        .details-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 30px;
        }

        .detail-card {
            background: white;
            border-radius: var(--border-radius);
            overflow: hidden;
            box-shadow: var(--shadow-sm);
            border: 1px solid rgba(0, 0, 0, 0.05);
            transition: var(--transition);
        }

        .detail-card:hover {
            transform: translateY(-3px);
            box-shadow: var(--shadow-md);
        }

        .card-header {
            background: var(--primary);
            padding: 15px 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        }

        .card-header h4 {
            font-size: 16px;
            color: var(--light);
            font-weight: 500;
        }

        .card-header i {
            color: var(--light);
            font-size: 18px;
        }

        .card-body {
            padding: 20px;
        }

        .detail-row {
            display: flex;
            margin-bottom: 12px;
        }

        .detail-label {
            width: 120px;
            font-size: 13px;
            color: var(--muted);
            flex-shrink: 0;
        }

        .detail-value {
            font-size: 14px;
            color: var(--text);
            font-weight: 500;
        }

        /* Package Specifications */
        .specs-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            border-radius: var(--border-radius);
            overflow: hidden;
            box-shadow: var(--shadow-sm);
        }

        .specs-table th, .specs-table td {
            padding: 15px;
            text-align: left;
            font-size: 14px;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        }

        .specs-table th {
            background: var(--primary);
            color: var(--light);
            font-weight: 500;
            text-transform: uppercase;
            font-size: 12px;
            letter-spacing: 0.5px;
        }

        .specs-table th i {
            margin-right: 8px;
            color: var(--sec);
        }

        .specs-table td {
            color: var(--text);
            font-weight: 500;
        }

        /* Service Information */
        .service-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 15px;
            margin-top: 20px;
        }

        .service-card {
            background: white;
            padding: 20px;
            border-radius: var(--border-radius);
            text-align: center;
            box-shadow: var(--shadow-sm);
            transition: var(--transition);
        }

        .service-card:hover {
            transform: translateY(-3px);
            box-shadow: var(--shadow-md);
        }

        .service-card i {
            font-size: 24px;
            color: var(--secondary);
            margin-bottom: 10px;
        }

        .service-card h5 {
            font-size: 14px;
            color: var(--primary);
            margin-bottom: 5px;
        }

        .service-card p {
            font-size: 13px;
            color: var(--muted);
        }

        /* Notes Section */
        .notes-section {
            margin-top: 30px;
        }

        .notes-content {
            background: #FFF9E6;
            padding: 15px 20px;
            border-radius: var(--border-radius);
            border-left: 4px solid var(--warning);
            font-size: 14px;
            line-height: 1.6;
            color: var(--text);
        }

        /* Terms Section */
        .terms-section {
            margin-top: 40px;
            background: var(--light);
            padding: 20px;
            border-radius: var(--border-radius);
            display: flex;
            gap: 15px;
            align-items: center;
        }

        .terms-section i {
            font-size: 24px;
            color: var(--muted);
            flex-shrink: 0;
        }

        .terms-section p {
            font-size: 12px;
            color: var(--muted);
            line-height: 1.6;
        }

        /* Elegant Footer */
        .receipt-footer {
            background: var(--primary);
            color: white;
            padding: 30px 40px;
        }

        .footer-content {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
        }

        .footer-brand {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 18px;
            font-weight: 500;
        }

        .footer-brand i {
            color: var(--secondary);
        }

        .footer-meta p {
            font-size: 13px;
            opacity: 0.8;
            width: 400px;
            margin-bottom: 10px;
        }

        .footer-contacts {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .contact-link {
            color: white;
            opacity: 0.8;
            font-size: 13px;
            text-decoration: none;
            transition: var(--transition);
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .contact-link:hover {
            opacity: 1;
            color: var(--secondary);
        }

        .footer-social {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 0;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            margin-bottom: 15px;
        }

        .footer-social span {
            font-size: 13px;
            opacity: 0.8;
        }

        .social-icons {
            display: flex;
            gap: 30px;
        }

        .social-icons a {
            color: white;
            opacity: 0.6;
            transition: var(--transition);
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.1);
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .social-icons a:hover {
            opacity: 1;
            background: var(--secondary);
        }

        .footer-legal {
            text-align: center;
            font-size: 11px;
            opacity: 0.6;
        }

        /* Download Button */
        .download-section {
            text-align: center;
            margin: 30px 0;
        }

        .btn-download {
            background: linear-gradient(135deg, var(--secondary), var(--primary));
            color: white;
            padding: 14px 28px;
            border: none;
            border-radius: 50px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            transition: var(--transition);
            box-shadow: 0 4px 15px rgba(52, 152, 219, 0.3);
        }

        .btn-download:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(52, 152, 219, 0.4);
        }

        @media print {
            .receipt-container {
                box-shadow: none;
                border: none;
                margin: 0;
                width: 100%;
            }

            .btn-download, .alert-success {
                display: none;
            }

            .receipt-footer {
                page-break-inside: avoid;
            }
        }
    </style>';
}

// Function to display receipt with download options
function displayReceiptWithDownload($shipment_data, $success_message) {
    $receipt_html = generateReceiptHTML($shipment_data);
    
    // Add external dependencies
    echo '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">';
    echo '<link href="https://fonts.googleapis.com/css2?family=Crimson+Pro:wght@400;500;600;700&family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet">';
    echo '<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>';
    echo '<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>';
    echo '<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.28/jspdf.plugin.autotable.min.js"></script>';
    
    echo '<script>
        // Improved download as PNG function
        function downloadReceiptPNG() {
            const element = document.getElementById("receipt-content");
            const options = {
                scale: 3, // Increased scale for better quality
                logging: true,
                useCORS: true,
                allowTaint: true,
                letterRendering: true,
                quality: 1, // Highest quality
                backgroundColor: "#FFFFFF",
                windowWidth: element.scrollWidth,
                windowHeight: element.scrollHeight
            };
            
            // Show loading indicator
            const downloadBtn = document.querySelector(".btn-download-png");
            const originalText = downloadBtn.innerHTML;
            downloadBtn.innerHTML = \'<i class="fas fa-spinner fa-spin"></i> Generating...\';
            
            html2canvas(element, options).then(canvas => {
                const link = document.createElement("a");
                link.download = "Gooselyte _Express_Receipt_' . htmlspecialchars($shipment_data['tracking_number']) . '.png";
                link.href = canvas.toDataURL("image/png", 1.0);
                link.click();
                
                // Restore button text
                downloadBtn.innerHTML = originalText;
            }).catch(error => {
                console.error("Error generating receipt image:", error);
                alert("Failed to download receipt. Please try again.");
                downloadBtn.innerHTML = originalText;
            });
        }
        
        // Download as PDF function
        function downloadReceiptPDF() {
            const { jsPDF } = window.jspdf;
            const doc = new jsPDF({
                orientation: "portrait",
                unit: "mm",
                format: "a4"
            });
            
            const element = document.getElementById("receipt-content");
            const options = {
                scale: 3,
                useCORS: true,
                allowTaint: true,
                letterRendering: true,
                quality: 1,
                backgroundColor: "#FFFFFF",
                windowWidth: element.scrollWidth,
                windowHeight: element.scrollHeight
            };
            
            // Show loading indicator
            const downloadBtn = document.querySelector(".btn-download-pdf");
            const originalText = downloadBtn.innerHTML;
            downloadBtn.innerHTML = \'<i class="fas fa-spinner fa-spin"></i> Generating...\';
            
            html2canvas(element, options).then(canvas => {
                const imgData = canvas.toDataURL("image/png", 1.0);
                const imgWidth = 210; // A4 width in mm
                const pageHeight = 295; // A4 height in mm
                const imgHeight = canvas.height * imgWidth / canvas.width;
                let heightLeft = imgHeight;
                let position = 0;
                
                doc.addImage(imgData, "PNG", 0, position, imgWidth, imgHeight);
                heightLeft -= pageHeight;
                
                while (heightLeft >= 0) {
                    position = heightLeft - imgHeight;
                    doc.addPage();
                    doc.addImage(imgData, "PNG", 0, position, imgWidth, imgHeight);
                    heightLeft -= pageHeight;
                }
                
                doc.save("Gooselyte _Express_Receipt_' . htmlspecialchars($shipment_data['tracking_number']) . '.pdf");
                
                // Restore button text
                downloadBtn.innerHTML = originalText;
            }).catch(error => {
                console.error("Error generating PDF:", error);
                alert("Failed to generate PDF. Please try again.");
                downloadBtn.innerHTML = originalText;
            });
        }
    </script>';
    
    // Display success message and receipt
    echo '<div class="alert alert-success" style="background: #27AE60; color: white; padding: 15px; border-radius: 4px; margin: 20px auto; width: 900px; text-align: center;">
            <i class="fas fa-check-circle"></i> ' . htmlspecialchars($success_message) . '
          </div>';
    echo $receipt_html;
    echo '<div class="download-section" style="text-align: center; margin: 30px auto; width: 900px; display: flex; justify-content: center; gap: 15px;">
            <button onclick="downloadReceiptPNG()" class="btn-download-png" style="background: linear-gradient(135deg, #3498DB, #2C3E50); color: white; padding: 12px 24px; border: none; border-radius: 50px; font-size: 16px; cursor: pointer; display: inline-flex; align-items: center; gap: 10px; transition: all 0.3s ease; box-shadow: 0 4px 15px rgba(52, 152, 219, 0.3);">
                <i class="fas fa-file-image"></i> Download as PNG
            </button>
            <button onclick="downloadReceiptPDF()" class="btn-download-pdf" style="background: linear-gradient(135deg, #E74C3C, #C0392B); color: white; padding: 12px 24px; border: none; border-radius: 50px; font-size: 16px; cursor: pointer; display: inline-flex; align-items: center; gap: 10px; transition: all 0.3s ease; box-shadow: 0 4px 15px rgba(231, 76, 60, 0.3);">
                <i class="fas fa-file-pdf"></i> Download as PDF
            </button>
          </div>';
}

// Handle form submission for new shipment
if (isset($_POST['submit_shipment'])) {
    // Collect form data
    $sender_name       = mysqli_real_escape_string($connection, $_POST['sender_name']);
    $sender_address    = mysqli_real_escape_string($connection, $_POST['sender_address']);
    $sender_phone      = mysqli_real_escape_string($connection, $_POST['sender_phone']);
    
    $receiver_name     = mysqli_real_escape_string($connection, $_POST['receiver_name']);
    $receiver_address  = mysqli_real_escape_string($connection, $_POST['receiver_address']);
    $receiver_phone    = mysqli_real_escape_string($connection, $_POST['receiver_phone']);
    $receiver_email    = mysqli_real_escape_string($connection, $_POST['receiver_email'] ?? '');
    
    $weight            = mysqli_real_escape_string($connection, $_POST['weight']);
    $shipment_type     = mysqli_real_escape_string($connection, $_POST['shipment_type']);
    $origin            = mysqli_real_escape_string($connection, $_POST['origin']);
    $destination       = mysqli_real_escape_string($connection, $_POST['destination']);
    $note              = mysqli_real_escape_string($connection, $_POST['note']);
    $value             = mysqli_real_escape_string($connection, $_POST['value']);
    $quantity          = mysqli_real_escape_string($connection, $_POST['quantity']); 
    $current_location  = mysqli_real_escape_string($connection, $_POST['current_location']);

    // Generate tracking number if not provided
    $tracking_number = !empty($_POST['tracking_number']) 
        ? mysqli_real_escape_string($connection, $_POST['tracking_number']) 
        : 'TRK' . strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 8));

    // NEW FIELD: departure date
    $departure_date    = mysqli_real_escape_string($connection, $_POST['departure_date']);
    
    $delivery_date     = mysqli_real_escape_string($connection, $_POST['delivery_date']);
    $status            = mysqli_real_escape_string($connection, $_POST['status']);
    
    // ✅ Updated INSERT query to include departure_date
    $query = "INSERT INTO shipments (
                sender_name, sender_address, sender_phone, 
                receiver_name, receiver_address, receiver_phone, receiver_email,
                weight, shipment_type, origin, destination, tracking_number, 
                departure_date, delivery_date, status, 
                value, quantity, current_location, note, created_at
              ) VALUES (
                '$sender_name', '$sender_address', '$sender_phone', 
                '$receiver_name', '$receiver_address', '$receiver_phone', '$receiver_email',
                '$weight', '$shipment_type', '$origin', '$destination', '$tracking_number', 
                '$departure_date', '$delivery_date', '$status', 
                '$value', '$quantity', '$current_location', '$note', NOW()
              )";

    $result = mysqli_query($connection, $query);
    
    if ($result) {
        $success_message = "Shipment successfully registered with Gooselyte Express";
        
        // Prepare shipment data for receipt
        $shipment_data = [
            'sender_name' => $sender_name,
            'sender_address' => $sender_address,
            'sender_phone' => $sender_phone,
            'receiver_name' => $receiver_name,
            'receiver_address' => $receiver_address,
            'receiver_phone' => $receiver_phone,
            'receiver_email' => $receiver_email,
            'weight' => $weight,
            'shipment_type' => $shipment_type,
            'origin' => $origin,
            'destination' => $destination,
            'tracking_number' => $tracking_number,
            'departure_date' => $departure_date,
            'delivery_date' => $delivery_date,
            'status' => $status,
            'value' => $value,
            'quantity' => $quantity,
            'current_location' => $current_location,
            'note' => $note
        ];
        
        // Display receipt with download options
        displayReceiptWithDownload($shipment_data, $success_message);
 
        // Continue with existing email notification code
        if (empty($receiver_email)) {
            $email_error = "Receiver email is empty. No email was sent.";
        } else {
            // Send email notification to receiver
            $mail = new PHPMailer(true); // Enable exceptions

            try {
                // Server settings
                $mail->isSMTP();
                $mail->Host = 'mail.gooselyte.com'; // SMTP server
                $mail->SMTPAuth = true;
                $mail->Username = 'contact@gooselyte.com'; // SMTP username
                $mail->Password = 'bigg369@'; // SMTP password
                $mail->SMTPSecure = 'ssl'; // Enable SSL encryption
                $mail->Port = 465; // TCP port to connect to

                // Recipients
                $mail->setFrom('contact@gooselyte.com', 'Gooselyte Express');
                $mail->addAddress($receiver_email, $receiver_name); // Add a recipient

                // Content
                $mail->isHTML(true); // Set email format to HTML
                $mail->Subject = 'You have a package incoming!';

                // Define the email body
                $mailBody = '
                    <!DOCTYPE html>
                    <html>
                    <head>
                        <style>
                            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                            .header { background-color: #0056b3; color: white; padding: 15px; text-align: center; }
                            .content { padding: 20px; border: 1px solid #ddd; }
                            .tracking-number { font-weight: bold; color: #0056b3; font-size: 18px; }
                            .details { margin: 15px 0; }
                            .details table { width: 100%; border-collapse: collapse; }
                            .details table th, .details table td { padding: 8px; text-align: left; border-bottom: 1px solid #ddd; }
                            .details table th { width: 40%; }
                            .footer { margin-top: 20px; font-size: 12px; color: #666; text-align: center; }
                            .note-box { background-color: #f0f8ff; padding: 10px; border-left: 3px solid #0056b3; margin: 10px 0; }
                        </style>
                    </head>
                    <body>
                        <div class="container">
                            <div class="header">
                                <h2>Shipment Notification</h2>
                            </div>
                            <div class="content">
                                <p>Dear ' . htmlspecialchars($receiver_name) . ',</p>
                                
                                <p>We are pleased to inform you that a package has been shipped to you. Below are the details of your shipment:</p>
                                
                                <p>Your Tracking Number: <span class="tracking-number">' . htmlspecialchars($tracking_number) . '</span></p>
                                
                                ' . (!empty($note) ? '<div class="note-box"><strong>Note:</strong> ' . htmlspecialchars($note) . '</div>' : '') . '
                                
                                <div class="details">
                                    <table>
                                        <tr>
                                            <th>Sender:</th>
                                            <td>' . htmlspecialchars($sender_name) . '</td>
                                        </tr>
                                        <tr>
                                            <th>Origin:</th>
                                            <td>' . htmlspecialchars($origin) . '</td>
                                        </tr>
                                        <tr>
                                            <th>Destination:</th>
                                            <td>' . htmlspecialchars($destination) . '</td>
                                        </tr>
                                        <tr>
                                            <th>Delivery Address:</th>
                                            <td>' . htmlspecialchars($receiver_address) . '</td>
                                        </tr>
                                        <tr>
                                            <th>Package Type:</th>
                                            <td>' . htmlspecialchars($shipment_type) . '</td>
                                        </tr>
                                        <tr>
                                            <th>Weight:</th>
                                            <td>' . htmlspecialchars($weight) . ' kg</td>
                                        </tr>
                                        <tr>
                                            <th>Expected Delivery Date:</th>
                                            <td>' . htmlspecialchars($delivery_date) . '</td>
                                        </tr>
                                        <tr>
                                            <th>Current Status:</th>
                                            <td>' . htmlspecialchars($status) . '</td>
                                        </tr>
                                    </table>
                                </div>
                                
                                <p>You can track your shipment status by visiting our website and entering your tracking number.</p>
                                
                                <p>If you have any questions regarding your shipment, please contact our customer service team.</p>
                                
                                <p>Thank you for your business!</p>
                                
                                <p>Best regards,<br>
                                The Shipping Team</p>
                            </div>
                            <div class="footer">
                                <p>This is an automated message. Please do not reply to this email.</p>
                                <p>© ' . date('Y') . ' Gooselyte Express. All rights reserved.</p>
                            </div>
                        </div>
                    </body>
                    </html>
                ';

                $mail->Body = $mailBody;
                $mail->AltBody = strip_tags(str_replace(['<br>', '</p>'], ["\n", "\n\n"], $mailBody)); // Plain text version

                // Attempt to send the email and capture the result
                if (!$mail->send()) {
                    $email_error = "Email could not be sent. Mailer Error: {$mail->ErrorInfo}";
                } else {
                    $email_success = "Email notification sent to receiver ($receiver_email).";
                    $success_message .= " " . $email_success;
                }
            } catch (Exception $e) {
                $email_error = "Email sending exception: {$e->getMessage()}";
            }

            // Add email error to the page for debugging if it exists
            if (isset($email_error)) {
                $error_message = isset($error_message) ? $error_message . " " . $email_error : $email_error;
            }
        }
    } else {
        $error_message = "Error: " . mysqli_error($connection);
    }

    // Display any error messages
    if (isset($error_message)) {
        echo '<div class="alert alert-danger">' . htmlspecialchars($error_message) . '</div>';
    }
}

// Handle delete shipment
if (isset($_GET['delete']) && !empty($_GET['delete'])) {
    $id = mysqli_real_escape_string($connection, $_GET['delete']);
    $query = "DELETE FROM shipments WHERE id = '$id'";
    
    $result = mysqli_query($connection, $query);
    
    if ($result) {
        $success_message = "Shipment deleted successfully!";
    } else {
        $error_message = "Error deleting shipment: " . mysqli_error($connection);
    }
}

// Handle update shipment
if (isset($_POST['update_shipment'])) {
    $id = mysqli_real_escape_string($connection, $_POST['shipment_id']);
    
    $sender_name = mysqli_real_escape_string($connection, $_POST['sender_name']);
    $sender_address = mysqli_real_escape_string($connection, $_POST['sender_address']);
    $sender_phone = mysqli_real_escape_string($connection, $_POST['sender_phone']);
    
    $receiver_name = mysqli_real_escape_string($connection, $_POST['receiver_name']);
    $receiver_address = mysqli_real_escape_string($connection, $_POST['receiver_address']);
    $receiver_phone = mysqli_real_escape_string($connection, $_POST['receiver_phone']);
    $receiver_email = mysqli_real_escape_string($connection, isset($_POST['receiver_email']) ? $_POST['receiver_email'] : '');
    
    $weight = mysqli_real_escape_string($connection, $_POST['weight']);
    $shipment_type = mysqli_real_escape_string($connection, $_POST['shipment_type']);
    $origin = mysqli_real_escape_string($connection, $_POST['origin']);
    $destination = mysqli_real_escape_string($connection, $_POST['destination']);
    $tracking_number = mysqli_real_escape_string($connection, $_POST['tracking_number']);
    $delivery_date = mysqli_real_escape_string($connection, $_POST['delivery_date']);
    $current_location = mysqli_real_escape_string($connection, $_POST['current_location']);
    $status = mysqli_real_escape_string($connection, $_POST['status']);
    $note = mysqli_real_escape_string($connection, $_POST['note']); // Added note field
    $value = mysqli_real_escape_string($connection, $_POST['value']);
    $quantity = mysqli_real_escape_string($connection, $_POST['quantity']);
    $departure_date = mysqli_real_escape_string($connection, $_POST['departure_date']);
    
    $query = "UPDATE shipments SET 
                sender_name = '$sender_name', 
                sender_address = '$sender_address', 
                sender_phone = '$sender_phone', 
                receiver_name = '$receiver_name', 
                receiver_address = '$receiver_address', 
                receiver_phone = '$receiver_phone', 
                receiver_email = '$receiver_email',
                weight = '$weight', 
                shipment_type = '$shipment_type', 
                origin = '$origin', 
                destination = '$destination', 
                tracking_number = '$tracking_number', 
                delivery_date = '$delivery_date', 
                current_location = '$current_location', 
                status = '$status', 
                note = '$note',
                value = '$value',
                quantity = '$quantity',
                departure_date = '$departure_date',
                updated_at = NOW() 
              WHERE id = '$id'";
    
    $result = mysqli_query($connection, $query);
    
    if ($result) {
        $success_message = "Shipment updated successfully!";
        
        // Get the updated shipment data
        $query = "SELECT * FROM shipments WHERE id = '$id'";
        $result = mysqli_query($connection, $query);
        $shipment_data = mysqli_fetch_assoc($result);
        
        // Display receipt with download options
        displayReceiptWithDownload($shipment_data, $success_message);
    } else {
        $error_message = "Error updating shipment: " . mysqli_error($connection);
    }
}

// Get shipment data for edit
$edit_data = null;
if (isset($_GET['edit']) && !empty($_GET['edit'])) {
    $id = mysqli_real_escape_string($connection, $_GET['edit']);
    $query = "SELECT * FROM shipments WHERE id = '$id'";
    $result = mysqli_query($connection, $query);
    
    if ($result && mysqli_num_rows($result) > 0) {
        $edit_data = mysqli_fetch_assoc($result);
    }
}

// Check if the receiver_email field exists in the shipments table
$check_field_query = "SHOW COLUMNS FROM shipments LIKE 'receiver_email'";
$check_field_result = mysqli_query($connection, $check_field_query);
if (mysqli_num_rows($check_field_result) == 0) {
    // Field doesn't exist, add it
    $add_field_query = "ALTER TABLE shipments ADD COLUMN receiver_email VARCHAR(255) AFTER receiver_phone";
    mysqli_query($connection, $add_field_query);
    echo "<div style='background-color: #fff3cd; color: #856404; padding: 10px; margin-bottom: 15px; border: 1px solid #ffeeba; border-radius: 4px;'>
        Database updated: Added receiver_email field to shipments table.
    </div>";
}

// Check if the note field exists in the shipments table
$check_note_field_query = "SHOW COLUMNS FROM shipments LIKE 'note'";
$check_note_field_result = mysqli_query($connection, $check_note_field_query);
if (mysqli_num_rows($check_note_field_result) == 0) {
    // Field doesn't exist, add it
    $add_note_field_query = "ALTER TABLE shipments ADD COLUMN note TEXT AFTER status";
    mysqli_query($connection, $add_note_field_query);
    echo "<div style='background-color: #fff3cd; color: #856404; padding: 10px; margin-bottom: 15px; border: 1px solid #ffeeba; border-radius: 4px;'>
        Database updated: Added note field to shipments table.
    </div>";
}

// Fetch all shipments for display
$query = "SELECT * FROM shipments ORDER BY created_at DESC";
$all_shipments = mysqli_query($connection, $query);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Shipment Management Dashboard</title>
    <!-- Include modern CSS framework -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Include Font Awesome icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Custom CSS -->
    <style>
        :root {
            --primary-color: #3498db;
            --secondary-color: #2c3e50;
            --accent-color: #e74c3c;
            --light-bg: #f8f9fa;
            --dark-bg: #343a40;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }
        
        .dashboard-container {
            max-width: 1400px;
            margin: 0 auto;
        }
        
        .dashboard-header {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            padding: 1rem;
            border-radius: 0.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .card {
            border: none;
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px rgba(0,0,0,0.05);
            transition: transform 0.3s, box-shadow 0.3s;
            margin-bottom: 1.5rem;
        }
        
        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 15px rgba(0,0,0,0.1);
        }
        
        .card-header {
            background: var(--primary);
            color: var(--light);
            border-bottom: none;
            font-weight: 600;
        }
        
        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        
        .btn-primary:hover {
            background-color: #2980b9;
            border-color: #2980b9;
        }
        
        .btn-success {
            background-color: #2ecc71;
            border-color: #2ecc71;
        }
        
        .btn-success:hover {
            background-color: #27ae60;
            border-color: #27ae60;
        }
        
        .btn-danger {
            background-color: var(--accent-color);
            border-color: var(--accent-color);
        }
        
        .btn-danger:hover {
            background-color: #c0392b;
            border-color: #c0392b;
        }
        
        .shipment-table th {
            background-color: var(--secondary-color);
            color: white;
        }
        
        .shipment-table tr:nth-child(even) {
            background-color: #f8f9fa;
        }
        
        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.25rem rgba(52, 152, 219, 0.25);
        }
        
        .status-badge {
            padding: 0.35em 0.65em;
            border-radius: 0.25rem;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.75em;
        }
        
        .status-pending {
            background-color: #f39c12;
            color: white;
        }
        
        .status-pending {
            background-color: #f39c12 !important;
            color: white !important;
        }
        .status-transit {
            background-color: #3498db !important;
            color: white !important;
        }
        
         .status-processing {
            background-color: #3498db !important;
            color: white !important;
        }
        .status-shipped {
            background-color: #9b59b6 !important;
            color: white !important;
        }
        .status-delivered {
            background-color: #2ecc71 !important;
            color: white !important;
        }
        .status-hold {
            background-color: #e74c3c !important;
            color: white !important;
        }
        
        .form-label {
            font-weight: 500;
        }
        
        .section-title {
            border-left: 4px solid var(--primary-color);
            padding-left: 10px;
            margin-bottom: 1.5rem;
        }
        
        .action-buttons .btn {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }
        
        /* Responsive Tables */
        @media (max-width: 992px) {
            .table-responsive-stack tr {
                display: flex;
                flex-direction: column;
                border-bottom: 3px solid #ddd;
                margin-bottom: 1rem;
            }
            .table-responsive-stack td {
                display: flex;
                padding: 10px 8px;
            }
            .table-responsive-stack td:before {
                content: attr(data-label);
                font-weight: bold;
                min-width: 120px;
                margin-right: 10px;
            }
            .table-responsive-stack th {
                display: none;
            }
        }
    </style>
</head>
<body>
    <div class="dashboard-container py-4">
        <!-- Dashboard Header -->
        <div class="dashboard-header mb-4">
            <div class="d-flex justify-content-between align-items-center">
                <h1 class="m-0"><i class="fas fa-shipping-fast me-2"></i>Shipment Management</h1>
                <div>
                    <span class="d-none d-md-inline">Admin Dashboard</span>
                    <i class="fas fa-user-shield ms-2"></i>
                </div>
            </div>
        </div>
        
        <!-- Alert Messages -->
        <?php if(isset($success_message) && empty($receipt_html)): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo htmlspecialchars($success_message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php endif; ?>
        
        <?php if(isset($error_message)): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?php echo htmlspecialchars($error_message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php endif; ?>
        
        <div class="row">
            <!-- Shipment Form -->
            <div class="col-lg-5 mb-4">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="m-0">
                            <?php echo isset($edit_data) ? 'Edit Shipment' : 'Create New Shipment'; ?>
                        </h5>
                        <?php if(isset($edit_data)): ?>
                            <a href="admin_dashboard.php" class="btn btn-sm btn-outline-secondary">Cancel Edit</a>
                        <?php endif; ?>
                    </div>
                    <div class="card-body">
                        <form method="post" action="">
                            <?php if(isset($edit_data)): ?>
                                <input type="hidden" name="shipment_id" value="<?php echo $edit_data['id']; ?>">
                            <?php endif; ?>
                            
                            <h6 class="section-title">Sender Information</h6>
                            <div class="mb-3">
                                <label for="sender_name" class="form-label">Sender's Name</label>
                                <input type="text" class="form-control" id="sender_name" name="sender_name" required
                                       value="<?php echo isset($edit_data) ? htmlspecialchars($edit_data['sender_name']) : ''; ?>">
                            </div>
                            <div class="mb-3">
                                <label for="sender_address" class="form-label">Sender's Address</label>
                                <textarea class="form-control" id="sender_address" name="sender_address" rows="2" required><?php echo isset($edit_data) ? htmlspecialchars($edit_data['sender_address']) : ''; ?></textarea>
                            </div>
                            <div class="mb-3">
                                <label for="sender_phone" class="form-label">Sender's Phone</label>
                                <input type="text" class="form-control" id="sender_phone" name="sender_phone" required
                                       value="<?php echo isset($edit_data) ? htmlspecialchars($edit_data['sender_phone']) : ''; ?>">
                            </div>
                            
                            <h6 class="section-title">Receiver Information</h6>
                            <div class="mb-3">
                                <label for="receiver_name" class="form-label">Receiver's Name</label>
                                <input type="text" class="form-control" id="receiver_name" name="receiver_name" required
                                       value="<?php echo isset($edit_data) ? htmlspecialchars($edit_data['receiver_name']) : ''; ?>">
                            </div>
                            <div class="mb-3">
                                <label for="receiver_address" class="form-label">Receiver's Address</label>
                                <textarea class="form-control" id="receiver_address" name="receiver_address" rows="2" required><?php echo isset($edit_data) ? htmlspecialchars($edit_data['receiver_address']) : ''; ?></textarea>
                            </div>
                            <div class="mb-3">
                                <label for="receiver_phone" class="form-label">Receiver's Phone</label>
                                <input type="text" class="form-control" id="receiver_phone" name="receiver_phone" required
                                       value="<?php echo isset($edit_data) ? htmlspecialchars($edit_data['receiver_phone']) : ''; ?>">
                            </div>
                            <div class="mb-3">
                                <label for="receiver_email" class="form-label">Receiver's Email</label>
                                <input type="email" class="form-control" id="receiver_email" name="receiver_email" required
                                       value="<?php echo isset($edit_data) ? htmlspecialchars($edit_data['receiver_email']) : ''; ?>">
                            </div>
                            
                            <h6 class="section-title">Shipment Details</h6>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="weight" class="form-label">Shipment Weight (kg)</label>
                                    <input type="number" step="0.01" class="form-control" id="weight" name="weight" required
                                           value="<?php echo isset($edit_data) ? htmlspecialchars($edit_data['weight']) : ''; ?>">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="shipment_type" class="form-label">Shipment Type</label>
                                    <select class="form-select" id="shipment_type" name="shipment_type" required>
                                        <option value="">Select Type</option>
                                        <option value="Document" <?php echo (isset($edit_data) && $edit_data['shipment_type'] == 'Document') ? 'selected' : ''; ?>>Document</option>
                                        <option value="Parcel" <?php echo (isset($edit_data) && $edit_data['shipment_type'] == 'Parcel') ? 'selected' : ''; ?>>Parcel</option>
                                        <option value="Fragile Item" <?php echo (isset($edit_data) && $edit_data['shipment_type'] == 'Fragile Item') ? 'selected' : ''; ?>>Fragile Item</option>
                                        <option value="Perishable Goods" <?php echo (isset($edit_data) && $edit_data['shipment_type'] == 'Perishable Goods') ? 'selected' : ''; ?>>Perishable Goods</option>
                                         <option value="Air Freight" <?php echo (isset($edit_data) && $edit_data['shipment_type'] == 'Air Freight') ? 'selected' : ''; ?>>Air Freight</option>
                                    </select>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="origin" class="form-label">Shipment Origin</label>
                                    <input type="text" class="form-control" id="origin" name="origin" required
                                           value="<?php echo isset($edit_data) ? htmlspecialchars($edit_data['origin']) : ''; ?>">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="destination" class="form-label">Shipment Destination</label>
                                    <input type="text" class="form-control" id="destination" name="destination" required
                                           value="<?php echo isset($edit_data) ? htmlspecialchars($edit_data['destination']) : ''; ?>">
                                </div>
                            </div>
                            <div class="row">
                                 <div class="col-md-6 mb-3">
                                    <label for="tracking_number" class="form-label">Tracking Number</label>
                                    <input type="text" class="form-control" id="tracking_number" name="tracking_number"
                                           value="<?php echo isset($edit_data) ? htmlspecialchars($edit_data['tracking_number']) : ''; ?>">
                                    <?php if(!isset($edit_data)): ?>
                                        <small class="text-muted">Leave blank to generate automatically</small>
                                    <?php endif; ?>
                                </div>
                                 <div class="col-md-6 mb-3">
                                    <label for="departure_date" class="form-label">Departure Date</label>
                                    <input type="date" class="form-control" id="departure_date" name="departure_date" required
                                           value="<?php echo isset($edit_data) ? htmlspecialchars($edit_data['departure_date']) : ''; ?>">
                                </div>

                                <div class="col-md-6 mb-3">
                                    <label for="delivery_date" class="form-label">Expected Delivery Date</label>
                                    <input type="date" class="form-control" id="delivery_date" name="delivery_date" required
                                           value="<?php echo isset($edit_data) ? htmlspecialchars($edit_data['delivery_date']) : ''; ?>">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="current_location" class="form-label">Current Location</label>
                                    <input type="text" class="form-control" id="current_location" name="current_location" required
                                           value="<?php echo isset($edit_data) ? htmlspecialchars($edit_data['current_location']) : ''; ?>">
                                </div>

                                <div class="col-md-6 mb-3">
                                    <label for="current_location" class="form-label">Shipping Cost</label>
                                    <input type="text" class="form-control" id="value" name="value" required
                                           value="<?php echo isset($edit_data) ? htmlspecialchars($edit_data['value']) : ''; ?>">
                                </div>
                                
                                 <div class="col-md-6 mb-3">
                                    <label for="current_location" class="form-label">Quantity</label>
                                    <input type="text" class="form-control" id="quantity" name="quantity" required
                                           value="<?php echo isset($edit_data) ? htmlspecialchars($edit_data['quantity']) : ''; ?>">
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="note" class="form-label">Note (Optional)</label>
                                <textarea class="form-control" id="note" name="note" rows="2"><?php echo isset($edit_data) ? htmlspecialchars($edit_data['note']) : ''; ?></textarea>
                            </div>
                            <div class="mb-4">
                                <label for="status" class="form-label">Shipment Status</label>
                                <select class="form-select status-dropdown" id="status" name="status" required onchange="updateStatusColor(this)">
                                    <option value="Pending" <?php echo (isset($edit_data) && $edit_data['status'] == 'Pending') ? 'selected' : ''; ?>>Pending</option>
                                    <option value="In Transit" <?php echo (isset($edit_data) && $edit_data['status'] == 'In Transit') ? 'selected' : ''; ?>>In Transit</option>
                                    <option value="Shipped" <?php echo (isset($edit_data) && $edit_data['status'] == 'Shipped') ? 'selected' : ''; ?>>Shipped</option>
                                    <option value="Delivered" <?php echo (isset($edit_data) && $edit_data['status'] == 'Delivered') ? 'selected' : ''; ?>>Delivered</option>
                                    <option value="On Hold" <?php echo (isset($edit_data) && $edit_data['status'] == 'On Hold') ? 'selected' : ''; ?>>On Hold</option>
                                    <option value="Processing" <?php echo (isset($edit_data) && $edit_data['status'] == 'Processing') ? 'selected' : ''; ?>>Processing</option>
                                </select>
                            </div>
                            
                            <div class="d-grid">
                                <?php if(isset($edit_data)): ?>
                                    <button type="submit" name="update_shipment" class="btn btn-success">
                                        <i class="fas fa-save me-2"></i>Update Shipment
                                    </button>
                                <?php else: ?>
                                    <button type="submit" name="submit_shipment" class="btn btn-primary">
                                        <i class="fas fa-plus me-2"></i>Submit Shipment
                                    </button>
                                <?php endif; ?>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            
            <!-- Shipments List -->
            <div class="col-lg-7">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="m-0">All Shipments</h5>
                        <div class="input-group" style="max-width: 300px;">
                            <input type="text" class="form-control" id="searchInput" placeholder="Search shipments...">
                            <button class="btn btn-outline-secondary" type="button">
                                <i class="fas fa-search"></i>
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <?php if(mysqli_num_rows($all_shipments) > 0): ?>
                            <div class="table-responsive">
                                <table class="table table-hover shipment-table" id="shipmentTable">
                                    <thead>
                                        <tr>
                                            <th>Tracking #</th>
                                            <th>Sender</th>
                                            <th>Receiver</th>
                                            <th>Origin → Destination</th>
                                            <th>Delivery Date</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php while($row = mysqli_fetch_assoc($all_shipments)): ?>
                                            <tr>
                                                <td data-label="Tracking #"><?php echo htmlspecialchars($row['tracking_number']); ?></td>
                                                <td data-label="Sender"><?php echo htmlspecialchars($row['sender_name']); ?></td>
                                                <td data-label="Receiver"><?php echo htmlspecialchars($row['receiver_name']); ?></td>
                                                <td data-label="Route"><?php echo htmlspecialchars($row['origin']); ?> → <?php echo htmlspecialchars($row['destination']); ?></td>
                                                <td data-label="Delivery Date"><?php echo date('M d, Y', strtotime($row['delivery_date'])); ?></td>
                                                <td data-label="Status">
                                                    <span class="status-badge status-<?php echo strtolower(str_replace(' ', '-', $row['status'])); ?>">
                                                        <?php echo htmlspecialchars($row['status']); ?>
                                                    </span>
                                                </td>
                                                <td data-label="Actions" class="action-buttons">
                                                    <a href="?edit=<?php echo $row['id']; ?>" class="btn btn-sm btn-info" title="Edit">
                                                        <i class="fas fa-edit"></i>
                                                    </a>
                                                    <a href="javascript:void(0);" onclick="confirmDelete(<?php echo $row['id']; ?>)" class="btn btn-sm btn-danger" title="Delete">
                                                        <i class="fas fa-trash"></i>
                                                    </a>
                                                    <button type="button" class="btn btn-sm btn-secondary" title="View Details" 
                                                            data-bs-toggle="modal" data-bs-target="#detailsModal<?php echo $row['id']; ?>">
                                                        <i class="fas fa-eye"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                            
                                            <!-- Details Modal -->
                                            <div class="modal fade" id="detailsModal<?php echo $row['id']; ?>" tabindex="-1" aria-hidden="true">
                                                <div class="modal-dialog modal-lg">
                                                    <div class="modal-content">
                                                        <div class="modal-header">
                                                            <h5 class="modal-title">Shipment Details: <?php echo htmlspecialchars($row['tracking_number']); ?></h5>
                                                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                        </div>
                                                        <div class="modal-body">
                                                            <?php if(!empty($row['note'])): ?>
                                                                <div class="alert alert-info">
                                                                    <strong>Note:</strong> <?php echo htmlspecialchars($row['note']); ?>
                                                                </div>
                                                            <?php endif; ?>
                                                            
                                                            <div class="row">
                                                                <div class="col-md-6">
                                                                    <h6 class="fw-bold">Sender Information</h6>
                                                                    <p><strong>Name:</strong> <?php echo htmlspecialchars($row['sender_name']); ?></p>
                                                                    <p><strong>Address:</strong> <?php echo htmlspecialchars($row['sender_address']); ?></p>
                                                                    <p><strong>Phone:</strong> <?php echo htmlspecialchars($row['sender_phone']); ?></p>
                                                                </div>
                                                                <div class="col-md-6">
                                                                    <h6 class="fw-bold">Receiver Information</h6>
                                                                    <p><strong>Name:</strong> <?php echo htmlspecialchars($row['receiver_name']); ?></p>
                                                                    <p><strong>Address:</strong> <?php echo htmlspecialchars($row['receiver_address']); ?></p>
                                                                    <p><strong>Phone:</strong> <?php echo htmlspecialchars($row['receiver_phone']); ?></p>
                                                                    <p><strong>Email:</strong> <?php echo htmlspecialchars($row['receiver_email']); ?></p>
                                                                </div>
                                                            </div>
                                                            <hr>
                                                            <div class="row">
                                                                <div class="col-md-6">
                                                                    <h6 class="fw-bold">Shipment Details</h6>
                                                                    <p><strong>Weight:</strong> <?php echo htmlspecialchars($row['weight']); ?> kg</p>
                                                                    <p><strong>Type:</strong> <?php echo htmlspecialchars($row['shipment_type']); ?></p>
                                                                    <p><strong>Origin:</strong> <?php echo htmlspecialchars($row['origin']); ?></p>
                                                                    <p><strong>Destination:</strong> <?php echo htmlspecialchars($row['destination']); ?></p>
                                                                </div>
                                                                <div class="col-md-6">
                                                                    <h6 class="fw-bold">Tracking Information</h6>
                                                                    <p><strong>Tracking Number:</strong> <?php echo htmlspecialchars($row['tracking_number']); ?></p>
                                                                    <p><strong>Current Location:</strong> <?php echo htmlspecialchars($row['current_location']); ?></p>
                                                                    <p><strong>Value:</strong> <?php echo htmlspecialchars($row['value']); ?></p>
                                                                    <p><strong>Expected Delivery:</strong> <?php echo date('F d, Y', strtotime($row['delivery_date'])); ?></p>
                                                                    <p><strong>Status:</strong> 
                                                                        <span class="status-badge status-<?php echo strtolower(str_replace(' ', '-', $row['status'])); ?>">
                                                                            <?php echo htmlspecialchars($row['status']); ?>
                                                                        </span>
                                                                    </p>
                                                                    <p><strong>Created:</strong> <?php echo date('F d, Y H:i', strtotime($row['created_at'])); ?></p>
                                                                    <?php if(!empty($row['updated_at'])): ?>
                                                                        <p><strong>Last Updated:</strong> <?php echo date('F d, Y H:i', strtotime($row['updated_at'])); ?></p>
                                                                    <?php endif; ?>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="modal-footer">
                                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                                            <a href="?edit=<?php echo $row['id']; ?>" class="btn btn-primary">Edit Shipment</a>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endwhile; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="text-center p-4">
                                <i class="fas fa-box-open fa-3x text-muted mb-3"></i>
                                <h5>No shipments found</h5>
                                <p class="text-muted">Start by adding a new shipment using the form.</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Confirm Deletion</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    Are you sure you want to delete this shipment? This action cannot be undone.
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <a href="#" id="deleteShipmentBtn" class="btn btn-danger">Delete Shipment</a>
                </div>
            </div>
        </div>
    </div>
    
    <!-- JavaScript -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Delete Confirmation
        function confirmDelete(id) {
            const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
            document.getElementById('deleteShipmentBtn').href = '?delete=' + id;
            deleteModal.show();
        }
        
        // Search Functionality
        document.getElementById('searchInput').addEventListener('keyup', function() {
            const searchTerm = this.value.toLowerCase();
            const table = document.getElementById('shipmentTable');
            const rows = table.getElementsByTagName('tr');
            
            for (let i = 1; i < rows.length; i++) {
                const row = rows[i];
                const cells = row.getElementsByTagName('td');
                let found = false;
                
                for (let j = 0; j < cells.length; j++) {
                    const cellText = cells[j].textContent.toLowerCase();
                    if (cellText.indexOf(searchTerm) > -1) {
                        found = true;
                        break;
                    }
                }
                
                if (found) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            }
        });
        
        // Make tables responsive
        window.addEventListener('load', function() {
            if (window.innerWidth < 992) {
                const tables = document.querySelectorAll('.shipment-table');
                tables.forEach(function(table) {
                    table.classList.add('table-responsive-stack');
                });
            }
        });
        
        window.addEventListener('resize', function() {
            const tables = document.querySelectorAll('.shipment-table');
            if (window.innerWidth < 992) {
                tables.forEach(function(table) {
                    table.classList.add('table-responsive-stack');
                });
            } else {
                tables.forEach(function(table) {
                    table.classList.remove('table-responsive-stack');
                });
            }
        });
        
        // Auto-dismiss alerts
        document.addEventListener('DOMContentLoaded', function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(function(alert) {
                setTimeout(function() {
                    const bsAlert = new bootstrap.Alert(alert);
                    bsAlert.close();
                }, 5000);
            });
        });
    </script>

    <script>
        function updateStatusColor(selectElement) {
            var statusClassMap = {
                "Pending": "status-pending",
                "In Transit": "status-transit",
                "Shipped": "status-shipped",
                "Delivered": "status-delivered",
                "On Hold": "status-hold",
                "Processing": "status-processing"
            };

            // Remove existing status classes
            selectElement.classList.remove("status-pending", "status-transit", "status-shipped", "status-delivered", "status-hold");

            // Add the new class based on selection
            var selectedStatus = selectElement.value;
            if (statusClassMap[selectedStatus]) {
                selectElement.classList.add(statusClassMap[selectedStatus]);
            }
        }

        // Initialize the correct color on page load
        document.addEventListener("DOMContentLoaded", function () {
            var statusDropdown = document.getElementById("status");
            if (statusDropdown) {
                updateStatusColor(statusDropdown);
            }
        });
    </script>
</body>
</html>