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

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$shipment_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$tracking_number = isset($_GET['tracking']) ? trim($_GET['tracking']) : '';

// If tracking number is provided, get shipment ID
if ($tracking_number && !$shipment_id) {
    $tracking_sql = "SELECT shipment_id FROM shipments WHERE tracking_number = ?";
    $tracking_stmt = $conn->prepare($tracking_sql);
    $tracking_stmt->bind_param("s", $tracking_number);
    $tracking_stmt->execute();
    $tracking_result = $tracking_stmt->get_result();
    if ($tracking_result->num_rows > 0) {
        $shipment_id = $tracking_result->fetch_assoc()['shipment_id'];
    }
}

if (!$shipment_id) {
    header('Location: shipments.php?error=invalid_shipment');
    exit();
}

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

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

// Fetch complete shipment details
$shipment_sql = "SELECT 
    s.*,
    st.service_name,
    st.service_code,
    st.service_category,
    st.transit_days_min,
    st.transit_days_max,
    ol.location_name as origin_location,
    ol.city as origin_city,
    ol.country_id as origin_country_id,
    oc.country_name as origin_country,
    dl.location_name as destination_location,
    dl.city as destination_city,
    dl.country_id as destination_country_id,
    dc.country_name as destination_country,
    sc.customer_code as sender_customer_code,
    sc.customer_type as sender_customer_type,
    CASE 
        WHEN sc.customer_type = 'CORPORATE' THEN sc.company_name
        ELSE CONCAT(sc.first_name, ' ', sc.last_name)
    END as sender_customer_name,
    sc.email as sender_customer_email,
    sc.phone as sender_customer_phone,
    creator.full_name as created_by_name,
    updater.full_name as updated_by_name
FROM shipments s
LEFT JOIN service_types st ON s.service_id = st.service_id
LEFT JOIN locations ol ON s.origin_location_id = ol.location_id
LEFT JOIN countries oc ON ol.country_id = oc.country_id
LEFT JOIN locations dl ON s.destination_location_id = dl.location_id
LEFT JOIN countries dc ON dl.country_id = dc.country_id
LEFT JOIN customers sc ON s.sender_customer_id = sc.customer_id
LEFT JOIN users creator ON s.created_by = creator.user_id
LEFT JOIN users updater ON s.updated_by = updater.user_id
WHERE s.shipment_id = ?";

$shipment_stmt = $conn->prepare($shipment_sql);
$shipment_stmt->bind_param("i", $shipment_id);
$shipment_stmt->execute();
$shipment_result = $shipment_stmt->get_result();

if ($shipment_result->num_rows === 0) {
    header('Location: shipments.php?error=shipment_not_found');
    exit();
}

$shipment = $shipment_result->fetch_assoc();

// Recalculate and update payment status based on actual payments
$payment_summary_sql = "SELECT 
    COALESCE(SUM(CASE WHEN p.status = 'CONFIRMED' THEN p.amount ELSE 0 END), 0) as total_paid,
    COUNT(CASE WHEN p.status = 'CONFIRMED' THEN 1 END) as payment_count
FROM payments p 
WHERE p.shipment_id = ?";

$payment_summary_stmt = $conn->prepare($payment_summary_sql);
$payment_summary_stmt->bind_param("i", $shipment_id);
$payment_summary_stmt->execute();
$payment_summary_result = $payment_summary_stmt->get_result();
$payment_summary = $payment_summary_result->fetch_assoc();

$total_paid = $payment_summary['total_paid'];
$outstanding_amount = $shipment['total_charges'] - $total_paid;

// Update shipment payment status if it's incorrect
$correct_payment_status = 'PENDING';
if ($total_paid >= $shipment['total_charges']) {
    $correct_payment_status = 'PAID';
} elseif ($total_paid > 0) {
    $correct_payment_status = 'PARTIAL';
}

// Update the shipment if status is wrong
if ($shipment['payment_status'] !== $correct_payment_status) {
    $update_status_sql = "UPDATE shipments SET 
        payment_status = ?, 
        updated_by = ?, 
        updated_at = CURRENT_TIMESTAMP 
        WHERE shipment_id = ?";
    $update_status_stmt = $conn->prepare($update_status_sql);
    $update_status_stmt->bind_param("sii", $correct_payment_status, $user_id, $shipment_id);
    $update_status_stmt->execute();
    
    // Update the shipment array for display
    $shipment['payment_status'] = $correct_payment_status;
}

// Fetch payment information for this shipment
$payments_sql = "SELECT 
    p.*,
    pm.method_name as payment_method_name,
    i.invoice_number,
    i.invoice_date,
    i.due_date,
    i.status as invoice_status,
    processor.full_name as processed_by_name
FROM payments p
LEFT JOIN payment_methods pm ON p.payment_method_id = pm.method_id
LEFT JOIN invoices i ON p.invoice_id = i.invoice_id
LEFT JOIN users processor ON p.created_by = processor.user_id
WHERE p.shipment_id = ?
ORDER BY p.created_at DESC";

$payments_stmt = $conn->prepare($payments_sql);
$payments_stmt->bind_param("i", $shipment_id);
$payments_stmt->execute();
$payments_result = $payments_stmt->get_result();

// Fetch associated invoice if exists
$invoice_sql = "SELECT 
    i.*,
    creator.full_name as created_by_name
FROM invoice_items ii
INNER JOIN invoices i ON ii.invoice_id = i.invoice_id
LEFT JOIN users creator ON i.created_by = creator.user_id
WHERE ii.shipment_id = ?
ORDER BY i.created_at DESC
LIMIT 1";

$invoice_stmt = $conn->prepare($invoice_sql);
$invoice_stmt->bind_param("i", $shipment_id);
$invoice_stmt->execute();
$invoice_result = $invoice_stmt->get_result();
$invoice = $invoice_result->fetch_assoc();

// Build payments data array
$last_payment_method = '';
$payments_data = [];
while ($payment = $payments_result->fetch_assoc()) {
    if ($payment['status'] === 'COMPLETED' && empty($last_payment_method)) {
        $last_payment_method = $payment['payment_method_name'];
    }
    $payments_data[] = $payment;
}

// Fetch available payment methods
$payment_methods_sql = "SELECT * FROM payment_methods WHERE is_active = 1 ORDER BY method_name";
$payment_methods_result = $conn->query($payment_methods_sql);

