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

$shipment = null;
$tracking_events = [];
$search_performed = false;
$error_message = '';

// Handle tracking search
if (isset($_GET['tracking']) || isset($_POST['tracking_number'])) {
    $tracking_number = $_GET['tracking'] ?? $_POST['tracking_number'];
    $search_performed = true;
    
    if (!empty($tracking_number)) {
        // Fetch shipment details
        $sql_shipment = "SELECT s.*, 
                                st.service_name, st.service_category,
                                ol.location_name as origin_location, ol.location_code as origin_code,
                                dl.location_name as destination_location, dl.location_code as destination_code,
                                oc.country_name as origin_country,
                                dc.country_name as destination_country,
                                c.first_name, c.last_name, c.customer_code, c.company_name, c.customer_type
                         FROM shipments s
                         LEFT JOIN service_types st ON s.service_id = st.service_id
                         LEFT JOIN locations ol ON s.origin_location_id = ol.location_id
                         LEFT JOIN 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 customers c ON s.sender_customer_id = c.customer_id
                         WHERE s.tracking_number = ?";
        
        $stmt_shipment = $conn->prepare($sql_shipment);
        $stmt_shipment->bind_param("s", $tracking_number);
        $stmt_shipment->execute();
        $result = $stmt_shipment->get_result();
        
        if ($result->num_rows > 0) {
            $shipment = $result->fetch_assoc();
            
            // Fetch tracking events
            $sql_events = "SELECT te.*, u.full_name as created_by_name
                          FROM tracking_events te
                          LEFT JOIN users u ON te.created_by = u.user_id
                          WHERE te.shipment_id = ?
                          ORDER BY te.event_date DESC";
            
            $stmt_events = $conn->prepare($sql_events);
            $stmt_events->bind_param("i", $shipment['shipment_id']);
            $stmt_events->execute();
            $events_result = $stmt_events->get_result();
            
            while ($event = $events_result->fetch_assoc()) {
                $tracking_events[] = $event;
            }
        } else {
            $error_message = "Shipment not found. Please check the tracking number and try again.";
        }
    } else {
        $error_message = "Please enter a valid tracking number.";
    }
}

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Track Shipment - Freight Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 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);
        }
        
        .search-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
            padding: 2rem;
        }
        
        .tracking-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .tracking-header {
            background: linear-gradient(135deg, #059669 0%, #10b981 100%);
            color: white;
            padding: 1.5rem;
            border-radius: 12px 12px 0 0;
        }
        
        .tracking-body {
            padding: 2rem;
        }
        
        .status-badge {
            padding: 0.5rem 1rem;
            border-radius: 9999px;
            font-size: 0.875rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .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; }
        
        .shipment-info {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin: 2rem 0;
        }
        
        .info-card {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1.5rem;
        }
        
        .info-label {
            font-size: 0.875rem;
            color: #64748b;
            margin-bottom: 0.5rem;
            font-weight: 500;
        }
        
        .info-value {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
        }
        
        .timeline {
            position: relative;
            padding-left: 2rem;
        }
        
        .timeline::before {
            content: '';
            position: absolute;
            left: 1rem;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #e2e8f0;
        }
        
        .timeline-item {
            position: relative;
            margin-bottom: 2rem;
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1.5rem;
            margin-left: 1rem;
        }
        
        .timeline-item::before {
            content: '';
            position: absolute;
            left: -2rem;
            top: 1.5rem;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #1e40af;
            border: 3px solid white;
            box-shadow: 0 0 0 3px #1e40af;
        }
        
        .timeline-item.current::before {
            background: #059669;
            box-shadow: 0 0 0 3px #059669;
        }
        
        .timeline-item.completed::before {
            background: #16a34a;
            box-shadow: 0 0 0 3px #16a34a;
        }
        
        .timeline-date {
            font-size: 0.875rem;
            color: #64748b;
            margin-bottom: 0.5rem;
        }
        
        .timeline-title {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .timeline-description {
            color: #64748b;
            margin-bottom: 0.5rem;
        }
        
        .timeline-location {
            font-size: 0.875rem;
            color: #1e40af;
            font-weight: 500;
        }
        
        .search-input {
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            font-size: 1rem;
            transition: all 0.2s ease;
        }
        
        .search-input:focus {
            border-color: #1e40af;
            box-shadow: 0 0 0 3px rgba(30, 64, 175, 0.1);
        }
        
        .btn-search {
            background: #1e40af;
            border-color: #1e40af;
            padding: 1rem 2rem;
            font-weight: 600;
            border-radius: 8px;
        }
        
        .btn-search:hover {
            background: #1d4ed8;
            border-color: #1d4ed8;
        }
        
        .no-results {
            text-align: center;
            padding: 3rem;
            color: #64748b;
        }
        
        .address-section {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1.5rem;
            margin: 1rem 0;
        }
        
        .address-title {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .progress-bar-container {
            background: #f1f5f9;
            border-radius: 8px;
            height: 8px;
            margin: 1rem 0;
            overflow: hidden;
        }
        
        .progress-bar {
            height: 100%;
            background: linear-gradient(90deg, #059669, #10b981);
            border-radius: 8px;
            transition: width 0.3s ease;
        }
        
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .shipment-info {
                grid-template-columns: 1fr;
            }
            
            .timeline {
                padding-left: 1.5rem;
            }
            
            .timeline-item {
                margin-left: 0.5rem;
            }
        }
    </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="d-flex justify-content-between align-items-center">
                            <div>
                                <h2 class="mb-2">Track Your Shipment</h2>
                                <p class="mb-0">Enter your tracking number to get real-time shipment updates</p>
                            </div>
                            <div class="d-none d-md-block">
                                <div class="text-end">
                                    <div style="font-size: 0.9rem; opacity: 0.8;">Track & Trace</div>
                                    <div style="font-size: 1.1rem; font-weight: 600;">🚚 Live Updates</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Search Form -->
                    <div class="search-card">
                        <form method="POST" class="d-flex gap-3">
                            <div class="flex-grow-1">
                                <input type="text" 
                                       class="form-control search-input" 
                                       name="tracking_number" 
                                       placeholder="Enter tracking number (e.g., TRK001234567)" 
                                       value="<?php echo isset($_POST['tracking_number']) ? htmlspecialchars($_POST['tracking_number']) : ''; ?>"
                                       required>
                            </div>
                            <button type="submit" class="btn btn-primary btn-search">
                                <i class="bx bx-search me-2"></i>Track Shipment
                            </button>
                        </form>
                    </div>

                    <!-- Error Message -->
                    <?php if ($error_message): ?>
                    <div class="alert alert-warning alert-dismissible fade show" role="alert">
                        <i class="bx bx-error-circle me-2"></i><?php echo $error_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <!-- Tracking Results -->
                    <?php if ($shipment): ?>
                    <div class="tracking-card">
                        <div class="tracking-header">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h3 class="mb-2">Tracking #<?php echo $shipment['tracking_number']; ?></h3>
                                    <p class="mb-0"><?php echo $shipment['service_name']; ?> | Booked: <?php echo date('M j, Y H:i', strtotime($shipment['booking_date'])); ?></p>
                                </div>
                                <div class="text-end">
                                    <?php 
                                    $status_class = 'status-' . strtolower(str_replace(' ', '_', $shipment['status']));
                                    ?>
                                    <span class="status-badge <?php echo $status_class; ?>">
                                        <?php echo ucfirst(strtolower(str_replace('_', ' ', $shipment['status']))); ?>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="tracking-body">
                            <!-- Progress Bar -->
                            <?php 
                            $progress_percentage = 0;
                            switch ($shipment['status']) {
                                case 'DRAFT': $progress_percentage = 10; break;
                                case 'BOOKED': $progress_percentage = 25; break;
                                case 'COLLECTED': $progress_percentage = 40; break;
                                case 'IN_TRANSIT': $progress_percentage = 60; break;
                                case 'OUT_FOR_DELIVERY': $progress_percentage = 80; break;
                                case 'DELIVERED': $progress_percentage = 100; break;
                                default: $progress_percentage = 10;
                            }
                            ?>
                            <div class="progress-bar-container">
                                <div class="progress-bar" style="width: <?php echo $progress_percentage; ?>%;"></div>
                            </div>
                            <div class="text-center mb-3">
                                <small class="text-muted"><?php echo $progress_percentage; ?>% Complete</small>
                            </div>
                            
                            <!-- Shipment Information -->
                            <div class="shipment-info">
                                <div class="info-card">
                                    <div class="info-label">Route</div>
                                    <div class="info-value">
                                        <?php echo $shipment['origin_code']; ?> → <?php echo $shipment['destination_code']; ?>
                                    </div>
                                    <div style="font-size: 0.875rem; color: #64748b; margin-top: 0.5rem;">
                                        <?php echo $shipment['origin_location']; ?> to <?php echo $shipment['destination_location']; ?>
                                    </div>
                                </div>
                                
                                <div class="info-card">
                                    <div class="info-label">Package Details</div>
                                    <div class="info-value"><?php echo $shipment['pieces']; ?> piece(s)</div>
                                    <div style="font-size: 0.875rem; color: #64748b; margin-top: 0.5rem;">
                                        <?php echo number_format($shipment['chargeable_weight'], 2); ?> kg | <?php echo $shipment['package_type']; ?>
                                    </div>
                                </div>
                                
                                <div class="info-card">
                                    <div class="info-label">Total Charges</div>
                                    <div class="info-value"><?php echo $shipment['currency']; ?> <?php echo number_format($shipment['total_charges'], 2); ?></div>
                                    <div style="font-size: 0.875rem; color: #64748b; margin-top: 0.5rem;">
                                        Payment: <?php echo ucfirst(strtolower($shipment['payment_status'])); ?>
                                    </div>
                                </div>
                                
                                <?php if ($shipment['estimated_delivery']): ?>
                                <div class="info-card">
                                    <div class="info-label">Estimated Delivery</div>
                                    <div class="info-value"><?php echo date('M j, Y H:i', strtotime($shipment['estimated_delivery'])); ?></div>
                                    <div style="font-size: 0.875rem; color: #64748b; margin-top: 0.5rem;">
                                        Local time
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>
                            
                            <!-- Sender and Receiver Information -->
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="address-section">
                                        <div class="address-title">
                                            📤 <span>Sender</span>
                                        </div>
                                        <div><strong><?php echo $shipment['sender_name']; ?></strong></div>
                                        <?php if ($shipment['sender_company']): ?>
                                        <div style="color: #64748b;"><?php echo $shipment['sender_company']; ?></div>
                                        <?php endif; ?>
                                        <div style="margin-top: 0.5rem;">
                                            <?php echo $shipment['sender_address']; ?><br>
                                            <?php echo $shipment['sender_city']; ?>, <?php echo $shipment['sender_country']; ?>
                                        </div>
                                        <div style="margin-top: 0.5rem; color: #1e40af;">
                                            📞 <?php echo $shipment['sender_phone']; ?>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="address-section">
                                        <div class="address-title">
                                            📥 <span>Receiver</span>
                                        </div>
                                        <div><strong><?php echo $shipment['receiver_name']; ?></strong></div>
                                        <?php if ($shipment['receiver_company']): ?>
                                        <div style="color: #64748b;"><?php echo $shipment['receiver_company']; ?></div>
                                        <?php endif; ?>
                                        <div style="margin-top: 0.5rem;">
                                            <?php echo $shipment['receiver_address']; ?><br>
                                            <?php echo $shipment['receiver_city']; ?>, <?php echo $shipment['receiver_country']; ?>
                                        </div>
                                        <div style="margin-top: 0.5rem; color: #1e40af;">
                                            📞 <?php echo $shipment['receiver_phone']; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Content Description -->
                            <div class="address-section">
                                <div class="address-title">
                                    📦 <span>Package Contents</span>
                                </div>
                                <div><?php echo nl2br(htmlspecialchars($shipment['content_description'])); ?></div>
                                <?php if ($shipment['special_instructions']): ?>
                                <div style="margin-top: 1rem; padding: 1rem; background: #fffbeb; border: 1px solid #f59e0b; border-radius: 6px;">
                                    <strong style="color: #d97706;">Special Instructions:</strong><br>
                                    <?php echo nl2br(htmlspecialchars($shipment['special_instructions'])); ?>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Tracking Timeline -->
                    <?php if (!empty($tracking_events)): ?>
                    <div class="tracking-card">
                        <div class="tracking-header">
                            <h3 class="mb-0">📍 Tracking History</h3>
                        </div>
                        <div class="tracking-body">
                            <div class="timeline">
                                <?php foreach ($tracking_events as $index => $event): ?>
                                <div class="timeline-item <?php echo $index === 0 ? 'current' : 'completed'; ?>">
                                    <div class="timeline-date">
                                        <?php echo date('M j, Y - H:i', strtotime($event['event_date'])); ?>
                                    </div>
                                    <div class="timeline-title">
                                        <?php echo ucfirst(strtolower(str_replace('_', ' ', $event['event_type']))); ?>
                                    </div>
                                    <div class="timeline-description">
                                        <?php echo $event['event_description']; ?>
                                    </div>
                                    <?php if ($event['location']): ?>
                                    <div class="timeline-location">
                                        📍 <?php echo $event['location']; ?>
                                    </div>
                                    <?php endif; ?>
                                    <?php if ($event['created_by_name']): ?>
                                    <div style="font-size: 0.75rem; color: #9ca3af; margin-top: 0.5rem;">
                                        Updated by: <?php echo $event['created_by_name']; ?>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <?php elseif ($search_performed && !$shipment): ?>
                    <!-- No Results -->
                    <div class="search-card">
                        <div class="no-results">
                            <div style="font-size: 3rem; margin-bottom: 1rem;">📦</div>
                            <h4>No shipment found</h4>
                            <p class="text-muted">Please check your tracking number and try again.</p>
                            <div style="margin-top: 2rem;">
                                <a href="create_shipment.php" class="btn btn-primary me-2">Create New Shipment</a>
                                <a href="shipments.php" class="btn btn-outline-primary">View All Shipments</a>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Quick Actions -->
                    <?php if (!$search_performed): ?>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="search-card text-center">
                                <div style="font-size: 2rem; margin-bottom: 1rem;">📦</div>
                                <h5>Create Shipment</h5>
                                <p class="text-muted">Book a new shipment and get instant tracking</p>
                                <a href="create_shipment.php" class="btn btn-primary">Create Now</a>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="search-card text-center">
                                <div style="font-size: 2rem; margin-bottom: 1rem;">📋</div>
                                <h5>All Shipments</h5>
                                <p class="text-muted">View and manage all your shipments</p>
                                <a href="shipments.php" class="btn btn-outline-primary">View All</a>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="search-card text-center">
                                <div style="font-size: 2rem; margin-bottom: 1rem;">💰</div>
                                <h5>Rate Calculator</h5>
                                <p class="text-muted">Calculate shipping rates instantly</p>
                                <a href="rate_calculator.php" class="btn btn-outline-primary">Calculate</a>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Auto-focus on search input
            $('.search-input').focus();
            
            // Handle Enter key in search input
            $('.search-input').on('keypress', function(e) {
                if (e.which === 13) {
                    $(this).closest('form').submit();
                }
            });
            
            // Copy tracking number to clipboard
            $('.tracking-header h3').on('click', function() {
                const trackingNumber = $(this).text().replace('Tracking #', '');
                navigator.clipboard.writeText(trackingNumber).then(function() {
                    // Show tooltip or alert
                    alert('Tracking number copied to clipboard!');
                });
            });
            
            // Auto-refresh tracking data every 30 seconds if viewing a shipment
            <?php if ($shipment): ?>
            setInterval(function() {
                // Only refresh if the shipment is not delivered
                const status = '<?php echo $shipment['status']; ?>';
                if (status !== 'DELIVERED' && status !== 'CANCELLED' && status !== 'RETURNED') {
                    // Reload the page to get fresh data
                    window.location.reload();
                }
            }, 30000); // 30 seconds
            <?php endif; ?>
        });
    </script>

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