<?php
include 'header.php';

$track_num = '';
$error = '';

// Check if a tracking number is provided via POST
if (isset($_POST['tracking_number']) && !empty($_POST['tracking_number'])) {
    $track_num = text_input($_POST['tracking_number']);
    $sql = mysqli_query($link, "SELECT * FROM tracking WHERE tracking_number = '$track_num'");
    if(mysqli_num_rows($sql) > 0){
        $row = mysqli_fetch_assoc($sql);
        $track_number = $row['tracking_number'];
        $sendersname = $row['sender_name'];
        $senderscontact = $row['sender_contact'];
        $sendersmail = $row['sender_email'];
        $sendersaddress = $row['sender_address'];
        $receiversname = $row['receiver_name'];
        $receiverscontact = $row['receiver_contact'];
        $receiversmail = $row['receiver_email'];
        $status = $row['status'];
        $dispatchl = $row['dispatch_location'];
        $dispatch = $row['dispatch_date'];
        $delivery = $row['delivery_date'];
        $desc = $row['pdesc'];
        $carrier = $row['carrier'];
        $carrier_ref = $row['carrier_ref'];
        $weight = $row['weight'];
        $payment_mode = $row['payment_mode'];
        $ship_mode = $row['ship_mode'];
        $quantity = $row['quantity'];
        $destination = $row['destination'];
        $delivery_time = $row['delivery_time'];
        $date = $row['date'];
        $images = $row['image'];



        $sqlx = mysqli_query($link, "SELECT status,current_location FROM track_update WHERE track_num = '$track_num' ORDER BY id  DESC LIMIT 1 ");
        if(mysqli_num_rows($sqlx) > 0){
            $rowx = mysqli_fetch_assoc($sqlx);
            $current_status = $rowx['status'];
            $current_location = $rowx['current_location'];
            $invoice = 'yes';
        }else{
            $current_status = $status;
            $current_location = $dispatchl;
            $invoice = 'no';
        }
        
    } else {
        $error = "Invalid tracking ID. Please input a valid tracking ID.";
    }
} else {
      header('location: tracking.php');
      echo "<script>window.location.href = 'tracking.php' </script>";
    }


?>


<!-- Tracking Hero Section -->
<div class="tracking-hero pt-5">
    <div class="container text-center">
        <br> <br>
        <h1 class="tracking-title fade-in-up py-5">Track Your Shipment</h1>
        <p class="tracking-subtitle fade-in-up" style="animation-delay: 0.1s;">Get real-time updates on your package's
            journey from origin to destination.</p>
        <?php if (!empty($error)) { ?>
        <p style="color: red;">
            <?php echo $error; ?>
        </p>
        <?php } ?>
        <div class="search-container fade-in-up" style="animation-delay: 0.2s;">
            <form method="GET" action="" class="d-flex">
                <input type="text" class="form-control search-input" id="tracking_number" name="tracking_number"
                    placeholder="Enter your tracking number" value="<?php echo $track_num; ?>" required>
                <button class="btn search-button" name="submit" type="submit">
                    <i class="fas fa-search me-2"></i>
                </button>
            </form>
        </div>
    </div>
</div>