// Handle form submissions
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    switch ($_POST['action']) {
        case 'process_payment':
            $payment_amount = floatval($_POST['payment_amount']);
            $payment_method_id = intval($_POST['payment_method_id']);
            $payment_reference = trim($_POST['payment_reference'] ?? '');
            $payment_notes = trim($_POST['payment_notes'] ?? '');
            $generate_receipt = isset($_POST['generate_receipt']) && $_POST['generate_receipt'] === 'on';
        
            // Validate payment amount
            if ($payment_amount <= 0 || $payment_amount > $outstanding_amount) {
                $message = "Invalid payment amount. Must be between 0 and " . number_format($outstanding_amount, 2);
                $message_type = "danger";
                break;
            }
        
            // Validate customer_id
            if (empty($shipment['sender_customer_id'])) {
                $message = "Error: Customer ID is missing for this shipment.";
                $message_type = "danger";
                break;
            }
        
            // Map payment_method_id to payment_method ENUM value
            $payment_method_sql = "SELECT method_name FROM payment_methods WHERE method_id = ?";
            $payment_method_stmt = $conn->prepare($payment_method_sql);
            $payment_method_stmt->bind_param("i", $payment_method_id);
            $payment_method_stmt->execute();
            $payment_method_result = $payment_method_stmt->get_result();
            $payment_method = $payment_method_result->fetch_assoc()['method_name'] ?? 'OTHER';
        
            // Convert method_name to ENUM value (ensure it matches ENUM values)
            $valid_payment_methods = ['CASH', 'BANK_TRANSFER', 'CARD', 'MOBILE_MONEY', 'CHEQUE', 'OTHER'];
            $payment_method = strtoupper(preg_replace('/\s+/', '_', $payment_method));
            if (!in_array($payment_method, $valid_payment_methods)) {
                $payment_method = 'OTHER';
            }
        
            // Start transaction
            $conn->begin_transaction();
        
            try {
                // Create or get invoice
                $invoice_id = null;
                if ($invoice) {
                    $invoice_id = $invoice['invoice_id'];
                } else {
                    // Create new invoice
                    $invoice_insert_sql = "INSERT INTO invoices (
                        invoice_number, customer_id, invoice_date, due_date, 
                        subtotal, tax_amount, total_amount, status, created_by
                    ) VALUES (?, ?, CURDATE(), DATE_ADD(CURDATE(), INTERVAL 30 DAY), 
                        ?, ?, ?, 'SENT', ?)";
                    
                    $invoice_stmt = $conn->prepare($invoice_insert_sql);
                    
                    // Generate invoice number
                    $invoice_number = 'INV' . date('Y') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
                    $customer_id = $shipment['sender_customer_id'];
                    $subtotal = $shipment['total_charges'] - $shipment['tax_amount'];
                    $tax_amount = $shipment['tax_amount'];
                    $total_amount = $shipment['total_charges'];
                    
                    $invoice_stmt->bind_param("sissddi", 
                        $invoice_number, $customer_id, $subtotal, 
                        $tax_amount, $total_amount, $user_id
                    );
                    if (!$invoice_stmt->execute()) {
                        throw new Exception("Failed to create invoice: " . $conn->error);
                    }
                    $invoice_id = $conn->insert_id;
                    
                    // Add invoice item
                    $item_insert_sql = "INSERT INTO invoice_items (
                        invoice_id, shipment_id, description, quantity, unit_price, line_total
                    ) VALUES (?, ?, ?, 1, ?, ?)";
                    $item_stmt = $conn->prepare($item_insert_sql);
                    $description = "Freight charges for " . $shipment['tracking_number'];
                    $unit_price = $shipment['total_charges'];
                    $line_total = $shipment['total_charges'];
                    $item_stmt->bind_param("iisdd", 
                        $invoice_id, $shipment_id, $description, 
                        $unit_price, $line_total
                    );
                    if (!$item_stmt->execute()) {
                        throw new Exception("Failed to create invoice item: " . $conn->error);
                    }
                }
                
                // Generate payment number
                $payment_number = 'PAY' . date('Ymd') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
                
                // Insert payment record
                $payment_insert_sql = "INSERT INTO payments (
                    payment_number, invoice_id, shipment_id, customer_id, payment_date,
                    payment_method, amount, reference_number, notes, status, created_by,
                    processed_by
                ) VALUES (?, ?, ?, ?, CURDATE(), ?, ?, ?, ?, 'CONFIRMED', ?, ?)";
                
                $payment_stmt = $conn->prepare($payment_insert_sql);
                $customer_id_value = $shipment['sender_customer_id'];
                
                $payment_stmt->bind_param("siisssdssi",
                    $payment_number, $invoice_id, $shipment_id, $customer_id_value,
                    $payment_method, $payment_amount, $payment_reference, 
                    $payment_notes, $user_id, $user_id
                );
                if (!$payment_stmt->execute()) {
                    throw new Exception("Failed to insert payment: " . $conn->error);
                }
                $payment_id = $conn->insert_id;
                
                // Insert receipt record if generate_receipt is checked
                if ($generate_receipt) {
                    $receipt_insert_sql = "INSERT INTO receipts (
                        payment_id, shipment_id, customer_id, receipt_type, 
                        total_amount, payment_method, issued_by, notes
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
                    
                    $receipt_stmt = $conn->prepare($receipt_insert_sql);
                    
                    // Assign 'PAYMENT' to a variable
                    $receipt_type = 'PAYMENT';
                    
                    // Match type string to actual parameter types
                    // i = int, d = double, s = string..
                    $receipt_stmt->bind_param(
                        "iiisdiss",
                        $payment_id,
                        $shipment_id,
                        $customer_id_value,
                        $receipt_type,      // <-- use variable, not literal
                        $payment_amount,
                        $payment_method,
                        $user_id,
                        $payment_notes
                    );
                    
                    if (!$receipt_stmt->execute()) {
                        throw new Exception("Failed to insert receipt: " . $conn->error);
                    }
                    $receipt_id = $conn->insert_id;
                
                    // Update payments table to mark receipt as generated
                    $update_payment_sql = "UPDATE payments SET 
                        receipt_generated = 1, 
                        receipt_generated_at = CURRENT_TIMESTAMP 
                        WHERE payment_id = ?";
                    $update_payment_stmt = $conn->prepare($update_payment_sql);
                    $update_payment_stmt->bind_param("i", $payment_id);
                    if (!$update_payment_stmt->execute()) {
                        throw new Exception("Failed to update payment receipt status: " . $conn->error);
                    }
                }

                // Update payment totals
                $new_total_paid = $total_paid + $payment_amount;
                $new_outstanding = $shipment['total_charges'] - $new_total_paid;
                
                // Update invoice status
                if ($invoice_id) {
                    $invoice_status = ($new_outstanding <= 0) ? 'PAID' : 'PARTIAL';
                    $update_invoice_sql = "UPDATE invoices SET 
                        paid_amount = ?, balance_amount = ?, status = ?
                        WHERE invoice_id = ?";
                    $update_stmt = $conn->prepare($update_invoice_sql);
                    $update_stmt->bind_param("ddsi", 
                        $new_total_paid, $new_outstanding, $invoice_status, $invoice_id
                    );
                    if (!$update_stmt->execute()) {
                        throw new Exception("Failed to update invoice: " . $conn->error);
                    }
                }
                
                // Update shipment payment status
                $shipment_payment_status = ($new_outstanding <= 0) ? 'PAID' : 'PARTIAL';
                $update_shipment_sql = "UPDATE shipments SET 
                    payment_status = ?, updated_by = ?, updated_at = CURRENT_TIMESTAMP 
                    WHERE shipment_id = ?";
                $update_shipment_stmt = $conn->prepare($update_shipment_sql);
                $update_shipment_stmt->bind_param("sii", 
                    $shipment_payment_status, $user_id, $shipment_id
                );
                if (!$update_shipment_stmt->execute()) {
                    throw new Exception("Failed to update shipment: " . $conn->error);
                }
                
                // Add tracking event
                $tracking_sql = "INSERT INTO tracking_events (
                    shipment_id, event_type, event_status, event_description, created_by
                ) VALUES (?, 'PAYMENT', ?, ?, ?)";
                $tracking_stmt = $conn->prepare($tracking_sql);
                $event_description = "Payment of " . $shipment['currency'] . " " . 
                    number_format($payment_amount, 2) . " received via " . $payment_method;
                $current_status = $shipment['status'];
                $tracking_stmt->bind_param("issi", 
                    $shipment_id, $current_status, $event_description, $user_id
                );
                if (!$tracking_stmt->execute()) {
                    throw new Exception("Failed to insert tracking event: " . $conn->error);
                }
                
                // Commit transaction
                $conn->commit();
                
                $message = "Payment processed successfully!";
                $message_type = "success";
                
                // Redirect to receipt generation or back to shipment view
                if ($generate_receipt) {
                    header("Location: generate_receipt.php?payment_id=$payment_id&receipt_id=$receipt_id");
                    exit();
                } else {
                    header("Location: view_shipment.php?id=$shipment_id&payment_success=1");
                    exit();
                }
                
            } catch (Exception $e) {
                $conn->rollback();
                $message = "Error processing payment: " . $e->getMessage();
                $message_type = "danger";
            }
            break;
            
        case 'generate_invoice':
            // Redirect to invoice generation
            header("Location: generate_invoice.php?shipment_id=$shipment_id");
            exit();
            break;
            
        case 'update_status':
            $new_status = $_POST['new_status'];
            $location = $_POST['location'] ?? '';
            $notes = $_POST['notes'] ?? '';
            
            // Update shipment status
            $update_sql = "UPDATE shipments SET status = ?, updated_by = ?, updated_at = CURRENT_TIMESTAMP WHERE shipment_id = ?";
            $update_stmt = $conn->prepare($update_sql);
            $update_stmt->bind_param("sii", $new_status, $user_id, $shipment_id);
            
            if ($update_stmt->execute()) {
                // Add tracking event
                $tracking_sql = "INSERT INTO tracking_events (shipment_id, event_type, event_status, event_description, location, created_by) 
                                VALUES (?, ?, ?, ?, ?, ?)";
                $tracking_stmt = $conn->prepare($tracking_sql);
                $event_description = "Status updated to " . $new_status . ($notes ? " - " . $notes : "");
                $tracking_stmt->bind_param("issssi", $shipment_id, $new_status, $new_status, $event_description, $location, $user_id);
                $tracking_stmt->execute();
                
                $message = "Shipment status updated successfully!";
                $message_type = "success";
                
                // Refresh page to show updated data
                header("Location: view_shipment.php?id=$shipment_id");
                exit();
            } else {
                $message = "Error updating shipment status.";
                $message_type = "danger";
            }
            break;
            
        case 'add_note':
            $note_text = $_POST['note_text'];
            $location = $_POST['location'] ?? '';
            
            // Add tracking event as note
            $note_sql = "INSERT INTO tracking_events (shipment_id, event_type, event_status, event_description, location, created_by) 
                        VALUES (?, 'NOTE', ?, ?, ?, ?)";
            $note_stmt = $conn->prepare($note_sql);
            $current_status = $shipment['status'];
            $note_stmt->bind_param("isssi", $shipment_id, $current_status, $note_text, $location, $user_id);
            
            if ($note_stmt->execute()) {
                $message = "Note added successfully!";
                $message_type = "success";
                header("Location: view_shipment.php?id=$shipment_id");
                exit();
            } else {
                $message = "Error adding note.";
                $message_type = "danger";
            }
            break;
    }
}

