<?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();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$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'];
}

// Get filters from URL parameters
$status_filter = $_GET['status'] ?? '';
$service_filter = $_GET['service'] ?? '';
$origin_filter = $_GET['origin'] ?? '';
$destination_filter = $_GET['destination'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$search = $_GET['search'] ?? '';
$payment_status_filter = $_GET['payment_status'] ?? '';

// Pagination setup
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$records_per_page = 20;
$offset = ($page - 1) * $records_per_page;

// Build WHERE clause for filters
$where_conditions = [];
$params = [];
$param_types = '';

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

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

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

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

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

if (!empty($date_from)) {
    $where_conditions[] = "DATE(s.booking_date) >= ?";
    $params[] = $date_from;
    $param_types .= 's';
}

if (!empty($date_to)) {
    $where_conditions[] = "DATE(s.booking_date) <= ?";
    $params[] = $date_to;
    $param_types .= 's';
}

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

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Get total records for pagination
$count_sql = "SELECT COUNT(*) as total FROM shipments s $where_clause";

if (!empty($params)) {
    $count_stmt = $conn->prepare($count_sql);
    $count_stmt->bind_param($param_types, ...$params);
    $count_stmt->execute();
    $total_records = $count_stmt->get_result()->fetch_assoc()['total'];
} else {
    $total_records = $conn->query($count_sql)->fetch_assoc()['total'];
}

$total_pages = ceil($total_records / $records_per_page);

// Get shipments with detailed information
$shipments_sql = "SELECT 
    s.shipment_id,
    s.tracking_number,
    s.reference_number,
    s.customer_reference,
    s.sender_name,
    s.sender_company,
    s.sender_phone,
    s.sender_email,
    s.receiver_name,
    s.receiver_company,
    s.receiver_phone,
    s.receiver_email,
    s.receiver_city,
    s.receiver_country,
    s.status,
    s.payment_status,
    s.customs_status,
    s.booking_date,
    s.estimated_delivery,
    s.pickup_date,
    s.delivery_date,
    s.pieces,
    s.actual_weight,
    s.volumetric_weight,
    s.chargeable_weight,
    s.total_charges,
    s.declared_value,
    s.currency,
    s.special_instructions,
    s.content_description,
    st.service_name,
    st.service_category,
    ol.location_name as origin_location,
    ol.city as origin_city,
    dl.location_name as destination_location,
    dl.city as destination_city,
    oc.country_name as origin_country,
    dc.country_name as destination_country,
    u.full_name as created_by_name,
    c.customer_code,
    c.customer_type,
    CASE 
        WHEN c.customer_type = 'CORPORATE' THEN c.company_name 
        ELSE CONCAT(c.first_name, ' ', c.last_name) 
    END as customer_name,
    DATEDIFF(CURDATE(), s.booking_date) as days_since_booking,
    CASE 
        WHEN s.estimated_delivery < CURDATE() AND s.status NOT IN ('DELIVERED', 'CANCELLED') THEN 'OVERDUE'
        WHEN s.estimated_delivery = CURDATE() AND s.status NOT IN ('DELIVERED', 'CANCELLED') THEN 'DUE_TODAY'
        ELSE 'NORMAL'
    END as urgency_status
FROM shipments s
LEFT JOIN customers c ON s.sender_customer_id = c.customer_id
LEFT JOIN service_types st ON s.service_id = st.service_id
LEFT JOIN locations ol ON s.origin_location_id = ol.location_id
LEFT JOIN locations dl ON s.destination_location_id = dl.location_id
LEFT JOIN countries oc ON ol.country_id = oc.country_id
LEFT JOIN countries dc ON dl.country_id = dc.country_id
LEFT JOIN users u ON s.created_by = u.user_id
$where_clause
ORDER BY 
    CASE WHEN s.status = 'DRAFT' THEN 0 ELSE 1 END,
    CASE WHEN s.status = 'BOOKED' THEN 0 ELSE 1 END,
    CASE WHEN s.status = 'OUT_FOR_DELIVERY' THEN 0 ELSE 1 END,
    s.booking_date DESC
LIMIT ? OFFSET ?";

// Add pagination parameters
$params[] = $records_per_page;
$params[] = $offset;
$param_types .= 'ii';

$stmt_shipments = $conn->prepare($shipments_sql);
if (!empty($params)) {
    $stmt_shipments->bind_param($param_types, ...$params);
}
$stmt_shipments->execute();
$shipments_result = $stmt_shipments->get_result();

// Get filter options
$service_types = $conn->query("SELECT service_id, service_name, service_category FROM service_types WHERE is_active = 1 ORDER BY service_name");
$locations = $conn->query("SELECT location_id, location_name, city, country_id FROM locations WHERE is_active = 1 ORDER BY location_name");

// Get summary statistics with current filters
$stats_sql = "SELECT 
    COUNT(*) as total_shipments,
    COUNT(CASE WHEN status = 'DELIVERED' THEN 1 END) as delivered,
    COUNT(CASE WHEN status = 'IN_TRANSIT' THEN 1 END) as in_transit,
    COUNT(CASE WHEN status IN ('DRAFT', 'BOOKED') THEN 1 END) as pending,
    COUNT(CASE WHEN status = 'OUT_FOR_DELIVERY' THEN 1 END) as out_for_delivery,
    COUNT(CASE WHEN status = 'CANCELLED' THEN 1 END) as cancelled,
    COUNT(CASE WHEN payment_status = 'PAID' THEN 1 END) as paid,
    COUNT(CASE WHEN payment_status = 'PENDING' THEN 1 END) as payment_pending,
    SUM(CASE WHEN payment_status = 'PAID' THEN total_charges ELSE 0 END) as total_revenue,
    SUM(chargeable_weight) as total_weight,
    COUNT(CASE WHEN estimated_delivery < CURDATE() AND status NOT IN ('DELIVERED', 'CANCELLED') THEN 1 END) as overdue_shipments
FROM shipments s
$where_clause";

if (!empty($where_conditions)) {
    $stats_stmt = $conn->prepare($stats_sql);
    if (!empty($params)) {
        // Remove pagination parameters for stats
        $stats_params = array_slice($params, 0, -2);
        $stats_param_types = substr($param_types, 0, -2);
        if (!empty($stats_params)) {
            $stats_stmt->bind_param($stats_param_types, ...$stats_params);
        }
    }
    $stats_stmt->execute();
    $stats = $stats_stmt->get_result()->fetch_assoc();
} else {
    $stats = $conn->query($stats_sql)->fetch_assoc();
}

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Shipments - Freight Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        .page-header {
            background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }
        
        .header-title h1 {
            font-size: 2rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .header-actions {
            display: flex;
            gap: 1rem;
            align-items: center;
        }
        
        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            transition: all 0.2s;
            border: none;
            cursor: pointer;
            font-size: 0.875rem;
        }
        
        .btn-white {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: 1px solid rgba(255, 255, 255, 0.3);
        }
        
        .btn-white:hover {
            background: rgba(255, 255, 255, 0.3);
            color: white;
        }
        
        .btn-success {
            background: #059669;
            color: white;
        }
        
        .btn-success:hover {
            background: #047857;
            color: white;
        }
        
        .btn-primary {
            background: #3b82f6;
            color: white;
        }
        
        .btn-sm {
            padding: 0.5rem 1rem;
            font-size: 0.75rem;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            transition: all 0.2s;
        }
        
        .stat-card:hover {
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            transform: translateY(-1px);
        }
        
        .stat-title {
            font-size: 0.875rem;
            font-weight: 500;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            margin-bottom: 0.5rem;
        }
        
        .stat-value {
            font-size: 1.875rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }
        
        .stat-subtitle {
            font-size: 0.75rem;
            color: #64748b;
        }
        
        .filters-section {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
        }
        
        .filters-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
        }
        
        .filters-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
        }
        
        .filters-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 1rem;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
        }
        
        .form-label {
            font-size: 0.875rem;
            font-weight: 500;
            color: #374151;
            margin-bottom: 0.5rem;
        }
        
        .form-control {
            padding: 0.75rem;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            font-size: 0.875rem;
            background: white;
            transition: all 0.2s;
        }
        
        .form-control:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        
        .shipments-table {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
            margin-bottom: 2rem;
        }
        
        .table-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .table-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .table-responsive {
            overflow-x: auto;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.875rem;
        }
        
        .data-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            color: #374151;
            border-bottom: 1px solid #e2e8f0;
            white-space: nowrap;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            vertical-align: top;
        }
        
        .data-table tbody tr:hover {
            background: #f8fafc;
        }
        
        .data-table tbody tr.overdue {
            background: #fef2f2;
            border-left: 4px solid #ef4444;
        }
        
        .data-table tbody tr.due-today {
            background: #fffbeb;
            border-left: 4px solid #f59e0b;
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            display: inline-block;
        }
        
        .status-draft { background: #f3f4f6; color: #374151; }
        .status-booked { background: #dbeafe; color: #1d4ed8; }
        .status-collected { background: #d1fae5; color: #059669; }
        .status-in_transit { background: #fef3c7; color: #d97706; }
        .status-out_for_delivery { background: #e0e7ff; color: #5b21b6; }
        .status-delivered { background: #dcfce7; color: #166534; }
        .status-returned { background: #fee2e2; color: #991b1b; }
        .status-cancelled { background: #fecaca; color: #7f1d1d; }
        
        .payment-badge {
            font-size: 0.75rem;
            padding: 0.125rem 0.5rem;
            border-radius: 4px;
            font-weight: 500;
        }
        
        .payment-paid { background: #dcfce7; color: #166534; }
        .payment-pending { background: #fef3c7; color: #d97706; }
        .payment-partial { background: #e0e7ff; color: #5b21b6; }
        .payment-overdue { background: #fee2e2; color: #991b1b; }
        
        .shipment-details {
            display: flex;
            flex-direction: column;
            gap: 0.25rem;
        }
        
        .tracking-link {
            color: #1e40af;
            text-decoration: none;
            font-weight: 600;
        }
        
        .tracking-link:hover {
            color: #1d4ed8;
            text-decoration: underline;
        }
        
        .customer-info {
            display: flex;
            flex-direction: column;
            gap: 0.25rem;
        }
        
        .customer-name {
            font-weight: 600;
            color: #1e293b;
        }
        
        .customer-type {
            font-size: 0.75rem;
            color: #64748b;
        }
        
        .route-info {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }
        
        .location {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.875rem;
        }
        
        .location-icon {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            flex-shrink: 0;
        }
        
        .origin-icon { background: #059669; }
        .destination-icon { background: #dc2626; }
        
        .quick-actions {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }
        
        .action-btn {
            padding: 0.25rem 0.75rem;
            font-size: 0.75rem;
            border-radius: 6px;
            text-decoration: none;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
            justify-content: center;
            transition: all 0.2s;
        }
        
        .action-view { background: #3b82f6; color: white; }
        .action-track { background: #059669; color: white; }
        .action-edit { background: #d97706; color: white; }
        .action-invoice { background: #7c3aed; color: white; }
        
        .action-btn:hover {
            opacity: 0.9;
            transform: translateY(-1px);
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 1rem;
            margin-top: 2rem;
        }
        
        .page-link {
            padding: 0.5rem 1rem;
            border: 1px solid #d1d5db;
            color: #374151;
            text-decoration: none;
            border-radius: 6px;
            transition: all 0.2s;
        }
        
        .page-link:hover {
            background: #f3f4f6;
        }
        
        .page-link.active {
            background: #3b82f6;
            border-color: #3b82f6;
            color: white;
        }
        
        .page-info {
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .no-data {
            text-align: center;
            padding: 3rem;
            color: #64748b;
        }
        
        .no-data i {
            font-size: 3rem;
            margin-bottom: 1rem;
            color: #d1d5db;
        }
        
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .header-content {
                flex-direction: column;
                text-align: center;
            }
            
            .header-actions {
                width: 100%;
                justify-content: center;
                flex-wrap: wrap;
            }
            
            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .filters-grid {
                grid-template-columns: 1fr;
            }
            
            .data-table {
                font-size: 0.75rem;
            }
            
            .data-table th,
            .data-table td {
                padding: 0.5rem;
            }
            
            .quick-actions {
                flex-direction: row;
                flex-wrap: wrap;
            }
        }
    </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 Header -->
                    <div class="page-header">
                        <div class="header-content">
                            <div class="header-title">
                                <h1>Shipments Management</h1>
                                <p>Track and manage all freight shipments across your network</p>
                            </div>
                            <div class="header-actions">
                                <a href="create_shipment.php" class="btn btn-success">
                                    <i class="bx bx-plus"></i> New Shipment
                                </a>
                                <a href="track_shipment.php" class="btn btn-white">
                                    <i class="bx bx-search"></i> Track
                                </a>
                                <a href="rate_calculator.php" class="btn btn-white">
                                    <i class="bx bx-calculator"></i> Calculator
                                </a>
                                <a href="export_shipments.php?<?php echo http_build_query($_GET); ?>" class="btn btn-white">
                                    <i class="bx bx-download"></i> Export
                                </a>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="stats-grid">
                        <div class="stat-card">
                            <div class="stat-title">Total Shipments</div>
                            <div class="stat-value"><?php echo number_format($stats['total_shipments']); ?></div>
                            <div class="stat-subtitle">All records</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-title">Delivered</div>
                            <div class="stat-value"><?php echo number_format($stats['delivered']); ?></div>
                            <div class="stat-subtitle">Successfully completed</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-title">In Transit</div>
                            <div class="stat-value"><?php echo number_format($stats['in_transit']); ?></div>
                            <div class="stat-subtitle">Currently shipping</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-title">Out for Delivery</div>
                            <div class="stat-value"><?php echo number_format($stats['out_for_delivery']); ?></div>
                            <div class="stat-subtitle">Final mile</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-title">Pending</div>
                            <div class="stat-value"><?php echo number_format($stats['pending']); ?></div>
                            <div class="stat-subtitle">Awaiting processing</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-title">Total Revenue</div>
                            <div class="stat-value">KSh <?php echo number_format($stats['total_revenue']); ?></div>
                            <div class="stat-subtitle">From paid shipments</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-title">Overdue</div>
                            <div class="stat-value"><?php echo number_format($stats['overdue_shipments']); ?></div>
                            <div class="stat-subtitle">Past due date</div>
                        </div>
                    </div>

                    <!-- Filters Section -->
                    <div class="filters-section">
                        <div class="filters-header">
                            <h3 class="filters-title">Filter Shipments</h3>
                            <a href="shipments.php" class="btn btn-sm btn-primary">Clear All Filters</a>
                        </div>
                        
                        <form method="GET" action="shipments.php">
                            <div class="filters-grid">
                                <div class="form-group">
                                    <label class="form-label">Search</label>
                                    <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" 
                                           class="form-control" placeholder="Tracking #, sender, receiver, reference...">
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label">Status</label>
                                    <select name="status" class="form-control">
                                        <option value="">All Status</option>
                                        <option value="DRAFT" <?php echo $status_filter === 'DRAFT' ? 'selected' : ''; ?>>Draft</option>
                                        <option value="BOOKED" <?php echo $status_filter === 'BOOKED' ? 'selected' : ''; ?>>Booked</option>
                                        <option value="COLLECTED" <?php echo $status_filter === 'COLLECTED' ? 'selected' : ''; ?>>Collected</option>
                                        <option value="IN_TRANSIT" <?php echo $status_filter === 'IN_TRANSIT' ? 'selected' : ''; ?>>In Transit</option>
                                        <option value="OUT_FOR_DELIVERY" <?php echo $status_filter === 'OUT_FOR_DELIVERY' ? 'selected' : ''; ?>>Out for Delivery</option>
                                        <option value="DELIVERED" <?php echo $status_filter === 'DELIVERED' ? 'selected' : ''; ?>>Delivered</option>
                                        <option value="RETURNED" <?php echo $status_filter === 'RETURNED' ? 'selected' : ''; ?>>Returned</option>
                                        <option value="CANCELLED" <?php echo $status_filter === 'CANCELLED' ? 'selected' : ''; ?>>Cancelled</option>
                                    </select>
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label">Payment Status</label>
                                    <select name="payment_status" class="form-control">
                                        <option value="">All Payment Status</option>
                                        <option value="PENDING" <?php echo $payment_status_filter === 'PENDING' ? 'selected' : ''; ?>>Pending</option>
                                        <option value="PAID" <?php echo $payment_status_filter === 'PAID' ? 'selected' : ''; ?>>Paid</option>
                                        <option value="PARTIAL" <?php echo $payment_status_filter === 'PARTIAL' ? 'selected' : ''; ?>>Partial</option>
                                        <option value="OVERDUE" <?php echo $payment_status_filter === 'OVERDUE' ? 'selected' : ''; ?>>Overdue</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">Service Type</label>
                                    <select name="service" class="form-control">
                                        <option value="">All Services</option>
                                        <?php while ($service = $service_types->fetch_assoc()): ?>
                                        <option value="<?php echo $service['service_id']; ?>" 
                                                <?php echo $service_filter == $service['service_id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($service['service_name']); ?> (<?php echo $service['service_category']; ?>)
                                        </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label">Origin Location</label>
                                    <select name="origin" class="form-control">
                                        <option value="">All Origins</option>
                                        <?php 
                                        $locations->data_seek(0);
                                        while ($location = $locations->fetch_assoc()): 
                                        ?>
                                        <option value="<?php echo $location['location_id']; ?>" 
                                                <?php echo $origin_filter == $location['location_id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($location['location_name'] . ' - ' . $location['city']); ?>
                                        </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label">Destination Location</label>
                                    <select name="destination" class="form-control">
                                        <option value="">All Destinations</option>
                                        <?php 
                                        $locations->data_seek(0);
                                        while ($location = $locations->fetch_assoc()): 
                                        ?>
                                        <option value="<?php echo $location['location_id']; ?>" 
                                                <?php echo $destination_filter == $location['location_id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($location['location_name'] . ' - ' . $location['city']); ?>
                                        </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label">Date From</label>
                                    <input type="date" name="date_from" value="<?php echo htmlspecialchars($date_from); ?>" class="form-control">
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label">Date To</label>
                                    <input type="date" name="date_to" value="<?php echo htmlspecialchars($date_to); ?>" class="form-control">
                                </div>
                            </div>
                            
                            <div style="display: flex; gap: 1rem; justify-content: flex-end;">
                                <button type="submit" class="btn btn-primary">
                                    <i class="bx bx-filter"></i> Apply Filters
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- Shipments Table -->
                    <div class="shipments-table">
                        <div class="table-header">
                            <h3 class="table-title">
                                Shipments 
                                <span style="font-weight: normal; color: #64748b;">
                                    (<?php echo number_format($total_records); ?> total)
                                </span>
                            </h3>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th>Tracking Info</th>
                                        <th>Customer</th>
                                        <th>Route</th>
                                        <th>Service</th>
                                        <th>Status</th>
                                        <th>Payment</th>
                                        <th>Weight/Pieces</th>
                                        <th>Amount</th>
                                        <th>Dates</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if ($shipments_result->num_rows > 0): ?>
                                        <?php while ($shipment = $shipments_result->fetch_assoc()): ?>
                                        <tr class="<?php 
                                            if ($shipment['urgency_status'] === 'OVERDUE') echo 'overdue';
                                            elseif ($shipment['urgency_status'] === 'DUE_TODAY') echo 'due-today';
                                        ?>">
                                            <td>
                                                <div class="shipment-details">
                                                    <a href="view_shipment.php?id=<?php echo $shipment['shipment_id']; ?>" 
                                                       class="tracking-link">
                                                        <?php echo htmlspecialchars($shipment['tracking_number']); ?>
                                                    </a>
                                                    <?php if ($shipment['reference_number']): ?>
                                                    <small style="color: #64748b;">
                                                        Ref: <?php echo htmlspecialchars($shipment['reference_number']); ?>
                                                    </small>
                                                    <?php endif; ?>
                                                    <?php if ($shipment['customer_reference']): ?>
                                                    <small style="color: #64748b;">
                                                        Customer Ref: <?php echo htmlspecialchars($shipment['customer_reference']); ?>
                                                    </small>
                                                    <?php endif; ?>
                                                    <small style="color: #64748b;">
                                                        <?php echo date('d/M/Y H:i', strtotime($shipment['booking_date'])); ?>
                                                        (<?php echo $shipment['days_since_booking']; ?> days ago)
                                                    </small>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="customer-info">
                                                    <?php if ($shipment['customer_name']): ?>
                                                    <div class="customer-name">
                                                        <?php echo htmlspecialchars($shipment['customer_name']); ?>
                                                    </div>
                                                    <div class="customer-type">
                                                        <?php echo htmlspecialchars($shipment['customer_code']); ?> 
                                                        (<?php echo ucfirst(strtolower($shipment['customer_type'])); ?>)
                                                    </div>
                                                    <?php else: ?>
                                                    <div class="customer-name">
                                                        <?php echo htmlspecialchars($shipment['sender_name']); ?>
                                                    </div>
                                                    <div class="customer-type">Walk-in Customer</div>
                                                    <?php endif; ?>
                                                    <small style="color: #64748b;">
                                                        <?php echo htmlspecialchars($shipment['sender_phone']); ?>
                                                    </small>
                                                    <?php if ($shipment['sender_email']): ?>
                                                    <small style="color: #64748b;">
                                                        <?php echo htmlspecialchars($shipment['sender_email']); ?>
                                                    </small>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="route-info">
                                                    <div class="location">
                                                        <span class="location-icon origin-icon"></span>
                                                        <span><?php echo htmlspecialchars($shipment['origin_location']); ?></span>
                                                    </div>
                                                    <div class="location">
                                                        <span class="location-icon destination-icon"></span>
                                                        <span><?php echo htmlspecialchars($shipment['destination_location']); ?></span>
                                                    </div>
                                                    <small style="color: #64748b; margin-top: 0.25rem;">
                                                        To: <?php echo htmlspecialchars($shipment['receiver_name']); ?>
                                                        <br><?php echo htmlspecialchars($shipment['receiver_phone']); ?>
                                                    </small>
                                                </div>
                                            </td>
                                            <td>
                                                <div style="display: flex; flex-direction: column; gap: 0.25rem;">
                                                    <span style="font-weight: 600;">
                                                        <?php echo htmlspecialchars($shipment['service_name']); ?>
                                                    </span>
                                                    <span class="status-badge" style="font-size: 0.65rem; background: #e0e7ff; color: #5b21b6;">
                                                        <?php echo htmlspecialchars($shipment['service_category']); ?>
                                                    </span>
                                                    <?php if ($shipment['content_description']): ?>
                                                    <small style="color: #64748b; font-size: 0.7rem;">
                                                        <?php echo htmlspecialchars(substr($shipment['content_description'], 0, 50)); ?>
                                                        <?php if (strlen($shipment['content_description']) > 50) echo '...'; ?>
                                                    </small>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                            <td>
                                                <div style="display: flex; flex-direction: column; gap: 0.25rem;">
                                                    <?php 
                                                    $status_class = 'status-' . strtolower($shipment['status']);
                                                    ?>
                                                    <span class="status-badge <?php echo $status_class; ?>">
                                                        <?php echo ucfirst(strtolower(str_replace('_', ' ', $shipment['status']))); ?>
                                                    </span>
                                                    <?php if ($shipment['customs_status'] && $shipment['customs_status'] !== 'PENDING'): ?>
                                                    <span class="status-badge" style="font-size: 0.65rem; background: #f3f4f6; color: #374151;">
                                                        Customs: <?php echo ucfirst(strtolower($shipment['customs_status'])); ?>
                                                    </span>
                                                    <?php endif; ?>
                                                    <?php if ($shipment['urgency_status'] === 'OVERDUE'): ?>
                                                    <span style="font-size: 0.65rem; color: #ef4444; font-weight: 600;">
                                                        <i class="bx bx-error-circle"></i> OVERDUE
                                                    </span>
                                                    <?php elseif ($shipment['urgency_status'] === 'DUE_TODAY'): ?>
                                                    <span style="font-size: 0.65rem; color: #f59e0b; font-weight: 600;">
                                                        <i class="bx bx-time"></i> DUE TODAY
                                                    </span>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                            <td>
                                                <?php 
                                                $payment_class = 'payment-' . strtolower($shipment['payment_status']);
                                                ?>
                                                <span class="payment-badge <?php echo $payment_class; ?>">
                                                    <?php echo ucfirst(strtolower($shipment['payment_status'])); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <div style="display: flex; flex-direction: column; gap: 0.25rem;">
                                                    <span style="font-weight: 600;">
                                                        <?php echo number_format($shipment['chargeable_weight'], 2); ?> KG
                                                    </span>
                                                    <span style="color: #64748b; font-size: 0.75rem;">
                                                        Actual: <?php echo number_format($shipment['actual_weight'], 2); ?> KG
                                                    </span>
                                                    <?php if ($shipment['volumetric_weight'] > 0): ?>
                                                    <span style="color: #64748b; font-size: 0.75rem;">
                                                        Vol: <?php echo number_format($shipment['volumetric_weight'], 2); ?> KG
                                                    </span>
                                                    <?php endif; ?>
                                                    <span style="color: #64748b; font-size: 0.75rem;">
                                                        <?php echo $shipment['pieces']; ?> piece<?php echo $shipment['pieces'] > 1 ? 's' : ''; ?>
                                                    </span>
                                                </div>
                                            </td>
                                            <td>
                                                <div style="display: flex; flex-direction: column; gap: 0.25rem;">
                                                    <span style="font-weight: 600; color: #1e40af;">
                                                        <?php echo $shipment['currency']; ?> <?php echo number_format($shipment['total_charges'], 2); ?>
                                                    </span>
                                                    <?php if ($shipment['declared_value'] > 0): ?>
                                                    <span style="color: #64748b; font-size: 0.75rem;">
                                                        Declared: <?php echo $shipment['currency']; ?> <?php echo number_format($shipment['declared_value'], 2); ?>
                                                    </span>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                            <td>
                                                <div style="display: flex; flex-direction: column; gap: 0.25rem; font-size: 0.75rem; color: #64748b;">
                                                    <div style="display: flex; justify-content: space-between;">
                                                        <span><strong>Booked:</strong></span>
                                                        <span><?php echo date('d/M/y', strtotime($shipment['booking_date'])); ?></span>
                                                    </div>
                                                    <?php if ($shipment['pickup_date']): ?>
                                                    <div style="display: flex; justify-content: space-between;">
                                                        <span><strong>Pickup:</strong></span>
                                                        <span><?php echo date('d/M/y', strtotime($shipment['pickup_date'])); ?></span>
                                                    </div>
                                                    <?php endif; ?>
                                                    <?php if ($shipment['estimated_delivery']): ?>
                                                    <div style="display: flex; justify-content: space-between;">
                                                        <span><strong>Est. Del:</strong></span>
                                                        <span style="<?php 
                                                            if ($shipment['urgency_status'] === 'OVERDUE') echo 'color: #ef4444; font-weight: 600;';
                                                            elseif ($shipment['urgency_status'] === 'DUE_TODAY') echo 'color: #f59e0b; font-weight: 600;';
                                                        ?>">
                                                            <?php echo date('d/M/y', strtotime($shipment['estimated_delivery'])); ?>
                                                        </span>
                                                    </div>
                                                    <?php endif; ?>
                                                    <?php if ($shipment['delivery_date']): ?>
                                                    <div style="display: flex; justify-content: space-between;">
                                                        <span><strong>Delivered:</strong></span>
                                                        <span><?php echo date('d/M/y', strtotime($shipment['delivery_date'])); ?></span>
                                                    </div>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="quick-actions">
                                                    <a href="view_shipment.php?id=<?php echo $shipment['shipment_id']; ?>" 
                                                       class="action-btn action-view">
                                                        <i class="bx bx-show"></i> View
                                                    </a>
                                                    <a href="track_shipment.php?tracking=<?php echo $shipment['tracking_number']; ?>" 
                                                       class="action-btn action-track">
                                                        <i class="bx bx-map"></i> Track
                                                    </a>
                                                    <?php if (in_array($role_name, ['Administrator', 'Operations Manager'])): ?>
                                                    <a href="edit_shipment.php?id=<?php echo $shipment['shipment_id']; ?>" 
                                                       class="action-btn action-edit">
                                                        <i class="bx bx-edit"></i> Edit
                                                    </a>
                                                    <?php endif; ?>
                                                    <?php if (in_array($role_name, ['Administrator', 'Finance Manager', 'Customer Service'])): ?>
                                                    <a href="generate_invoice.php?shipment_id=<?php echo $shipment['shipment_id']; ?>" 
                                                       class="action-btn action-invoice">
                                                        <i class="bx bx-receipt"></i> Invoice
                                                    </a>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="10">
                                                <div class="no-data">
                                                    <i class="bx bx-package"></i>
                                                    <h4>No shipments found</h4>
                                                    <p>Try adjusting your filters or create a new shipment.</p>
                                                    <a href="create_shipment.php" class="btn btn-primary" style="margin-top: 1rem;">
                                                        <i class="bx bx-plus"></i> Create New Shipment
                                                    </a>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                    <div class="pagination">
                        <div class="page-info">
                            Showing <?php echo number_format($offset + 1); ?> to 
                            <?php echo number_format(min($offset + $records_per_page, $total_records)); ?> 
                            of <?php echo number_format($total_records); ?> shipments
                        </div>
                        
                        <div style="display: flex; gap: 0.5rem;">
                            <?php if ($page > 1): ?>
                            <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => 1])); ?>" 
                               class="page-link">First</a>
                            <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>" 
                               class="page-link">Previous</a>
                            <?php endif; ?>
                            
                            <?php
                            $start_page = max(1, $page - 2);
                            $end_page = min($total_pages, $page + 2);
                            
                            for ($i = $start_page; $i <= $end_page; $i++):
                            ?>
                            <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>" 
                               class="page-link <?php echo $i == $page ? 'active' : ''; ?>">
                                <?php echo $i; ?>
                            </a>
                            <?php endfor; ?>
                            
                            <?php if ($page < $total_pages): ?>
                            <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>" 
                               class="page-link">Next</a>
                            <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $total_pages])); ?>" 
                               class="page-link">Last</a>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Auto-refresh for active shipments (every 60 seconds)
            let autoRefreshInterval;
            
            function startAutoRefresh() {
                const urlParams = new URLSearchParams(window.location.search);
                const statusFilter = urlParams.get('status');
                
                // Only auto-refresh for active shipment statuses
                if (!statusFilter || ['IN_TRANSIT', 'OUT_FOR_DELIVERY', 'BOOKED'].includes(statusFilter)) {
                    autoRefreshInterval = setInterval(() => {
                        // Check if user is still active
                        const lastActivity = localStorage.getItem('lastActivity');
                        const now = Date.now();
                        
                        if (!lastActivity || (now - parseInt(lastActivity)) > 60000) {
                            location.reload();
                        }
                    }, 60000); // 60 seconds
                }
            }
            
            // Track user activity
            function updateActivity() {
                localStorage.setItem('lastActivity', Date.now().toString());
            }
            
            document.addEventListener('mousemove', updateActivity);
            document.addEventListener('keypress', updateActivity);
            document.addEventListener('click', updateActivity);
            
            startAutoRefresh();
            
            // Stop auto-refresh when page is hidden
            document.addEventListener('visibilitychange', function() {
                if (document.hidden) {
                    if (autoRefreshInterval) {
                        clearInterval(autoRefreshInterval);
                    }
                } else {
                    startAutoRefresh();
                }
            });
        });
        
        // Enhanced table interactions
        document.querySelectorAll('.data-table tbody tr').forEach(row => {
            // Double-click to view shipment
            row.addEventListener('dblclick', function(e) {
                if (e.target.tagName === 'A' || e.target.tagName === 'BUTTON' || e.target.closest('a') || e.target.closest('button')) {
                    return;
                }
                
                const trackingLink = row.querySelector('.tracking-link');
                if (trackingLink) {
                    window.location.href = trackingLink.href;
                }
            });
        });
        
        // Keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            const searchInput = document.querySelector('input[name="search"]');
            
            // Ctrl/Cmd + K for search focus
            if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
                e.preventDefault();
                searchInput?.focus();
            }
            
            // Ctrl/Cmd + N for new shipment
            if ((e.ctrlKey || e.metaKey) && e.key === 'n') {
                e.preventDefault();
                window.location.href = 'create_shipment.php';
            }
            
            // Ctrl/Cmd + T for track shipment
            if ((e.ctrlKey || e.metaKey) && e.key === 't') {
                e.preventDefault();
                window.location.href = 'track_shipment.php';
            }
        });
    </script>
</body>
</html>