<?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'];

// 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'];
}

// Get filters from URL parameters
$status_filter = $_GET['status'] ?? '';
$location_filter = $_GET['location'] ?? '';
$driver_filter = $_GET['driver'] ?? '';
$date_from = $_GET['date_from'] ?? date('Y-m-d');
$date_to = $_GET['date_to'] ?? date('Y-m-d');
$search = $_GET['search'] ?? '';
$urgency_filter = $_GET['urgency'] ?? '';

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

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

// Base condition for delivery-related shipments
$where_conditions[] = "s.status IN ('OUT_FOR_DELIVERY', 'DELIVERED', 'RETURNED')";

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

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

if (!empty($urgency_filter)) {
    if ($urgency_filter === 'OVERDUE') {
        $where_conditions[] = "s.estimated_delivery < CURDATE() AND s.status != 'DELIVERED'";
    } elseif ($urgency_filter === 'DUE_TODAY') {
        $where_conditions[] = "DATE(s.estimated_delivery) = CURDATE() AND s.status != 'DELIVERED'";
    }
}

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 ?)";
    $search_param = '%' . $search . '%';
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $param_types .= 'sss';
}

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

// Get delivery statistics
$stats_sql = "SELECT 
    COUNT(CASE WHEN s.status = 'OUT_FOR_DELIVERY' THEN 1 END) as out_for_delivery,
    COUNT(CASE WHEN s.status = 'DELIVERED' THEN 1 END) as delivered,
    COUNT(CASE WHEN s.status = 'RETURNED' THEN 1 END) as returned,
    COUNT(CASE WHEN DATE(s.delivery_date) = CURDATE() THEN 1 END) as delivered_today,
    COUNT(CASE WHEN s.estimated_delivery < CURDATE() AND s.status != 'DELIVERED' THEN 1 END) as overdue,
    AVG(CASE WHEN s.delivery_date IS NOT NULL THEN TIMESTAMPDIFF(HOUR, s.booking_date, s.delivery_date) END) as avg_delivery_hours
FROM shipments s
LEFT JOIN delivery_attempts da ON s.shipment_id = da.shipment_id
$where_clause";

if (!empty($params)) {
    $stats_stmt = $conn->prepare($stats_sql);
    $stats_stmt->bind_param($param_types, ...$params);
    $stats_stmt->execute();
    $stats = $stats_stmt->get_result()->fetch_assoc();
} else {
    $stats = $conn->query($stats_sql)->fetch_assoc();
}

// Get total records for pagination
$count_sql = "SELECT COUNT(DISTINCT s.shipment_id) as total 
              FROM shipments s
              LEFT JOIN locations dl ON s.destination_location_id = dl.location_id
              $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 delivery status data with detailed information
$delivery_sql = "SELECT 
    s.shipment_id,
    s.tracking_number,
    s.sender_name,
    s.receiver_name,
    s.receiver_phone,
    s.receiver_address,
    s.receiver_city,
    s.receiver_country,
    s.status,
    s.booking_date,
    s.estimated_delivery,
    s.delivery_date,
    s.pieces,
    s.chargeable_weight,
    s.total_charges,
    s.special_instructions,
    s.content_description,
    dl.location_name as destination_location,
    dl.city as destination_city,
    st.service_name,
    st.service_category,
    da.attempt_number,
    da.attempt_date,
    da.status as attempt_status,
    da.failure_reason,
    da.delivery_notes,
    da.delivered_to,
    dr.first_name as driver_first_name,
    dr.last_name as driver_last_name,
    dr.phone as driver_phone,
    CASE 
        WHEN s.status = 'DELIVERED' AND s.delivery_date <= s.estimated_delivery THEN 'ON_TIME'
        WHEN s.status = 'DELIVERED' AND s.delivery_date > s.estimated_delivery THEN 'LATE'
        WHEN s.status != 'DELIVERED' AND s.estimated_delivery < CURDATE() THEN 'OVERDUE'
        WHEN s.status != 'DELIVERED' AND DATE(s.estimated_delivery) = CURDATE() THEN 'DUE_TODAY'
        ELSE 'PENDING'
    END as delivery_urgency
FROM shipments s
LEFT JOIN locations dl ON s.destination_location_id = dl.location_id
LEFT JOIN service_types st ON s.service_id = st.service_id
LEFT JOIN delivery_attempts da ON s.shipment_id = da.shipment_id 
    AND da.attempt_id = (SELECT MAX(attempt_id) FROM delivery_attempts WHERE shipment_id = s.shipment_id)