// Fetch tracking events
$tracking_events_sql = "SELECT 
    te.*,
    creator.full_name as created_by_name
FROM tracking_events te
LEFT JOIN users creator ON te.created_by = creator.user_id
WHERE te.shipment_id = ?
ORDER BY te.event_date DESC, te.event_id DESC";

$tracking_events_stmt = $conn->prepare($tracking_events_sql);
$tracking_events_stmt->bind_param("i", $shipment_id);
$tracking_events_stmt->execute();
$tracking_events = $tracking_events_stmt->get_result();

// Fetch delivery attempts
$delivery_attempts_sql = "SELECT 
    da.*,
    d.first_name as driver_first_name,
    d.last_name as driver_last_name,
    d.phone as driver_phone
FROM delivery_attempts da
LEFT JOIN drivers d ON da.delivered_by = d.driver_id
WHERE da.shipment_id = ?
ORDER BY da.attempt_date DESC";

$delivery_attempts_stmt = $conn->prepare($delivery_attempts_sql);
$delivery_attempts_stmt->bind_param("i", $shipment_id);
$delivery_attempts_stmt->execute();
$delivery_attempts = $delivery_attempts_stmt->get_result();

// Fetch shipment documents
$documents_sql = "SELECT 
    sd.*,
    uploader.full_name as uploaded_by_name
FROM shipment_documents sd
LEFT JOIN users uploader ON sd.uploaded_by = uploader.user_id
WHERE sd.shipment_id = ?
ORDER BY sd.uploaded_at DESC";

$documents_stmt = $conn->prepare($documents_sql);
$documents_stmt->bind_param("i", $shipment_id);
$documents_stmt->execute();
$documents = $documents_stmt->get_result();

// Fetch customs declaration if exists
$customs_sql = "SELECT 
    cd.*,
    creator.full_name as created_by_name
FROM customs_declarations cd
LEFT JOIN users creator ON cd.created_by = creator.user_id
WHERE cd.shipment_id = ?";

$customs_stmt = $conn->prepare($customs_sql);
$customs_stmt->bind_param("i", $shipment_id);
$customs_stmt->execute();
$customs_result = $customs_stmt->get_result();
$customs_declaration = $customs_result->fetch_assoc();

// Fetch shipment commodities
$commodities_sql = "SELECT 
    sc.*,
    c.hs_code,
    c.commodity_name,
    c.is_restricted,
    c.is_hazardous,
    c.duty_rate,
    c.vat_rate
FROM shipment_commodities sc
LEFT JOIN commodities c ON sc.commodity_id = c.commodity_id
WHERE sc.shipment_id = ?";

$commodities_stmt = $conn->prepare($commodities_sql);
$commodities_stmt->bind_param("i", $shipment_id);
$commodities_stmt->execute();
$commodities = $commodities_stmt->get_result();

// Calculate shipment metrics
$total_declared_value = 0;
$has_restricted_items = false;
$has_hazardous_items = false;

while ($commodity = $commodities->fetch_assoc()) {
    $total_declared_value += $commodity['total_value'];
    if ($commodity['is_restricted']) $has_restricted_items = true;
    if ($commodity['is_hazardous']) $has_hazardous_items = true;
}
$commodities->data_seek(0); // Reset for display

// Helper functions
function getStatusColor($status) {
    $colors = [
        'DRAFT' => '#6b7280',
        'BOOKED' => '#3b82f6',
        'COLLECTED' => '#10b981',
        'IN_TRANSIT' => '#f59e0b',
        'OUT_FOR_DELIVERY' => '#8b5cf6',
        'DELIVERED' => '#059669',
        'RETURNED' => '#ef4444',
        'CANCELLED' => '#dc2626'
    ];
    return $colors[$status] ?? '#6b7280';
}