<!-- Results Section -->
<section class="py-5">
    <div class="container">

        <div class="tracking-card fade-in-up">
            <div class="tracking-card-header">
                <h2 class="m-0">Tracking Information</h2>
            </div>
            <div class="tracking-card-body">
                <!-- Progress Tracker -->
                <div class="progress-tracker">
                    <div class="progress-bar-container">
                        <div class="progress-bar-fill" style="--progress-percent: 0%;"></div>
                    </div>
                    <div class="progress-steps">
                        <div class="step-item completed fade-in-up" style="animation-delay: 0.3s;" data-value="0">
                            <div class="step-icon">
                                <i class="fas fa-warehouse"></i>
                            </div>
                            <div class="step-label">Arrival</div>
                        </div>
                        <div class="step-item completed fade-in-up" style="animation-delay: 0.4s;" data-value="20">
                            <div class="step-icon">
                                <i class="fas fa-plane-departure"></i>
                            </div>
                            <div class="step-label">Departure</div>
                        </div>
                        <div class="step-item completed fade-in-up" style="animation-delay: 0.5s;" data-value="40">
                            <div class="step-icon">
                                <i class="fas fa-truck-moving"></i>
                            </div>
                            <div class="step-label">InTransit</div>
                        </div>
                        <div class="step-item completed fade-in-up" style="animation-delay: 0.6s;" data-value="60">
                            <?php 
                            if($current_status=='onHold'){echo '<div class="step-icon redhold" >
                                <i class="fas fa-info-circle" ></i>
                            </div>';}else{ echo '<div class="step-icon">
                                <i class="fas fa-clipboard-check"></i>
                            </div>';}
                            ?>
                            <div class="step-label"><?php if($current_status=='onHold'){echo '<div style="color: red;" >onHold</div>';}else{echo 'Custom clearance';} ?></div>
                        </div>
                        <div class="step-item  fade-in-up" style="animation-delay: 0.7s;" data-value="80">
                            <div class="step-icon">
                                <i class="fas fa-map-marker-alt"></i>
                            </div>
                            <div class="step-label">Destination</div>
                        </div>
                        <div class="step-item  fade-in-up" style="animation-delay: 0.8s;" data-value="100">
                            <div class="step-icon">
                                <i class="fas fa-box-open"></i>
                            </div>
                            <div class="step-label">Delivered</div>
                        </div>
                    </div>
                </div>

                <!-- Parcel Details -->
                <div class="parcel-details">
                    <div class="detail-item fade-in-up" style="animation-delay: 0.4s;">
                        <div class="detail-label"><i class="fas fa-map-marker-alt"></i> Origin</div>
                        <div class="detail-value">
                            <?php echo $dispatchl; ?>
                        </div>
                    </div>
                    <div class="detail-item fade-in-up" style="animation-delay: 0.5s;">
                        <div class="detail-label"><i class="fas fa-map-pin"></i> Destination</div>
                        <div class="detail-value">
                            <?php echo $destination; ?>
                        </div>
                    </div>
                    <div class="detail-item fade-in-up" style="animation-delay: 0.6s;">
                        <div class="detail-label"><i class="fas fa-shipping-fast"></i> Shipment Type</div>
                        <div class="detail-value">
                            <?php echo $ship_mode; ?>
                        </div>
                    </div>
                    <div class="detail-item fade-in-up" style="animation-delay: 0.7s;">
                        <div class="detail-label"><i class="far fa-calendar-alt"></i> Expected Delivery</div>
                        <div class="detail-value">
                            <?php echo $delivery; ?>
                        </div>
                    </div>
                </div>
                <!-- Timeline -->
                <div class="timeline-container">
                    <div class="timeline-connector"></div>
                    <?php
                    $sql1 = mysqli_query($link, "SELECT * FROM track_update WHERE track_num = '$track_num'");
                    $updates = [];

                    if(mysqli_num_rows($sql1) > 0){
                        while ($row = mysqli_fetch_assoc($sql1)) {
                            $updates[] = $row;
                        }

                        // Reverse the array to show the latest update first
                        $updates = array_reverse($updates);

                        foreach ($updates as $index => $row1) {
                            $track_number = $row1['track_num'];
                            $status = $row1['status'];
                            $date = $row1['date'];
                            $time = $row1['time'];
                            $note = $row1['note'];
                            $current_location = $row1['current_location'];
                            $shiping_cost = $row1['shiping_cost'];
                            $clearance_cost = $row1['clearance_cost'];
                            $updated_at = $row1['updated_at'];

                            // Add 'active' class only to the first item in the reversed array (which is the latest)
                            $activeClass = ($index === 0) ? 'active' : '';
                    ?>
                        <div class="timeline-item <?php echo $activeClass; ?>" style="animation-delay: 0.65s;" data-animation-index="3">
                            <div class="timeline-dot"></div>
                            <div class="timeline-content">
                                <div class="timeline-date">
                                    <i class="far fa-clock"></i>
                                    <?php echo $date . ' ' . $time; ?>
                                </div>
                                <h4 class="timeline-title">
                                    Arrived at <?php echo $current_location; ?>
                                </h4>
                                <p class="timeline-text">
                                    <?php echo $note; ?>.
                                </p>
                            </div>
                        </div>
                    <?php
                        }
                    }
                    ?>


                  
                </div>
            
                <!-- Accordion for Map and Images -->
                <div class="accordion mt-5" id="trackingAccordion">
                    <div class="accordion-item border-0 mb-3 fade-in-up" style="animation-delay: 0.8s;">
                        <h2 class="accordion-header" id="headingMap">
                            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse"
                                data-bs-target="#collapseMap" aria-expanded="false" aria-controls="collapseMap">
                                <i class="fas fa-map-marked-alt me-2"></i>
                                View Package Location
                            </button>
                        </h2>
                        <div id="collapseMap" class="accordion-collapse collapse" aria-labelledby="headingMap"
                            data-bs-parent="#trackingAccordion">
                            <div class="accordion-body p-0">
                                <iframe
                                    src="map-view.php?tracking_id=<?= $track_num ?>&t=<?= time() ?>"
                                    width="100%" height="450" style="border:0;" allowfullscreen="" loading="lazy">
                                </iframe>
                                

                            </div>
                        </div>
                    </div>

                    <div class="accordion-item border-0 fade-in-up" style="animation-delay: 0.9s;">
                        <h2 class="accordion-header" id="headingImages">
                            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse"
                                data-bs-target="#collapseImages" aria-expanded="false" aria-controls="collapseImages">
                                <i class="fas fa-images me-2"></i>
                                View Package Image
                            </button>
                        </h2>
                        <div id="collapseImages" class="accordion-collapse collapse" aria-labelledby="headingImages"
                            data-bs-parent="#trackingAccordion">
                            <div class="accordion-body">
                                <div class="parcel-images">
                                    <div class="parcel-image fade-in-up" style="animation-delay: 0.5s;"><img
                                            src="uploads/<?php echo $images; ?>"
                                            alt="Parcel Image" loading="lazy"
                                            onerror="this.src='assets/img/placeholder-image.jpg'" /></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php
         
        
        ?>
        <!-- Delivery Status Badge -->
        <div class="delivery-status-badge fade-in-up"
            style="animation-delay: 1s; text-align: center; margin-bottom: 30px;">
            <h4 class="mb-0 text-warning">
                <i class="fas fa-clipboard-check me-2"></i>
                Current Status: <strong>
                    <?php echo $current_status; ?>
                </strong>
            </h4>
        </div>
        <?php 
            if($invoice == "yes"){
        ?>
        <div class="delivery-status-badge fade-in-up"
            style="animation-delay: 1s; text-align: center; margin-bottom: 30px;">
            <h4 class="mb-0 text-warning">
                <i class="fas fa-clipboard-check me-2"></i>
                Full Details: <strong>
                    <a target="_blank" href="invoice.php?tnum=<?php echo $track_num ?>">View Details</a>
                </strong>
            </h4>
        </div>
        <?php
        }
        ?>
    </div>
</section>



<script>
function updateProgress(currentStatus) {
    const steps = document.querySelectorAll('.step-item');
    const progressBar = document.querySelector('.progress-bar-fill');
    let statusMatched = false;
    let lastCompletedValue = 0;

    steps.forEach(step => {
        const label = step.querySelector('.step-label').textContent.trim();

        if (!statusMatched) {
            step.classList.add('completed');
            lastCompletedValue = parseInt(step.getAttribute('data-value')) || 0;

            if (label.toLowerCase() === currentStatus.toLowerCase()) {
                statusMatched = true;
            }
        } else {
            step.classList.remove('completed');
        }
    });

    // Reset if invalid status
    if (!statusMatched || currentStatus === '') {
        steps.forEach(step => step.classList.remove('completed'));
        lastCompletedValue = 0;
    }

    // Update the progress bar after DOM update
    setTimeout(function () {
        if (progressBar) {
            progressBar.style.width = lastCompletedValue + '%';
        }
    }, 500);
}

document.addEventListener("DOMContentLoaded", function () {
    updateProgress("<?php echo $current_status ?>"); // Replace with dynamic status if needed
});


</script>


<!-- Animation Scripts -->
<script>
    document.addEventListener('DOMContentLoaded', function () {
        // Handle loading animation
        const loader = document.getElementById('loadingAnimation');

        setTimeout(function () {
            loader.classList.add('fade-out');
            setTimeout(function () {
                loader.style.display = 'none';
            }, 500);
        }, 1200);

        // Show loading animation when form is submitted
        const trackingForm = document.querySelector('form');
        if (trackingForm) {
            trackingForm.addEventListener('submit', function () {
                loader.classList.remove('fade-out');
                loader.style.display = 'flex';
            });
        }


        // Show welcome notification
        showNotification({
            type: 'info',
            title: 'Tracking Information',
            message: 'We\'ve located your package! View its current status below.'
        });

        // Animate progress bar
        // setTimeout(function () {
        //     const progressBar = document.querySelector('.progress-bar-fill');
        //     if (progressBar) {
        //         progressBar.style.width = '60%';
        //     }
        // }, 500);

        // Animate timeline items
        setTimeout(function () {
            document.querySelectorAll('.timeline-item').forEach(function (item, index) {
                setTimeout(function () {
                    item.classList.add('animate');
                }, index * 200);
            });
        }, 1000);

        // Custom notification function
        function showNotification(options) {
            const notificationElement = document.createElement('div');
            notificationElement.className = 'custom-notification';
            notificationElement.innerHTML = `
                    <div class="notification-${options.type}">
                        <div class="notification-icon">
                            <i class="fas fa-${options.type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
                        </div>
                        <div class="notification-content">
                            <h4>${options.title}</h4>
                            <p>${options.message}</p>
                        </div>
                        <button type="button" class="notification-close">×</button>
                    </div>
                `;

            document.body.appendChild(notificationElement);

            // Handle close button
            const closeButton = notificationElement.querySelector('.notification-close');
            closeButton.addEventListener('click', function () {
                notificationElement.style.animation = 'fadeOutNotification 0.3s forwards';
                setTimeout(function () {
                    notificationElement.remove();
                }, 300);
            });

            // Auto-remove after 7 seconds
            setTimeout(function () {
                if (document.body.contains(notificationElement)) {
                    notificationElement.remove();
                }
            }, 7000);
        }
    });
</script>

<!-- WhatsHelp.io widget -->
<script type="text/javascript">
    (function () {
        var options = {
            whatsapp: "", // WhatsApp number
            call_to_action: "Message us", // Call to action
            position: "left", // Position may be 'right' or 'left'
        };
        var proto = document.location.protocol, host = "getbutton.io", url = proto + "//static." + host;
        var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = url + '/widget-send-button/js/init.js';
        s.onload = function () { WhWidgetSendButton.init(host, proto, options); };
        var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x);
    })();
</script>
<!-- /WhatsHelp.io widget -->
<?php
include 'footer.php';
?>