LEFT JOIN drivers dr ON da.delivered_by = dr.driver_id
$where_clause
ORDER BY 
    FIELD(s.status, 'OUT_FOR_DELIVERY', 'RETURNED', 'DELIVERED'),
    s.estimated_delivery ASC,
    s.booking_date DESC
LIMIT $offset, $records_per_page";

if (!empty($params)) {
    $delivery_stmt = $conn->prepare($delivery_sql);
    $delivery_stmt->bind_param($param_types, ...$params);
    $delivery_stmt->execute();
    $deliveries = $delivery_stmt->get_result();
} else {
    $deliveries = $conn->query($delivery_sql);
}

// Get locations for filter dropdown
$locations_sql = "SELECT location_id, location_name, city FROM locations WHERE is_destination = 1 AND is_active = 1 ORDER BY location_name";
$locations_result = $conn->query($locations_sql);

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

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Delivery Status - Freight Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .delivery-card {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            margin-bottom: 1rem;
            background: white;
            transition: box-shadow 0.2s ease;
        }
        
        .delivery-card:hover {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .delivery-header {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            background: #f8fafc;
        }
        
        .delivery-body {
            padding: 1rem;
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .status-out_for_delivery { background: #dbeafe; color: #1d4ed8; }
        .status-delivered { background: #dcfce7; color: #166534; }
        .status-returned { background: #fee2e2; color: #991b1b; }
        
        .urgency-overdue { background: #fecaca; color: #7f1d1d; }
        .urgency-due_today { background: #fef3c7; color: #92400e; }
        .urgency-on_time { background: #dcfce7; color: #166534; }
        .urgency-late { background: #fed7aa; color: #9a3412; }
        .urgency-pending { background: #e0e7ff; color: #3730a3; }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1.5rem;
            text-align: center;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .filters-section {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .delivery-timeline {
            display: flex;
            align-items: center;
            font-size: 0.875rem;
            margin-top: 0.5rem;
        }
        
        .timeline-step {
            display: flex;
            align-items: center;
            margin-right: 1rem;
        }
        
        .timeline-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 0.5rem;
        }
        
        .timeline-dot.completed { background: #10b981; }
        .timeline-dot.current { background: #3b82f6; }
        .timeline-dot.pending { background: #d1d5db; }
        
        .delivery-details {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1rem;
            margin-top: 1rem;
        }
        
        @media (max-width: 768px) {
            .delivery-details {
                grid-template-columns: 1fr;
            }
            
            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }
    </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">Delivery Status</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 active">Delivery Status</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="stats-grid">
                        <div class="stat-card">
                            <div class="stat-value" style="color: #3b82f6;"><?php echo number_format($stats['out_for_delivery'] ?? 0); ?></div>
                            <div class="stat-label">Out for Delivery</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value" style="color: #10b981;"><?php echo number_format($stats['delivered'] ?? 0); ?></div>
                            <div class="stat-label">Delivered</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value" style="color: #f59e0b;"><?php echo number_format($stats['delivered_today'] ?? 0); ?></div>
                            <div class="stat-label">Delivered Today</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value" style="color: #ef4444;"><?php echo number_format($stats['overdue'] ?? 0); ?></div>
                            <div class="stat-label">Overdue</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value" style="color: #8b5cf6;"><?php echo number_format($stats['returned'] ?? 0); ?></div>
                            <div class="stat-label">Returned</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value" style="color: #64748b;"><?php echo number_format($stats['avg_delivery_hours'] ?? 0, 1); ?>h</div>
                            <div class="stat-label">Avg Delivery Time</div>
                        </div>
                    </div>

                    <!-- Filters Section -->
                    <div class="filters-section">
                        <form method="GET" class="row g-3">
                            <div class="col-md-3">
                                <label class="form-label">Search</label>
                                <input type="text" class="form-control" name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="Tracking number, sender, receiver...">
                            </div>
                            
                            <div class="col-md-2">
                                <label class="form-label">Status</label>
                                <select class="form-select" name="status">
                                    <option value="">All Status</option>
                                    <option value="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>
                                </select>
                            </div>
                            
                            <div class="col-md-2">
                                <label class="form-label">Urgency</label>
                                <select class="form-select" name="urgency">
                                    <option value="">All</option>
                                    <option value="OVERDUE" <?php echo $urgency_filter === 'OVERDUE' ? 'selected' : ''; ?>>Overdue</option>
                                    <option value="DUE_TODAY" <?php echo $urgency_filter === 'DUE_TODAY' ? 'selected' : ''; ?>>Due Today</option>
                                </select>
                            </div>
                            
                            <div class="col-md-2">
                                <label class="form-label">Location</label>
                                <select class="form-select" name="location">
                                    <option value="">All Locations</option>
                                    <?php while($location = $locations_result->fetch_assoc()): ?>
                                    <option value="<?php echo $location['location_id']; ?>" <?php echo $location_filter == $location['location_id'] ? 'selected' : ''; ?>>
                                        <?php echo $location['location_name'] . ' - ' . $location['city']; ?>
                                    </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-2">
                                <label class="form-label">Date From</label>
                                <input type="date" class="form-control" name="date_from" value="<?php echo $date_from; ?>">
                            </div>
                            
                            <div class="col-md-1">
                                <label class="form-label">&nbsp;</label>
                                <button type="submit" class="btn btn-primary d-block">Filter</button>
                            </div>
                        </form>
                    </div>

                    <!-- Delivery List -->
                    <div class="row">
                        <div class="col-12">
                            <?php if ($deliveries->num_rows > 0): ?>
                                <?php while($delivery = $deliveries->fetch_assoc()): ?>
                                <div class="delivery-card">
                                    <div class="delivery-header">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <h5 class="mb-1">
                                                    <a href="track_shipment.php?tracking=<?php echo $delivery['tracking_number']; ?>" class="text-decoration-none">
                                                        <?php echo $delivery['tracking_number']; ?>
                                                    </a>
                                                </h5>
                                                <small class="text-muted"><?php echo $delivery['service_name']; ?></small>
                                            </div>
                                            <div class="text-end">
                                                <span class="status-badge status-<?php echo strtolower(str_replace(' ', '_', $delivery['status'])); ?>">
                                                    <?php echo ucfirst(strtolower(str_replace('_', ' ', $delivery['status']))); ?>
                                                </span>
                                                <br>
                                                <span class="status-badge urgency-<?php echo strtolower($delivery['delivery_urgency']); ?> mt-1">
                                                    <?php echo ucfirst(strtolower(str_replace('_', ' ', $delivery['delivery_urgency']))); ?>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="delivery-body">
                                        <div class="delivery-details">
                                            <div>
                                                <h6>Sender</h6>
                                                <p class="mb-2"><?php echo htmlspecialchars($delivery['sender_name']); ?></p>
                                                
                                                <h6>Content</h6>
                                                <p class="mb-2"><?php echo htmlspecialchars($delivery['content_description']); ?></p>
                                                <small class="text-muted"><?php echo $delivery['pieces']; ?> pieces • <?php echo $delivery['chargeable_weight']; ?> kg</small>
                                            </div>
                                            
                                            <div>
                                                <h6>Receiver</h6>
                                                <p class="mb-1"><strong><?php echo htmlspecialchars($delivery['receiver_name']); ?></strong></p>
                                                <p class="mb-1"><?php echo htmlspecialchars($delivery['receiver_phone']); ?></p>
                                                <p class="mb-2 small"><?php echo htmlspecialchars($delivery['receiver_address']); ?>, <?php echo htmlspecialchars($delivery['receiver_city']); ?></p>
                                                
                                                <?php if ($delivery['special_instructions']): ?>
                                                <div class="alert alert-warning py-2">
                                                    <small><strong>Special Instructions:</strong> <?php echo htmlspecialchars($delivery['special_instructions']); ?></small>
                                                </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        
                                        <!-- Timeline -->
                                        <div class="delivery-timeline mt-3 pt-3 border-top">
                                            <div class="timeline-step">
                                                <div class="timeline-dot completed"></div>
                                                <span>Booked: <?php echo date('M j, H:i', strtotime($delivery['booking_date'])); ?></span>
                                            </div>
                                            
                                            <?php if ($delivery['estimated_delivery']): ?>
                                            <div class="timeline-step">
                                                <div class="timeline-dot <?php echo $delivery['status'] == 'DELIVERED' ? 'completed' : ($delivery['delivery_urgency'] == 'OVERDUE' ? 'current' : 'pending'); ?>"></div>
                                                <span>Est. Delivery: <?php echo date('M j, H:i', strtotime($delivery['estimated_delivery'])); ?></span>
                                            </div>
                                            <?php endif; ?>
                                            
                                            <?php if ($delivery['delivery_date']): ?>
                                            <div class="timeline-step">
                                                <div class="timeline-dot completed"></div>
                                                <span>Delivered: <?php echo date('M j, H:i', strtotime($delivery['delivery_date'])); ?></span>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <!-- Delivery Attempt Info -->
                                        <?php if ($delivery['attempt_number']): ?>
                                        <div class="mt-3 pt-3 border-top">
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <small class="text-muted">Attempt #<?php echo $delivery['attempt_number']; ?> 
                                                    - <?php echo date('M j, Y H:i', strtotime($delivery['attempt_date'])); ?></small>
                                                    <?php if ($delivery['attempt_status'] == 'FAILED' && $delivery['failure_reason']): ?>
                                                    <br><small class="text-danger">Failed: <?php echo htmlspecialchars($delivery['failure_reason']); ?></small>
                                                    <?php endif; ?>
                                                </div>
                                                <div class="col-md-6 text-end">
                                                    <?php if ($delivery['driver_first_name']): ?>
                                                    <small class="text-muted">Driver: <?php echo $delivery['driver_first_name'] . ' ' . $delivery['driver_last_name']; ?></small>
                                                    <?php if ($delivery['driver_phone']): ?>
                                                    <br><small class="text-muted"><?php echo $delivery['driver_phone']; ?></small>
                                                    <?php endif; ?>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                            
                                            <?php if ($delivery['delivery_notes']): ?>
                                            <div class="mt-2">
                                                <small><strong>Notes:</strong> <?php echo htmlspecialchars($delivery['delivery_notes']); ?></small>
                                            </div>
                                            <?php endif; ?>
                                            
                                            <?php if ($delivery['delivered_to']): ?>
                                            <div class="mt-2">
                                                <small><strong>Delivered to:</strong> <?php echo htmlspecialchars($delivery['delivered_to']); ?></small>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <!-- Actions -->
                                        <div class="mt-3 pt-3 border-top d-flex justify-content-between align-items-center">
                                            <div>
                                                <small class="text-muted">Total: KES <?php echo number_format($delivery['total_charges'], 2); ?></small>
                                            </div>
                                            <div>
                                                <a href="track_shipment.php?tracking=<?php echo $delivery['tracking_number']; ?>" class="btn btn-sm btn-outline-primary me-2">
                                                    Track
                                                </a>
                                                <a href="view_shipment.php?id=<?php echo $delivery['shipment_id']; ?>" class="btn btn-sm btn-outline-secondary">
                                                    View Details
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                                
                                <!-- Pagination -->
                                <?php if ($total_pages > 1): ?>
                                <nav aria-label="Delivery pagination" class="mt-4">
                                    <ul class="pagination justify-content-center">
                                        <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                            <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>">Previous</a>
                                        </li>
                                        
                                        <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                                        <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                            <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>"><?php echo $i; ?></a>
                                        </li>
                                        <?php endfor; ?>
                                        
                                        <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                                            <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>">Next</a>
                                        </li>
                                    </ul>
                                </nav>
                                
                                <div class="text-center text-muted">
                                    Showing <?php echo (($page - 1) * $records_per_page) + 1; ?> to <?php echo min($page * $records_per_page, $total_records); ?> of <?php echo number_format($total_records); ?> deliveries
                                </div>
                                <?php endif; ?>
                                
                            <?php else: ?>
                                <div class="text-center py-5">
                                    <div class="mb-3">
                                        <i class="bx bx-package" style="font-size: 4rem; color: #64748b;"></i>
                                    </div>
                                    <h5 class="text-muted">No delivery records found</h5>
                                    <p class="text-muted">Try adjusting your filters or search criteria.</p>
                                    <a href="delivery_status.php" class="btn btn-primary">Reset Filters</a>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <script>
        // Auto-refresh every 30 seconds for out-for-delivery items
        setTimeout(function() {
            if (window.location.search.includes('status=OUT_FOR_DELIVERY') || 
                window.location.search === '' || 
                window.location.search.includes('urgency=')) {
                window.location.reload();
            }
        }, 30000);
        
        // Quick filter buttons
        document.addEventListener('DOMContentLoaded', function() {
            // Add quick filter buttons
            const filtersSection = document.querySelector('.filters-section');
            const quickFilters = document.createElement('div');
            quickFilters.className = 'mb-3 pb-3 border-bottom';
            quickFilters.innerHTML = `
                <div class="d-flex flex-wrap gap-2">
                    <button class="btn btn-sm btn-outline-primary" onclick="applyQuickFilter('status', 'OUT_FOR_DELIVERY')">Out for Delivery</button>
                    <button class="btn btn-sm btn-outline-success" onclick="applyQuickFilter('status', 'DELIVERED')">Delivered</button>
                    <button class="btn btn-sm btn-outline-danger" onclick="applyQuickFilter('urgency', 'OVERDUE')">Overdue</button>
                    <button class="btn btn-sm btn-outline-warning" onclick="applyQuickFilter('urgency', 'DUE_TODAY')">Due Today</button>
                    <button class="btn btn-sm btn-outline-secondary" onclick="applyQuickFilter('status', 'RETURNED')">Returned</button>
                    <button class="btn btn-sm btn-outline-info" onclick="clearFilters()">Clear All</button>
                </div>
            `;
            filtersSection.prepend(quickFilters);
        });
        
        function applyQuickFilter(filterType, value) {
            const url = new URL(window.location);
            url.searchParams.set(filterType, value);
            url.searchParams.delete('page'); // Reset to first page
            window.location.href = url.toString();
        }
        
        function clearFilters() {
            window.location.href = 'delivery_status.php';
        }
        
        // Enhanced search functionality
        document.querySelector('input[name="search"]').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.target.closest('form').submit();
            }
        });
        
        // Status update via AJAX (for real-time updates)
        function updateDeliveryStatus(shipmentId, newStatus) {
            fetch('ajax/update_delivery_status.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    shipment_id: shipmentId,
                    status: newStatus
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Refresh the page to show updated status
                    window.location.reload();
                } else {
                    alert('Error updating status: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error updating status');
            });
        }
        
        // Print delivery list
        function printDeliveryList() {
            window.print();
        }
        
        // Export to CSV functionality
        function exportToCsv() {
            const params = new URLSearchParams(window.location.search);
            params.set('export', 'csv');
            window.location.href = 'delivery_status.php?' + params.toString();
        }
        
        // Bulk actions functionality
        function toggleSelectAll() {
            const checkboxes = document.querySelectorAll('input[name="selected_deliveries[]"]');
            const selectAll = document.getElementById('selectAll');
            
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAll.checked;
            });
            
            updateBulkActionsVisibility();
        }
        
        function updateBulkActionsVisibility() {
            const selectedCount = document.querySelectorAll('input[name="selected_deliveries[]"]:checked').length;
            const bulkActions = document.getElementById('bulkActions');
            
            if (selectedCount > 0) {
                bulkActions.style.display = 'block';
                document.getElementById('selectedCount').textContent = selectedCount;
            } else {
                bulkActions.style.display = 'none';
            }
        }
        
        function performBulkAction(action) {
            const selectedDeliveries = Array.from(document.querySelectorAll('input[name="selected_deliveries[]"]:checked'))
                .map(checkbox => checkbox.value);
            
            if (selectedDeliveries.length === 0) {
                alert('Please select at least one delivery');
                return;
            }
            
            if (confirm(`Are you sure you want to ${action} ${selectedDeliveries.length} deliveries?`)) {
                fetch('ajax/bulk_delivery_action.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        action: action,
                        delivery_ids: selectedDeliveries
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert(`Successfully ${action}ed ${data.affected_count} deliveries`);
                        window.location.reload();
                    } else {
                        alert('Error: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error performing bulk action');
                });
            }
        }
        
        // Live tracking updates (WebSocket or polling)
        function startLiveTracking() {
            // Poll for updates every 30 seconds
            setInterval(function() {
                const activeDeliveries = document.querySelectorAll('.status-out_for_delivery');
                if (activeDeliveries.length > 0) {
                    checkForUpdates();
                }
            }, 30000);
        }
        
        function checkForUpdates() {
            fetch('ajax/check_delivery_updates.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    current_filters: Object.fromEntries(new URLSearchParams(window.location.search))
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.has_updates) {
                    // Show notification or auto-refresh
                    showUpdateNotification(data.update_count);
                }
            })
            .catch(error => {
                console.error('Error checking for updates:', error);
            });
        }
        
        function showUpdateNotification(count) {
            const notification = document.createElement('div');
            notification.className = 'alert alert-info alert-dismissible fade show position-fixed';
            notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999;';
            notification.innerHTML = `
                <strong>Updates Available!</strong> ${count} delivery status changes detected.
                <button onclick="window.location.reload()" class="btn btn-sm btn-info ms-2">Refresh</button>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            document.body.appendChild(notification);
            
            // Auto-remove after 10 seconds
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.remove();
                }
            }, 10000);
        }
        
        // Initialize live tracking
        startLiveTracking();
        
        // Keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            // Ctrl/Cmd + F for focus search
            if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
                e.preventDefault();
                document.querySelector('input[name="search"]').focus();
            }
            
            // Ctrl/Cmd + R for refresh
            if ((e.ctrlKey || e.metaKey) && e.key === 'r') {
                e.preventDefault();
                window.location.reload();
            }
        });
        
        // Mobile-friendly improvements
        if (window.innerWidth <= 768) {
            // Collapse filters on mobile by default
            const filtersForm = document.querySelector('.filters-section form');
            if (filtersForm) {
                filtersForm.style.display = 'none';
                
                const toggleButton = document.createElement('button');
                toggleButton.className = 'btn btn-outline-secondary mb-3';
                toggleButton.textContent = 'Show Filters';
                toggleButton.onclick = function() {
                    if (filtersForm.style.display === 'none') {
                        filtersForm.style.display = 'block';
                        this.textContent = 'Hide Filters';
                    } else {
                        filtersForm.style.display = 'none';
                        this.textContent = 'Show Filters';
                    }
                };
                
                document.querySelector('.filters-section').prepend(toggleButton);
            }
        }
    </script>
    
    <!-- Print Styles -->
    <style media="print">
        .no-print, .btn, .page-title-right, .filters-section {
            display: none !important;
        }
        
        .delivery-card {
            break-inside: avoid;
            margin-bottom: 20px;
            border: 1px solid #000;
        }
        
        .page-content {
            padding: 0;
        }
        
        .container-fluid {
            padding: 0;
        }
        
        @page {
            margin: 1cm;
        }
        
        .delivery-header {
            background: #f8f9fa !important;
            -webkit-print-color-adjust: exact;
        }
        
        .status-badge {
            border: 1px solid #000;
            -webkit-print-color-adjust: exact;
        }
    </style>
    
    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>

<?php
// Handle CSV export
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    // Rebuild the query for export (without LIMIT)
    $export_sql = str_replace("LIMIT $offset, $records_per_page", "", $delivery_sql);
    
    if (!empty($params)) {
        $export_stmt = $conn->prepare($export_sql);
        $export_stmt->bind_param($param_types, ...$params);
        $export_stmt->execute();
        $export_result = $export_stmt->get_result();
    } else {
        $export_result = $conn->query($export_sql);
    }
    
    // Set headers for CSV download
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=delivery_status_' . date('Y-m-d_H-i-s') . '.csv');
    
    $output = fopen('php://output', 'w');
    
    // CSV headers
    fputcsv($output, [
        'Tracking Number',
        'Sender',
        'Receiver',
        'Receiver Phone',
        'Destination',
        'Status',
        'Service',
        'Booking Date',
        'Estimated Delivery',
        'Actual Delivery',
        'Pieces',
        'Weight (KG)',
        'Total Charges',
        'Delivery Urgency',
        'Driver',
        'Attempt Number',
        'Special Instructions'
    ]);
    
    // CSV data
    while ($row = $export_result->fetch_assoc()) {
        fputcsv($output, [
            $row['tracking_number'],
            $row['sender_name'],
            $row['receiver_name'],
            $row['receiver_phone'],
            $row['destination_location'] . ', ' . $row['destination_city'],
            str_replace('_', ' ', $row['status']),
            $row['service_name'],
            $row['booking_date'],
            $row['estimated_delivery'],
            $row['delivery_date'],
            $row['pieces'],
            $row['chargeable_weight'],
            $row['total_charges'],
            str_replace('_', ' ', $row['delivery_urgency']),
            $row['driver_first_name'] ? $row['driver_first_name'] . ' ' . $row['driver_last_name'] : '',
            $row['attempt_number'] ?? '',
            $row['special_instructions']
        ]);
    }
    
    fclose($output);
    exit;
}
?>