function formatStatus($status) {
    return ucfirst(strtolower(str_replace('_', ' ', $status)));
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'View Shipment - ' . $shipment['tracking_number'])); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        .shipment-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .info-card {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
        }
        
        .info-card h5 {
            color: #1e293b;
            margin-bottom: 1rem;
            padding-bottom: 0.5rem;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .status-badge {
            padding: 0.5rem 1rem;
            border-radius: 9999px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            font-size: 0.875rem;
        }
        
        .timeline-container {
            position: relative;
            padding: 1rem 0;
        }
        
        .timeline-item {
            position: relative;
            padding: 1rem 0 1rem 3rem;
            border-left: 2px solid #e2e8f0;
        }
        
        .timeline-item:last-child {
            border-left-color: transparent;
        }
        
        .timeline-dot {
            position: absolute;
            left: -8px;
            top: 1.5rem;
            width: 16px;
            height: 16px;
            border-radius: 50%;
            background: white;
            border: 3px solid #e2e8f0;
        }
        
        .timeline-dot.completed {
            background: #10b981;
            border-color: #10b981;
        }
        
        .timeline-dot.current {
            background: #3b82f6;
            border-color: #3b82f6;
        }
        
        .timeline-content {
            background: #f8fafc;
            border-radius: 8px;
            padding: 1rem;
        }
        
        .address-block {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
        }
        
        .charge-breakdown {
            background: #f0fdf4;
            border: 1px solid #bbf7d0;
            border-radius: 8px;
            padding: 1rem;
        }
        
        .document-item {
            background: #fafafa;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 0.5rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .commodity-item {
            background: #fffbeb;
            border: 1px solid #fed7aa;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 0.5rem;
        }
        
        .action-buttons {
            position: sticky;
            top: 20px;
            z-index: 10;
        }
        
        .quick-actions {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            padding: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .route-display {
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 1rem 0;
        }
        
        .route-point {
            background: #f8fafc;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            padding: 1rem;
            text-align: center;
            min-width: 120px;
        }
        
        .route-arrow {
            font-size: 2rem;
            color: #64748b;
            margin: 0 1rem;
        }
        
        .metrics-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }
        
        .metric-card {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1.5rem;
            text-align: center;
        }
        
        .metric-value {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .metric-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        @media (max-width: 768px) {
            .shipment-header {
                padding: 1.5rem;
            }
            
            .info-card {
                padding: 1rem;
            }
            
            .route-display {
                flex-direction: column;
            }
            
            .route-arrow {
                transform: rotate(90deg);
                margin: 0.5rem 0;
            }
            
            .metrics-grid {
                grid-template-columns: 1fr;
            }
        }
        
        .priority-high {
            background: #fee2e2;
            color: #991b1b;
            border: 1px solid #fecaca;
        }
        
        .priority-urgent {
            background: #fef2f2;
            color: #7f1d1d;
            border: 1px solid #fecaca;
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.8; }
        }
        
        .print-section {
            background: white;
            padding: 2rem;
            border-radius: 12px;
            margin: 2rem 0;
        }
        
        @media print {
            .no-print {
                display: none !important;
            }
            
            .print-section {
                margin: 0;
                box-shadow: none;
                border: none;
            }
            
            .shipment-header {
                background: #f8f9fa !important;
                color: #000 !important;
                -webkit-print-color-adjust: exact;
            }
        }
    </style>
</head>

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

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

                    <!-- Shipment Header -->
                    <div class="shipment-header">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <h2 class="mb-2"><?php echo $shipment['tracking_number']; ?></h2>
                                <p class="mb-1">
                                    <strong><?php echo htmlspecialchars($shipment['sender_name']); ?></strong>
                                    → <strong><?php echo htmlspecialchars($shipment['receiver_name']); ?></strong>
                                </p>
                                <p class="mb-0 opacity-90">
                                    <?php echo $shipment['origin_location']; ?>, <?php echo $shipment['origin_country']; ?>
                                    → <?php echo $shipment['destination_location']; ?>, <?php echo $shipment['destination_country']; ?>
                                </p>
                            </div>
                            <div class="col-md-4 text-md-end">
                                <div class="status-badge" style="background: <?php echo getStatusColor($shipment['status']); ?>;">
                                    <?php echo formatStatus($shipment['status']); ?>
                                </div>
                                <div class="mt-2">
                                    <h4 class="mb-0"><?php echo $shipment['currency']; ?> <?php echo number_format($shipment['total_charges'], 2); ?></h4>
                                    <small class="opacity-90">
                                        <?php echo $shipment['pieces']; ?> pieces • <?php echo $shipment['chargeable_weight']; ?> kg
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Left Column -->
                        <div class="col-xl-8">
                            <!-- Quick Actions -->
                            <div class="quick-actions no-print">
                                <h6 class="mb-3">Quick Actions</h6>
                                <div class="d-flex flex-wrap gap-2">
                                    <?php if ($role_name === 'Administrator' || $role_name === 'Operations Manager' || $role_name === 'Customer Service'): ?>
                                    <button type="button" class="btn btn-outline-primary btn-sm" data-bs-toggle="modal" data-bs-target="#updateStatusModal">
                                        <i class="bx bx-refresh"></i> Update Status
                                    </button>
                                    <?php endif; ?>
                                    
                                    <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-toggle="modal" data-bs-target="#addNoteModal">
                                        <i class="bx bx-note"></i> Add Note
                                    </button>
                                    
                                    <a href="generate_label.php?shipment_id=<?php echo $shipment_id; ?>" class="btn btn-outline-info btn-sm" target="_blank">
                                        <i class="bx bx-printer"></i> Print Label
                                    </a>
                                    
                                    <a href="generate_invoice.php?shipment_id=<?php echo $shipment_id; ?>" class="btn btn-outline-success btn-sm">
                                        <i class="bx bx-receipt"></i> Generate Invoice
                                    </a>
                                    
                                    <?php if ($shipment['status'] === 'DELIVERED'): ?>
                                    <a href="generate_pod.php?id=<?php echo $shipment_id; ?>" class="btn btn-outline-warning btn-sm" target="_blank">
                                        <i class="bx bx-check-circle"></i> POD Report
                                    </a>
                                    <?php endif; ?>
                                    
                                    <button type="button" class="btn btn-outline-dark btn-sm" onclick="window.print()">
                                        <i class="bx bx-printer"></i> Print Details
                                    </button>
                                </div>
                            </div>

                            <!-- Payment Information -->
                            <div class="info-card">
                                <h5><i class="bx bx-credit-card"></i> Payment Information</h5>
                                
                                <!-- Payment Summary -->
                                <div class="row mb-3">
                                    <div class="col-md-3">
                                        <small class="text-muted">Total Amount:</small>
                                        <div class="h6 text-primary"><?php echo $shipment['currency']; ?> <?php echo number_format($shipment['total_charges'], 2); ?></div>
                                    </div>
                                    <div class="col-md-3">
                                        <small class="text-muted">Amount Paid:</small>
                                        <div class="h6 text-success"><?php echo $shipment['currency']; ?> <?php echo number_format($total_paid, 2); ?></div>
                                    </div>
                                    <div class="col-md-3">
                                        <small class="text-muted">Outstanding:</small>
                                        <div class="h6 <?php echo $outstanding_amount > 0 ? 'text-danger' : 'text-success'; ?>">
                                            <?php echo $shipment['currency']; ?> <?php echo number_format($outstanding_amount, 2); ?>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <small class="text-muted">Payment Status:</small>
                                        <div>
                                            <span class="badge bg-<?php echo $shipment['payment_status'] === 'PAID' ? 'success' : ($shipment['payment_status'] === 'PARTIAL' ? 'warning' : 'danger'); ?>">
                                                <?php echo ucfirst(strtolower($shipment['payment_status'])); ?>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Payment Actions - Only show if outstanding amount > 0 -->
                                <?php if ($outstanding_amount > 0 && ($role_name === 'Administrator' || $role_name === 'Finance Manager' || $role_name === 'Customer Service')): ?>
                                <div class="d-flex gap-2 mb-3">
                                    <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#processPaymentModal">
                                        <i class="bx bx-credit-card"></i> Process Payment
                                    </button>
                                    
                                    <?php if (!$invoice): ?>
                                    <form method="POST" class="d-inline">
                                        <input type="hidden" name="action" value="generate_invoice">
                                        <button type="submit" class="btn btn-outline-secondary btn-sm">
                                            <i class="bx bx-receipt"></i> Generate Invoice
                                        </button>
                                    </form>
                                    <?php endif; ?>
                                </div>
                                <?php endif; ?>
                                
                                <!-- Invoice Information -->
                                <?php if ($invoice): ?>
                                <div class="alert alert-info">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <strong>Invoice: <?php echo $invoice['invoice_number']; ?></strong>
                                            <br><small>Created: <?php echo date('M j, Y', strtotime($invoice['invoice_date'])); ?></small>
                                            <br><small>Due: <?php echo date('M j, Y', strtotime($invoice['due_date'])); ?></small>
                                        </div>
                                        <div class="col-md-6 text-md-end">
                                            <span class="badge bg-<?php echo $invoice['status'] === 'PAID' ? 'success' : ($invoice['status'] === 'PARTIAL' ? 'warning' : 'danger'); ?>">
                                                <?php echo $invoice['status']; ?>
                                            </span>
                                            <br><a href="view_invoice.php?id=<?php echo $invoice['invoice_id']; ?>" class="btn btn-link btn-sm p-0">View Invoice</a>
                                        </div>
                                    </div>
                                </div>
                                <?php endif; ?>
                                
                                <!-- Payment History -->
                                <?php if (!empty($payments_data)): ?>
                                <h6 class="mt-3 mb-2">Payment History</h6>
                                <div class="table-responsive">
                                    <table class="table table-sm">
                                        <thead>
                                            <tr>
                                                <th>Payment #</th>
                                                <th>Date</th>
                                                <th>Method</th>
                                                <th>Amount</th>
                                                <th>Reference</th>
                                                <th>Status</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($payments_data as $payment): ?>
                                            <tr>
                                                <td><code><?php echo $payment['payment_number']; ?></code></td>
                                                <td><?php echo date('M j, Y', strtotime($payment['payment_date'])); ?></td>
                                                <td><?php echo $payment['payment_method_name']; ?></td>
                                                <td><strong><?php echo $shipment['currency']; ?> <?php echo number_format($payment['amount'], 2); ?></strong></td>
                                                <td><?php echo $payment['reference_number'] ?: '-'; ?></td>
                                                <td>
                                                    <span class="badge bg-<?php echo $payment['status'] === 'COMPLETED' ? 'success' : ($payment['status'] === 'PENDING' ? 'warning' : 'danger'); ?>">
                                                        <?php echo $payment['status']; ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <?php if ($payment['status'] === 'COMPLETED'): ?>
                                                    <a href="generate_receipt.php?payment_id=<?php echo $payment['payment_id']; ?>" 
                                                       class="btn btn-outline-primary btn-sm" target="_blank">
                                                        <i class="bx bx-printer"></i> Receipt
                                                    </a>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <?php endif; ?>
                            </div>

                            <!-- Route Information -->
                            <div class="info-card">
                                <h5><i class="bx bx-map"></i> Route Information</h5>
                                <div class="route-display">
                                    <div class="route-point">
                                        <strong><?php echo $shipment['origin_location']; ?></strong>
                                        <br><small><?php echo $shipment['origin_city']; ?>, <?php echo $shipment['origin_country']; ?></small>
                                    </div>
                                    <div class="route-arrow">→</div>
                                    <div class="route-point">
                                        <strong><?php echo $shipment['destination_location']; ?></strong>
                                        <br><small><?php echo $shipment['destination_city']; ?>, <?php echo $shipment['destination_country']; ?></small>
                                    </div>
                                </div>
                                
                                <div class="row mt-3">
                                    <div class="col-md-6">
                                        <small class="text-muted">Service Type:</small>
                                        <div><strong><?php echo $shipment['service_name']; ?></strong></div>
                                        <small class="badge bg-secondary"><?php echo $shipment['service_category']; ?></small>
                                    </div>
                                    <div class="col-md-6">
                                        <small class="text-muted">Transit Time:</small>
                                        <div>
                                            <?php if ($shipment['transit_days_min'] && $shipment['transit_days_max']): ?>
                                                <?php echo $shipment['transit_days_min']; ?> - <?php echo $shipment['transit_days_max']; ?> days
                                            <?php else: ?>
                                                Standard delivery
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Sender & Receiver Information -->
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="info-card">
                                        <h5><i class="bx bx-user"></i> Sender Information</h5>
                                        <div class="address-block">
                                            <strong><?php echo htmlspecialchars($shipment['sender_name']); ?></strong>
                                            <?php if ($shipment['sender_company']): ?>
                                            <br><?php echo htmlspecialchars($shipment['sender_company']); ?>
                                            <?php endif; ?>
                                            <br><?php echo htmlspecialchars($shipment['sender_address']); ?>
                                            <br><?php echo htmlspecialchars($shipment['sender_city']); ?>
                                            <?php if ($shipment['sender_state']): ?>
                                            , <?php echo htmlspecialchars($shipment['sender_state']); ?>
                                            <?php endif; ?>
                                            <?php if ($shipment['sender_postal_code']): ?>
                                            <br><?php echo $shipment['sender_postal_code']; ?>
                                            <?php endif; ?>
                                            <br><?php echo htmlspecialchars($shipment['sender_country']); ?>
                                            
                                            <hr class="my-2">
                                            <small class="text-muted">Contact:</small>
                                            <br><strong><?php echo $shipment['sender_phone']; ?></strong>
                                            <?php if ($shipment['sender_email']): ?>
                                            <br><?php echo $shipment['sender_email']; ?>
                                            <?php endif; ?>
                                            
                                            <?php if ($shipment['sender_customer_name']): ?>
                                            <hr class="my-2">
                                            <small class="text-muted">Account:</small>
                                            <br><strong><?php echo $shipment['sender_customer_name']; ?></strong>
                                            <br><small><?php echo $shipment['sender_customer_code']; ?></small>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="info-card">
                                        <h5><i class="bx bx-user-pin"></i> Receiver Information</h5>
                                        <div class="address-block">
                                            <strong><?php echo htmlspecialchars($shipment['receiver_name']); ?></strong>
                                            <?php if ($shipment['receiver_company']): ?>
                                            <br><?php echo htmlspecialchars($shipment['receiver_company']); ?>
                                            <?php endif; ?>
                                            <br><?php echo htmlspecialchars($shipment['receiver_address']); ?>
                                            <br><?php echo htmlspecialchars($shipment['receiver_city']); ?>
                                            <?php if ($shipment['receiver_state']): ?>
                                            , <?php echo htmlspecialchars($shipment['receiver_state']); ?>
                                            <?php endif; ?>
                                            <?php if ($shipment['receiver_postal_code']): ?>
                                            <br><?php echo $shipment['receiver_postal_code']; ?>
                                            <?php endif; ?>
                                            <br><?php echo htmlspecialchars($shipment['receiver_country']); ?>
                                            
                                            <hr class="my-2">
                                            <small class="text-muted">Contact:</small>
                                            <br><strong><?php echo $shipment['receiver_phone']; ?></strong>
                                            <?php if ($shipment['receiver_email']): ?>
                                            <br><?php echo $shipment['receiver_email']; ?>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Package Details -->
                            <div class="info-card">
                                <h5><i class="bx bx-package"></i> Package Details</h5>
                                <div class="row">
                                    <div class="col-md-8">
                                        <div class="row">
                                            <div class="col-6">
                                                <small class="text-muted">Content:</small>
                                                <div><strong><?php echo htmlspecialchars($shipment['content_description']); ?></strong></div>
                                            </div>
                                            <div class="col-6">
                                                <small class="text-muted">Package Type:</small>
                                                <div><?php echo $shipment['package_type']; ?></div>
                                            </div>
                                        </div>
                                        
                                        <div class="row mt-3">
                                            <div class="col-4">
                                                <small class="text-muted">Pieces:</small>
                                                <div><strong><?php echo $shipment['pieces']; ?></strong></div>
                                            </div>
                                            <div class="col-4">
                                                <small class="text-muted">Actual Weight:</small>
                                                <div><?php echo $shipment['actual_weight']; ?> kg</div>
                                            </div>
                                            <div class="col-4">
                                                <small class="text-muted">Chargeable Weight:</small>
                                                <div><strong><?php echo $shipment['chargeable_weight']; ?> kg</strong></div>
                                            </div>
                                        </div>
                                        
                                        <?php if ($shipment['dimensions_length'] || $shipment['dimensions_width'] || $shipment['dimensions_height']): ?>
                                        <div class="row mt-3">
                                            <div class="col-12">
                                                <small class="text-muted">Dimensions (L × W × H):</small>
                                                <div>
                                                    <?php echo $shipment['dimensions_length'] ?? 0; ?> × 
                                                    <?php echo $shipment['dimensions_width'] ?? 0; ?> × 
                                                    <?php echo $shipment['dimensions_height'] ?? 0; ?> cm
                                                    <?php if ($shipment['volumetric_weight']): ?>
                                                    <br><small class="text-muted">Volumetric Weight: <?php echo $shipment['volumetric_weight']; ?> kg</small>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                    <div class="col-md-4">
                                        <small class="text-muted">Declared Value:</small>
                                        <div class="h5 text-primary">
                                            <?php echo $shipment['currency']; ?> <?php echo number_format($shipment['declared_value'], 2); ?>
                                        </div>
                                        
                                        <?php if ($has_restricted_items): ?>
                                        <div class="alert alert-warning py-2 px-3 mt-2">
                                            <i class="bx bx-error-circle"></i> Contains restricted items
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($has_hazardous_items): ?>
                                        <div class="alert alert-danger py-2 px-3 mt-2">
                                            <i class="bx bx-error-circle"></i> Contains hazardous items
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Charge Breakdown -->
                            <div class="info-card">
                                <h5><i class="bx bx-calculator"></i> Charge Breakdown</h5>
                                <div class="charge-breakdown">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="d-flex justify-content-between mb-2">
                                                <span>Freight Charges:</span>
                                                <strong><?php echo $shipment['currency']; ?> <?php echo number_format($shipment['freight_charges'], 2); ?></strong>
                                            </div>
                                            <div class="d-flex justify-content-between mb-2">
                                                <span>Fuel Surcharge:</span>
                                                <strong><?php echo $shipment['currency']; ?> <?php echo number_format($shipment['fuel_surcharge'], 2); ?></strong>
                                            </div>
                                            <div class="d-flex justify-content-between mb-2">
                                                <span>Insurance:</span>
                                                <strong><?php echo $shipment['currency']; ?> <?php echo number_format($shipment['insurance_charges'], 2); ?></strong>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="d-flex justify-content-between mb-2">
                                                <span>Handling Charges:</span>
                                                <strong><?php echo $shipment['currency']; ?> <?php echo number_format($shipment['handling_charges'], 2); ?></strong>
                                            </div>
                                            <div class="d-flex justify-content-between mb-2">
                                                <span>Customs Charges:</span>
                                                <strong><?php echo $shipment['currency']; ?> <?php echo number_format($shipment['customs_charges'], 2); ?></strong>
                                            </div>
                                            <div class="d-flex justify-content-between mb-2">
                                                <span>Other Charges:</span>
                                                <strong><?php echo $shipment['currency']; ?> <?php echo number_format($shipment['other_charges'], 2); ?></strong>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <hr>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="d-flex justify-content-between">
                                                <span>Tax Amount:</span>
                                                <strong><?php echo $shipment['currency']; ?> <?php echo number_format($shipment['tax_amount'], 2); ?></strong>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="d-flex justify-content-between h5 text-primary">
                                                <span>Total Charges:</span>
                                                <strong><?php echo $shipment['currency']; ?> <?php echo number_format($shipment['total_charges'], 2); ?></strong>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Commodities (if international shipment) -->
                            <?php if ($commodities->num_rows > 0): ?>
                            <div class="info-card">
                                <h5><i class="bx bx-box"></i> Commodity Details</h5>
                                <?php while ($commodity = $commodities->fetch_assoc()): ?>
                                <div class="commodity-item">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <strong><?php echo $commodity['commodity_name']; ?></strong>
                                            <br><small class="text-muted">HS Code: <?php echo $commodity['hs_code']; ?></small>
                                            
                                            <?php if ($commodity['is_restricted']): ?>
                                            <span class="badge bg-warning ms-2">Restricted</span>
                                            <?php endif; ?>
                                            
                                            <?php if ($commodity['is_hazardous']): ?>
                                            <span class="badge bg-danger ms-2">Hazardous</span>
                                            <?php endif; ?>
                                        </div>
                                        <div class="col-md-3">
                                            <small class="text-muted">Quantity:</small>
                                            <div><?php echo number_format($commodity['quantity'], 2); ?></div>
                                            
                                            <small class="text-muted">Unit Value:</small>
                                            <div>$<?php echo number_format($commodity['unit_value'], 2); ?></div>
                                        </div>
                                        <div class="col-md-3">
                                            <small class="text-muted">Total Value:</small>
                                            <div class="h6 text-primary">$<?php echo number_format($commodity['total_value'], 2); ?></div>
                                            
                                            <small class="text-muted">Duty Rate:</small>
                                            <div><?php echo $commodity['duty_rate']; ?>%</div>
                                        </div>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                                
                                <div class="mt-3 p-3 bg-light rounded">
                                    <div class="row">
                                        <div class="col-6">
                                            <strong>Total Declared Value:</strong>
                                        </div>
                                        <div class="col-6 text-end">
                                            <strong class="text-primary">$<?php echo number_format($total_declared_value, 2); ?></strong>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>

                            <!-- Special Instructions -->
                            <?php if ($shipment['special_instructions'] || $shipment['handling_instructions']): ?>
                            <div class="info-card">
                                <h5><i class="bx bx-info-circle"></i> Special Instructions</h5>
                                
                                <?php if ($shipment['special_instructions']): ?>
                                <div class="alert alert-info">
                                    <h6>Special Instructions:</h6>
                                    <?php echo nl2br(htmlspecialchars($shipment['special_instructions'])); ?>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($shipment['handling_instructions']): ?>
                                <div class="alert alert-warning">
                                    <h6>Handling Instructions:</h6>
                                    <?php echo nl2br(htmlspecialchars($shipment['handling_instructions'])); ?>
                                </div>
                                <?php endif; ?>
                            </div>
                            <?php endif; ?>

                            <!-- Pickup Information -->
                            <?php if ($shipment['pickup_required']): ?>
                            <div class="info-card">
                                <h5><i class="bx bx-calendar-check"></i> Pickup Information</h5>
                                <div class="row">
                                    <div class="col-md-4">
                                        <small class="text-muted">Pickup Date:</small>
                                        <div><strong><?php echo $shipment['pickup_date'] ? date('M j, Y', strtotime($shipment['pickup_date'])) : 'Not scheduled'; ?></strong></div>
                                    </div>
                                    <div class="col-md-4">
                                        <small class="text-muted">Time Window:</small>
                                        <div>
                                            <?php if ($shipment['pickup_time_from'] && $shipment['pickup_time_to']): ?>
                                                <?php echo date('H:i', strtotime($shipment['pickup_time_from'])); ?> - 
                                                <?php echo date('H:i', strtotime($shipment['pickup_time_to'])); ?>
                                            <?php else: ?>
                                                Standard hours
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <small class="text-muted">Status:</small>
                                        <div>
                                            <?php if ($shipment['collection_date']): ?>
                                                <span class="badge bg-success">Collected</span>
                                                <br><small><?php echo date('M j, Y H:i', strtotime($shipment['collection_date'])); ?></small>
                                            <?php else: ?>
                                                <span class="badge bg-warning">Pending</span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>

                            <!-- Documents -->
                            <?php if ($documents->num_rows > 0): ?>
                            <div class="info-card">
                                <h5><i class="bx bx-file"></i> Documents</h5>
                                <?php while ($document = $documents->fetch_assoc()): ?>
                                <div class="document-item">
                                    <div class="d-flex align-items-center">
                                        <i class="bx bx-file-blank me-3 fs-4"></i>
                                        <div>
                                            <strong><?php echo $document['document_name']; ?></strong>
                                            <br><small class="text-muted">
                                                <?php echo ucfirst(strtolower(str_replace('_', ' ', $document['document_type']))); ?> • 
                                                <?php echo $document['uploaded_by_name']; ?> • 
                                                <?php echo date('M j, Y H:i', strtotime($document['uploaded_at'])); ?>
                                            </small>
                                        </div>
                                    </div>
                                    <div>
                                        <a href="<?php echo $document['file_path']; ?>" class="btn btn-outline-primary btn-sm" target="_blank">
                                            <i class="bx bx-download"></i> Download
                                        </a>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                            </div>
                            <?php endif; ?>

                            <!-- Delivery Attempts -->
                            <?php if ($delivery_attempts->num_rows > 0): ?>
                            <div class="info-card">
                                <h5><i class="bx bx-truck"></i> Delivery Attempts</h5>
                                <?php while ($attempt = $delivery_attempts->fetch_assoc()): ?>
                                <div class="timeline-item">
                                    <div class="timeline-dot <?php echo $attempt['status'] === 'SUCCESSFUL' ? 'completed' : 'current'; ?>"></div>
                                    <div class="timeline-content">
                                        <div class="d-flex justify-content-between align-items-start mb-2">
                                            <div>
                                                <strong>Attempt #<?php echo $attempt['attempt_number']; ?></strong>
                                                <span class="badge bg-<?php echo $attempt['status'] === 'SUCCESSFUL' ? 'success' : ($attempt['status'] === 'FAILED' ? 'danger' : 'warning'); ?> ms-2">
                                                    <?php echo ucfirst(strtolower($attempt['status'])); ?>
                                                </span>
                                            </div>
                                            <small class="text-muted"><?php echo date('M j, Y H:i', strtotime($attempt['attempt_date'])); ?></small>
                                        </div>
                                        
                                        <?php if ($attempt['driver_first_name']): ?>
                                        <div class="mb-2">
                                            <small class="text-muted">Driver:</small>
                                            <?php echo $attempt['driver_first_name'] . ' ' . $attempt['driver_last_name']; ?>
                                            <?php if ($attempt['driver_phone']): ?>
                                            (<?php echo $attempt['driver_phone']; ?>)
                                            <?php endif; ?>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($attempt['delivered_to']): ?>
                                        <div class="mb-2">
                                            <small class="text-muted">Delivered to:</small>
                                            <strong><?php echo $attempt['delivered_to']; ?></strong>
                                            <?php if ($attempt['delivery_location']): ?>
                                            at <?php echo $attempt['delivery_location']; ?>
                                            <?php endif; ?>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($attempt['failure_reason']): ?>
                                        <div class="mb-2">
                                            <small class="text-muted">Reason:</small>
                                            <?php echo $attempt['failure_reason']; ?>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($attempt['delivery_notes']): ?>
                                        <div class="mb-2">
                                            <small class="text-muted">Notes:</small>
                                            <?php echo nl2br(htmlspecialchars($attempt['delivery_notes'])); ?>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <div class="d-flex gap-2">
                                            <?php if ($attempt['signature_image']): ?>
                                            <a href="<?php echo $attempt['signature_image']; ?>" class="btn btn-outline-primary btn-sm" target="_blank">
                                                <i class="bx bx-edit"></i> View Signature
                                            </a>
                                            <?php endif; ?>
                                            
                                            <?php if ($attempt['photo_proof']): ?>
                                            <a href="<?php echo $attempt['photo_proof']; ?>" class="btn btn-outline-secondary btn-sm" target="_blank">
                                                <i class="bx bx-camera"></i> View Photo
                                            </a>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                            </div>
                            <?php endif; ?>
                        </div>

                        <!-- Right Column -->
                        <div class="col-xl-4">
                            <!-- Shipment Summary -->
                            <div class="info-card">
                                <h5><i class="bx bx-info-circle"></i> Shipment Summary</h5>
                                <div class="row g-3">
                                    <div class="col-6">
                                        <small class="text-muted">Booking Date:</small>
                                        <div><strong><?php echo date('M j, Y', strtotime($shipment['booking_date'])); ?></strong></div>
                                        <small><?php echo date('H:i', strtotime($shipment['booking_date'])); ?></small>
                                    </div>
                                    <div class="col-6">
                                        <small class="text-muted">Estimated Delivery:</small>
                                        <div>
                                            <?php if ($shipment['estimated_delivery']): ?>
                                                <strong><?php echo date('M j, Y', strtotime($shipment['estimated_delivery'])); ?></strong>
                                            <?php else: ?>
                                                TBD
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <small class="text-muted">Payment Status:</small>
                                        <div>
                                            <span class="badge bg-<?php echo $shipment['payment_status'] === 'PAID' ? 'success' : ($shipment['payment_status'] === 'PARTIAL' ? 'warning' : 'danger'); ?>">
                                                <?php echo ucfirst(strtolower($shipment['payment_status'])); ?>
                                            </span>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <small class="text-muted">Customs Status:</small>
                                        <div>
                                            <?php if ($shipment['customs_status']): ?>
                                                <span class="badge bg-<?php echo $shipment['customs_status'] === 'CLEARED' ? 'success' : ($shipment['customs_status'] === 'PENDING' ? 'warning' : 'danger'); ?>">
                                                    <?php echo ucfirst(strtolower($shipment['customs_status'])); ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="badge bg-secondary">N/A</span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                                
                                <hr>
                                
                                <div class="row g-3">
                                    <div class="col-6">
                                        <small class="text-muted">Created By:</small>
                                        <div><?php echo $shipment['created_by_name']; ?></div>
                                    </div>
                                    <div class="col-6">
                                        <small class="text-muted">Last Updated:</small>
                                        <div><?php echo $shipment['updated_by_name'] ? $shipment['updated_by_name'] : 'N/A'; ?></div>
                                        <?php if ($shipment['updated_at'] && $shipment['updated_at'] !== $shipment['created_at']): ?>
                                        <small><?php echo date('M j, H:i', strtotime($shipment['updated_at'])); ?></small>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <?php if ($shipment['reference_number'] || $shipment['customer_reference']): ?>
                                <hr>
                                <div class="row g-3">
                                    <?php if ($shipment['reference_number']): ?>
                                    <div class="col-12">
                                        <small class="text-muted">Reference Number:</small>
                                        <div><code><?php echo $shipment['reference_number']; ?></code></div>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($shipment['customer_reference']): ?>
                                    <div class="col-12">
                                        <small class="text-muted">Customer Reference:</small>
                                        <div><code><?php echo $shipment['customer_reference']; ?></code></div>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                <?php endif; ?>
                            </div>

                            <!-- Customs Declaration -->
                            <?php if ($customs_declaration): ?>
                            <div class="info-card">
                                <h5><i class="bx bx-shield-check"></i> Customs Declaration</h5>
                                <div class="row g-2">
                                    <div class="col-12">
                                        <small class="text-muted">Declaration Number:</small>
                                        <div><strong><?php echo $customs_declaration['declaration_number'] ?? 'Pending'; ?></strong></div>
                                    </div>
                                    <div class="col-6">
                                        <small class="text-muted">Type:</small>
                                        <div><?php echo ucfirst(strtolower($customs_declaration['declaration_type'])); ?></div>
                                    </div>
                                    <div class="col-6">
                                        <small class="text-muted">Status:</small>
                                        <div>
                                            <span class="badge bg-<?php echo $customs_declaration['status'] === 'CLEARED' ? 'success' : ($customs_declaration['status'] === 'PENDING' ? 'warning' : 'danger'); ?>">
                                                <?php echo ucfirst(strtolower($customs_declaration['status'])); ?>
                                            </span>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <small class="text-muted">Customs Value:</small>
                                        <div><strong><?php echo $customs_declaration['currency']; ?> <?php echo number_format($customs_declaration['customs_value'], 2); ?></strong></div>
                                    </div>
                                    <div class="col-6">
                                        <small class="text-muted">Total Charges:</small>
                                        <div><strong><?php echo $customs_declaration['currency']; ?> <?php echo number_format($customs_declaration['total_charges'], 2); ?></strong></div>
                                    </div>
                                    
                                    <?php if ($customs_declaration['submission_date']): ?>
                                    <div class="col-12">
                                        <small class="text-muted">Submitted:</small>
                                        <div><?php echo date('M j, Y H:i', strtotime($customs_declaration['submission_date'])); ?></div>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($customs_declaration['clearance_date']): ?>
                                    <div class="col-12">
                                        <small class="text-muted">Cleared:</small>
                                        <div><?php echo date('M j, Y H:i', strtotime($customs_declaration['clearance_date'])); ?></div>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($customs_declaration['remarks']): ?>
                                    <div class="col-12">
                                        <small class="text-muted">Remarks:</small>
                                        <div><?php echo nl2br(htmlspecialchars($customs_declaration['remarks'])); ?></div>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <?php endif; ?>

                            <!-- Tracking Timeline -->
                            <div class="info-card">
                                <h5><i class="bx bx-time"></i> Tracking History</h5>
                                <div class="timeline-container">
                                    <?php if ($tracking_events->num_rows > 0): ?>
                                        <?php while ($event = $tracking_events->fetch_assoc()): ?>
                                        <div class="timeline-item">
                                            <div class="timeline-dot <?php echo $event['event_type'] === $shipment['status'] ? 'current' : 'completed'; ?>"></div>
                                            <div class="timeline-content">
                                                <div class="d-flex justify-content-between align-items-start mb-2">
                                                    <div>
                                                        <strong><?php echo formatStatus($event['event_status']); ?></strong>
                                                        <?php if ($event['event_type'] === 'NOTE'): ?>
                                                        <span class="badge bg-info ms-2">Note</span>
                                                        <?php endif; ?>
                                                    </div>
                                                    <small class="text-muted"><?php echo date('M j, H:i', strtotime($event['event_date'])); ?></small>
                                                </div>
                                                
                                                <?php if ($event['event_description']): ?>
                                                <p class="mb-2"><?php echo nl2br(htmlspecialchars($event['event_description'])); ?></p>
                                                <?php endif; ?>
                                                
                                                <?php if ($event['location']): ?>
                                                <div class="d-flex align-items-center mb-2">
                                                    <i class="bx bx-map-pin me-2 text-muted"></i>
                                                    <small><?php echo $event['location']; ?></small>
                                                </div>
                                                <?php endif; ?>
                                                
                                                <?php if ($event['created_by_name']): ?>
                                                <div class="d-flex align-items-center">
                                                    <i class="bx bx-user me-2 text-muted"></i>
                                                    <small class="text-muted"><?php echo $event['created_by_name']; ?></small>
                                                </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <p class="text-muted">No tracking events available.</p>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Update Status Modal -->
    <div class="modal fade" id="updateStatusModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST">
                    <div class="modal-header">
                        <h5 class="modal-title">Update Shipment Status</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="action" value="update_status">
                        
                        <div class="mb-3">
                            <label class="form-label">Current Status</label>
                            <input type="text" class="form-control" value="<?php echo formatStatus($shipment['status']); ?>" readonly>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">New Status <span class="text-danger">*</span></label>
                            <select name="new_status" class="form-select" required>
                                <option value="">Select Status</option>
                                <option value="BOOKED" <?php echo $shipment['status'] === 'DRAFT' ? '' : 'disabled'; ?>>Booked</option>
                                <option value="COLLECTED" <?php echo in_array($shipment['status'], ['BOOKED', 'DRAFT']) ? '' : 'disabled'; ?>>Collected</option>
                                <option value="IN_TRANSIT" <?php echo in_array($shipment['status'], ['COLLECTED', 'BOOKED']) ? '' : 'disabled'; ?>>In Transit</option>
                                <option value="OUT_FOR_DELIVERY" <?php echo in_array($shipment['status'], ['IN_TRANSIT', 'COLLECTED']) ? '' : 'disabled'; ?>>Out for Delivery</option>
                                <option value="DELIVERED" <?php echo $shipment['status'] === 'OUT_FOR_DELIVERY' ? '' : 'disabled'; ?>>Delivered</option>
                                <option value="RETURNED">Returned</option>
                                <option value="CANCELLED">Cancelled</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Location</label>
                            <input type="text" name="location" class="form-control" placeholder="Current location">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Notes</label>
                            <textarea name="notes" class="form-control" rows="3" placeholder="Additional notes about status update"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Update Status</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Process Payment Modal -->
    <div class="modal fade" id="processPaymentModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <form method="POST" id="paymentForm">
                    <div class="modal-header">
                        <h5 class="modal-title">Process Payment</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="action" value="process_payment">
                        
                        <!-- Payment Summary -->
                        <div class="row mb-4">
                            <div class="col-md-4">
                                <div class="bg-light p-3 rounded text-center">
                                    <small class="text-muted">Total Amount</small>
                                    <div class="h5 text-primary"><?php echo $shipment['currency']; ?> <?php echo number_format($shipment['total_charges'], 2); ?></div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="bg-light p-3 rounded text-center">
                                    <small class="text-muted">Paid Amount</small>
                                    <div class="h5 text-success"><?php echo $shipment['currency']; ?> <?php echo number_format($total_paid, 2); ?></div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="bg-light p-3 rounded text-center">
                                    <small class="text-muted">Outstanding</small>
                                    <div class="h5 text-danger"><?php echo $shipment['currency']; ?> <span id="outstandingAmount"><?php echo number_format($outstanding_amount, 2); ?></span></div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Payment Amount <span class="text-danger">*</span></label>
                                    <div class="input-group">
                                        <span class="input-group-text"><?php echo $shipment['currency']; ?></span>
                                        <input type="number" name="payment_amount" class="form-control" 
                                               step="0.01" min="0.01" max="<?php echo $outstanding_amount; ?>"
                                               value="<?php echo $outstanding_amount; ?>" required>
                                    </div>
                                    <div class="form-text">Maximum: <?php echo $shipment['currency']; ?> <?php echo number_format($outstanding_amount, 2); ?></div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Payment Method <span class="text-danger">*</span></label>
                                    <select name="payment_method_id" class="form-select" required>
                                        <option value="">Select Method</option>
                                        <?php 
                                        // Reset the result set
                                        $payment_methods_result->data_seek(0);
                                        while ($method = $payment_methods_result->fetch_assoc()): ?>
                                        <option value="<?php echo $method['method_id']; ?>" data-name="<?php echo $method['method_name']; ?>">
                                            <?php echo $method['method_name']; ?>
                                        </option>
                                        <?php endwhile; ?>
                                    </select>
                                    <input type="hidden" name="payment_method_name" id="paymentMethodName">
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Reference Number</label>
                                    <input type="text" name="payment_reference" class="form-control" 
                                           placeholder="Transaction reference, check number, etc.">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Payment Notes</label>
                                    <textarea name="payment_notes" class="form-control" rows="2" 
                                             placeholder="Additional notes about payment"></textarea>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-check">
                            <input type="checkbox" name="generate_receipt" class="form-check-input" id="generateReceipt" checked>
                            <label class="form-check-label" for="generateReceipt">
                                Generate and print receipt after processing payment
                            </label>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="bx bx-credit-card"></i> Process Payment
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Note Modal -->
    <div class="modal fade" id="addNoteModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST">
                    <div class="modal-header">
                        <h5 class="modal-title">Add Note</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="action" value="add_note">
                        
                        <div class="mb-3">
                            <label class="form-label">Note <span class="text-danger">*</span></label>
                            <textarea name="note_text" class="form-control" rows="4" placeholder="Enter your note here..." required></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Location</label>
                            <input type="text" name="location" class="form-control" placeholder="Current location (optional)">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Add Note</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Payment form handling
            const paymentForm = document.getElementById('paymentForm');
            const paymentMethodSelect = document.querySelector('select[name="payment_method_id"]');
            const paymentMethodNameInput = document.getElementById('paymentMethodName');
            
            if (paymentMethodSelect && paymentMethodNameInput) {
                paymentMethodSelect.addEventListener('change', function() {
                    const selectedOption = this.options[this.selectedIndex];
                    paymentMethodNameInput.value = selectedOption.dataset.name || '';
                });
            }
            
            // Payment amount validation
            const paymentAmountInput = document.querySelector('input[name="payment_amount"]');
            const maxAmount = <?php echo $outstanding_amount; ?>;
            
            if (paymentAmountInput) {
                paymentAmountInput.addEventListener('input', function() {
                    const amount = parseFloat(this.value);
                    if (amount > maxAmount) {
                        this.value = maxAmount;
                    }
                    if (amount <= 0) {
                        this.value = 0.01;
                    }
                });
            }
            
            // Form submission confirmation
            if (paymentForm) {
                paymentForm.addEventListener('submit', function(e) {
                    const amount = parseFloat(document.querySelector('input[name="payment_amount"]').value);
                    const method = document.querySelector('select[name="payment_method_id"]').selectedOptions[0].text;
                    
                    if (!confirm(`Process payment of ${amount.toFixed(2)} <?php echo $shipment['currency']; ?> via ${method}?`)) {
                        e.preventDefault();
                        return false;
                    }
                });
            }
        });
    </script>

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