<?php
require_once __DIR__ . '/includes/db.php';

$tracking_number = '';
$shipment = null;
$sender = null;
$receiver = null;
$history = [];
$error = '';
$searched = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty(trim($_POST['tracking_number'] ?? ''))) {
    $searched = true;
    $tracking_number = strtoupper(trim($_POST['tracking_number']));

    $stmt = $pdo->prepare('SELECT * FROM shipments WHERE tracking_number = ? LIMIT 1');
    $stmt->execute([$tracking_number]);
    $shipment = $stmt->fetch();

    if ($shipment) {
        $stmt = $pdo->prepare('SELECT * FROM senders WHERE shipment_id = ? LIMIT 1');
        $stmt->execute([$shipment['id']]);
        $sender = $stmt->fetch();

        $stmt = $pdo->prepare('SELECT * FROM receivers WHERE shipment_id = ? LIMIT 1');
        $stmt->execute([$shipment['id']]);
        $receiver = $stmt->fetch();

        $stmt = $pdo->prepare('SELECT * FROM tracking_history WHERE shipment_id = ? ORDER BY sort_order ASC');
        $stmt->execute([$shipment['id']]);
        $history = $stmt->fetchAll();
    } else {
        $error = 'No shipment found for tracking number <strong>' . htmlspecialchars($tracking_number) . '</strong>. Please check and try again.';
    }
}

function status_badge(string $status): string {
    $map = [
        'order_placed' => 'secondary', 'picked_up' => 'info',
        'in_transit' => 'primary', 'out_for_delivery' => 'warning',
        'delivered' => 'success', 'on_hold' => 'danger',
        'returned' => 'dark', 'cancelled' => 'danger',
    ];
    $colour = $map[$status] ?? 'secondary';
    $label = ucwords(str_replace('_', ' ', $status));
    return '<span class="badge badge-' . $colour . '" style="font-size:14px;padding:6px 14px;">' . $label . '</span>';
}
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Track Your Shipment | Turi Express Courier Services</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" type="image/x-icon" href="uploads/686313cb0cbcasocratesLogistics.png">
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/animate.min.css">
    <link rel="stylesheet" href="css/fontawesome-all.min.css">
    <link rel="stylesheet" href="css/aos.css">
    <link rel="stylesheet" href="css/flaticon.css">
    <link rel="stylesheet" href="css/meanmenu.css">
    <link rel="stylesheet" href="css/slick.css">
    <link rel="stylesheet" href="css/default.css">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/responsive.css">
    <link rel="stylesheet" href="css/rootec92.css">
    <style>
        .track-result-wrapper{padding:40px 0;background:#f7f7f7}
        .track-card{background:#fff;border-radius:8px;padding:30px;margin-bottom:24px;box-shadow:0 2px 12px rgba(0,0,0,.07)}
        .track-card h5{font-weight:700;border-bottom:2px solid #FF440A;padding-bottom:10px;margin-bottom:20px}
        .info-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}
        .info-item label{font-size:12px;color:#888;margin-bottom:2px;display:block}
        .info-item span{font-weight:600;color:#222;font-size:14px}
        .error-box{background:#fff3f3;border-left:4px solid #e74c3c;padding:20px 24px;border-radius:6px}
        @media(max-width:600px){.info-grid{grid-template-columns:1fr}}
    </style>
</head>
<body>
<div id="preloader">
    <div id="ctn-preloader" class="ctn-preloader">
        <div class="animation-preloader"><div class="spinner"></div></div>
        <div class="loader"><div class="row">
            <div class="col-3 loader-section section-left"><div class="bg"></div></div>
            <div class="col-3 loader-section section-left"><div class="bg"></div></div>
            <div class="col-3 loader-section section-right"><div class="bg"></div></div>
            <div class="col-3 loader-section section-right"><div class="bg"></div></div>
        </div></div>
    </div>
</div>

<header>
    <div class="header-top-wrap purple-bg d-none d-md-block">
        <div class="container-fluid header-container-p">
            <div class="row">
                <div class="col-xl-6 col-lg-7 col-md-6">
                    <div class="header-contact"><ul>
                        <li><i class="fas fa-headphones"></i>09052133836</li>
                        <li><i class="far fa-envelope"></i>info@turiexpress.com</li>
                        <li><i class="fas fa-map-marker"></i>25 Ogunbiyi Street, Ajao Estate, Lagos</li>
                    </ul></div>
                </div>
                <div class="col-xl-6 col-lg-5 col-md-6">
                    <div class="header-top-right d-flex justify-content-end align-items-center">
                        <div class="header-social"><ul>
                            <li>Follow us :</li>
                            <li><a href="#"><i class="fab fa-facebook-f"></i></a></li>
                            <li><a href="#"><i class="fab fa-twitter"></i></a></li>
                            <li><a href="#"><i class="fab fa-linkedin-in"></i></a></li>
                        </ul></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div id="header-sticky" class="main-header">
        <div class="container-fluid header-container-p">
            <div class="row align-items-center">
                <div class="col-lg-3 col-md-6">
                    <div class="logo"><a href="index.php"><img src="uploads/686313cb0cbcasocratesLogistics.png" class="mobile-logo" alt="Logo"></a></div>
                </div>
                <div class="col-lg-9 col-md-6 d-none d-md-block">
                    <div class="menu-area">
                        <div class="main-menu">
                            <nav id="mobile-menu"><ul>
                                <li><a href="index.php">Home</a></li>
                                <li><a href="#">About</a><ul class="submenu">
                                    <li><a href="about-us.php">About Us</a></li>
                                    <li><a href="faq.php">FAQs</a></li>
                                </ul></li>
                                <li><a href="#">Services</a><ul class="submenu">
                                    <li><a href="cargo-transportation.php">Cargo Transportation</a></li>
                                    <li><a href="air-freight.php">Air Freight</a></li>
                                    <li><a href="ocean-freight.php">Ocean Freight</a></li>
                                    <li><a href="packaging-and-storage.php">Packaging And Storage</a></li>
                                </ul></li>
                                <li class="active"><a href="#">Tracking</a><ul class="submenu">
                                    <li><a href="track.php">Track Your Order</a></li>
                                    <li><a href="admin/signin.php">Admin Login</a></li>
                                </ul></li>
                                <li><a href="contact.php">Contact Us</a></li>
                            </ul></nav>
                        </div>
                        <div class="header-btn">
                            <a href="#" class="btn" data-toggle="modal" data-target="#exampleModalLong">
                                <img src="img/icon/calculator-symbols.png" alt="icon">Get A Quote
                            </a>
                        </div>
                    </div>
                </div>
                <div class="col-12"><div class="mobile-menu"></div></div>
            </div>
        </div>
    </div>
</header>

<main class="track">
    <section class="slider-area">
        <div class="slider-active">
            <div class="single-slider slider-bg d-flex align-items-center">
                <div class="slider-overlay-bg"></div>
                <div class="slider-bg-shape"></div>
                <div class="container">
                    <div class="row justify-content-center">
                        <div class="col-xl-10 col-lg-11">
                            <div class="slider-content text-center">
                                <h2 data-animation="fadeInUpS" data-delay=".3s">Track &amp; Trace</h2>
                                <p data-animation="fadeInUpS" data-delay=".6s">Enter your tracking ID below.</p>
                                <div class="slider-form" data-animation="fadeInUpS" data-delay=".9s">
                                    <form action="track.php" method="POST">
                                        <input type="text" name="tracking_number" placeholder="e.g. TEC-2024-0001" value="<?= htmlspecialchars($tracking_number) ?>">
                                        <button class="btn" type="submit">TRACK NOW</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <?php if ($searched): ?>
    <div class="track-result-wrapper">
        <div class="container">
            <?php if ($error): ?>
            <div class="error-box">
                <h5 style="color:#e74c3c;"><i class="fas fa-exclamation-circle"></i> Not Found</h5>
                <p style="margin:0;"><?= $error ?></p>
            </div>
            <?php else: ?>

            <!-- STATUS BANNER -->
            <div class="track-card text-center">
                <h5 style="border:none;margin-bottom:8px;">Tracking: <strong><?= htmlspecialchars($shipment['tracking_number']) ?></strong></h5>
                <p style="margin:0 0 12px;">Status: <?= status_badge($shipment['status']) ?></p>
                <?php if ($shipment['estimated_delivery']): ?>
                <p style="color:#555;margin:0;">Estimated Delivery: <strong><?= date('d M Y', strtotime($shipment['estimated_delivery'])) ?></strong></p>
                <?php endif ?>
                <?php if ($shipment['actual_delivery']): ?>
                <p style="color:#27ae60;margin:4px 0 0;"><i class="fas fa-check-circle"></i> Delivered on <?= date('d M Y, H:i', strtotime($shipment['actual_delivery'])) ?></p>
                <?php endif ?>
            </div>

            <!-- TRACKING TIMELINE -->
            <?php if (!empty($history)): ?>
            <div class="track-card">
                <h5><i class="fas fa-route"></i> Shipment Journey</h5>
                <div class="tracking-bar-section">
                <?php foreach ($history as $event):
                    $icons = ['Order Placed'=>'fa-clipboard-check','Picked Up'=>'fa-box','In Transit'=>'fa-plane','Out for Delivery'=>'fa-truck','Delivered'=>'fa-check','On Hold'=>'fa-pause-circle'];
                    $icon = 'fa-circle';
                    foreach ($icons as $k=>$v) { if (stripos($event['status'],$k)!==false){$icon=$v;break;} }
                ?>
                <div class="box <?= $event['is_active'] ? 'active' : '' ?>">
                    <div class="progress-container">
                        <div class="middle-circle"><i class="fas <?= $icon ?>"></i></div>
                    </div>
                    <div class="details">
                        <div class="status"><?= htmlspecialchars($event['status']) ?></div>
                        <?php if ($event['note']): ?><div class="note"><?= htmlspecialchars($event['note']) ?></div><?php endif ?>
                        <?php if ($event['location']): ?><div class="note" style="color:#555;"><i class="fas fa-map-marker-alt"></i> <?= htmlspecialchars($event['location']) ?></div><?php endif ?>
                        <div class="date"><?= $event['event_date'] ? date('d M Y, H:i', strtotime($event['event_date'])) : '—' ?></div>
                    </div>
                </div>
                <?php endforeach ?>
                </div>
            </div>
            <?php endif ?>

            <!-- SENDER & RECEIVER -->
            <div class="sender-and-receiver-container">
                <div class="row">
                <?php if ($sender): ?>
                <div class="col-md-6">
                    <div class="track-card">
                        <h5><i class="fas fa-user-tie"></i> Sender</h5>
                        <div class="info-grid">
                            <div class="info-item"><label>Name</label><span><?= htmlspecialchars($sender['full_name']) ?></span></div>
                            <?php if ($sender['company']): ?><div class="info-item"><label>Company</label><span><?= htmlspecialchars($sender['company']) ?></span></div><?php endif ?>
                            <div class="info-item"><label>Phone</label><span><?= htmlspecialchars($sender['phone']) ?></span></div>
                            <div class="info-item"><label>Location</label><span><?= htmlspecialchars($sender['city'].', '.$sender['country']) ?></span></div>
                        </div>
                    </div>
                </div>
                <?php endif ?>
                <?php if ($receiver): ?>
                <div class="col-md-6">
                    <div class="track-card">
                        <h5><i class="fas fa-user"></i> Receiver</h5>
                        <div class="info-grid">
                            <div class="info-item"><label>Name</label><span><?= htmlspecialchars($receiver['full_name']) ?></span></div>
                            <?php if ($receiver['company']): ?><div class="info-item"><label>Company</label><span><?= htmlspecialchars($receiver['company']) ?></span></div><?php endif ?>
                            <div class="info-item"><label>Phone</label><span><?= htmlspecialchars($receiver['phone']) ?></span></div>
                            <div class="info-item"><label>Location</label><span><?= htmlspecialchars($receiver['city'].', '.$receiver['country']) ?></span></div>
                        </div>
                    </div>
                </div>
                <?php endif ?>
                </div>
            </div>

            <!-- SHIPMENT DETAILS -->
            <div class="shipment-information-container">
                <div class="section-title">Shipment Information</div>
                <div class="track-card">
                    <div class="info-grid" style="grid-template-columns:1fr 1fr 1fr;">
                        <div class="info-item"><label>Service</label><span><?= ucwords(str_replace('_',' ',$shipment['service_type'])) ?></span></div>
                        <div class="info-item"><label>Mode</label><span><?= ucfirst($shipment['shipping_mode']) ?></span></div>
                        <div class="info-item"><label>Package Type</label><span><?= htmlspecialchars($shipment['package_type'] ?: '—') ?></span></div>
                        <div class="info-item"><label>Weight</label><span><?= $shipment['weight'] ? $shipment['weight'].' '.$shipment['weight_unit'] : '—' ?></span></div>
                        <div class="info-item"><label>Quantity</label><span><?= (int)$shipment['quantity'] ?></span></div>
                        <div class="info-item"><label>Dimensions</label><span><?= htmlspecialchars($shipment['dimensions'] ?: '—') ?></span></div>
                        <div class="info-item"><label>Origin</label><span><?= htmlspecialchars($shipment['origin_city'].', '.$shipment['origin_country']) ?></span></div>
                        <div class="info-item"><label>Destination</label><span><?= htmlspecialchars($shipment['destination_city'].', '.$shipment['destination_country']) ?></span></div>
                        <div class="info-item"><label>Ship Date</label><span><?= date('d M Y', strtotime($shipment['ship_date'])) ?></span></div>
                        <?php if ($shipment['description']): ?>
                        <div class="info-item" style="grid-column:1/-1"><label>Description</label><span><?= htmlspecialchars($shipment['description']) ?></span></div>
                        <?php endif ?>
                    </div>
                </div>
            </div>

            <!-- BARCODE -->
            <div style="text-align:center;padding:30px 0;">
                <svg id="barcode"></svg>
            </div>

            <!-- RECEIPT -->
            <?php if ($shipment['freight_charge'] > 0): ?>
            <div class="print-receipt-container" style="flex-direction:column;align-items:center;">
                <button onclick="window.print()" class="print-receipt-btn" style="cursor:pointer;border:none;margin-bottom:20px;">
                    <i class="fas fa-print"></i> Print Receipt
                </button>
                <div class="receipt">
                    <div class="watermark-container"><img class="watermark-image" src="uploads/686313cb0cbcasocratesLogistics.png" alt=""></div>
                    <div class="top-section">
                        <div class="logo-container"><img class="logo" src="uploads/686313cb0cbcasocratesLogistics.png" alt="logo"></div>
                        <div class="invoice-summary-container">
                            <div class="box"><div class="left">Tracking Number</div><div class="right"><?= htmlspecialchars($shipment['tracking_number']) ?></div></div>
                            <div class="box"><div class="left">Ship Date</div><div class="right"><?= date('d M Y', strtotime($shipment['ship_date'])) ?></div></div>
                            <div class="box"><div class="left">Status</div><div class="right"><?= ucwords(str_replace('_',' ',$shipment['status'])) ?></div></div>
                            <div class="box"><div class="left">Origin</div><div class="right"><?= htmlspecialchars($shipment['origin_city'].', '.$shipment['origin_country']) ?></div></div>
                            <div class="box"><div class="left">Destination</div><div class="right"><?= htmlspecialchars($shipment['destination_city'].', '.$shipment['destination_country']) ?></div></div>
                        </div>
                        <table>
                            <thead><tr><th>Charge Type</th><th style="text-align:right;">Amount (<?= htmlspecialchars($shipment['currency']) ?>)</th></tr></thead>
                            <tbody>
                                <tr><td>Freight Charge</td><td style="text-align:right;"><?= number_format($shipment['freight_charge'],2) ?></td></tr>
                                <tr><td>Insurance</td><td style="text-align:right;"><?= number_format($shipment['insurance_charge'],2) ?></td></tr>
                                <tr><td>Handling</td><td style="text-align:right;"><?= number_format($shipment['handling_charge'],2) ?></td></tr>
                                <?php if ($shipment['other_charge'] > 0): ?>
                                <tr><td>Other Charges</td><td style="text-align:right;"><?= number_format($shipment['other_charge'],2) ?></td></tr>
                                <?php endif ?>
                                <tr><td class="total-charge"><strong>TOTAL</strong></td><td class="total-charge" style="text-align:right;"><strong><?= number_format($shipment['total_charge'],2) ?></strong></td></tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <?php endif ?>

            <?php endif ?>
        </div>
    </div>
    <?php endif ?>

    <section class="newsletter-area">
        <div class="container">
            <div class="newsletter-wrap">
                <div class="row">
                    <div class="col-lg-5"><div class="newsletter-content"><h4>Newsletter Sign Up</h4><span>Get notified of our best deals...</span></div></div>
                    <div class="col-lg-7"><div class="newsletter-form"><form action="newsletter.php" method="POST"><input type="email" name="email" placeholder="Enter your email..."><button class="btn" type="submit">subscribe</button></form></div></div>
                </div>
            </div>
        </div>
    </section>
</main>

<footer>
    <div class="footer-wrap pt-190 pb-40" data-background="img/bg/footer_bg.jpg">
        <div class="container"><div class="row">
            <div class="col-xl-3 col-lg-4 col-md-6"><div class="footer-widget mb-50">
                <div class="footer-logo mb-35"><a href="index.php"><img src="uploads/686313cb0cbcasocratesLogistics.png" alt="logo"></a></div>
                <div class="footer-text"><p>Trusted, Reliable and Insured Delivery Services. Ensuring the secure transport of your valuable assets.</p></div>
            </div></div>
            <div class="col-xl-3 col-lg-4 col-md-6"><div class="footer-widget mb-50">
                <div class="fw-title mb-30"><h5>SERVICES</h5></div>
                <div class="fw-link"><ul>
                    <li><a href="cargo-transportation.php"><i class="fas fa-caret-right"></i> Cargo Transportation</a></li>
                    <li><a href="air-freight.php"><i class="fas fa-caret-right"></i> Air Freight</a></li>
                    <li><a href="ocean-freight.php"><i class="fas fa-caret-right"></i> Ocean Freight</a></li>
                    <li><a href="packaging-and-storage.php"><i class="fas fa-caret-right"></i> Packaging And Storage</a></li>
                </ul></div>
            </div></div>
            <div class="col-xl-3 col-lg-4 col-md-6"><div class="footer-widget mb-50">
                <div class="fw-title mb-30"><h5>QUICK LINKS</h5></div>
                <div class="fw-link"><ul>
                    <li><a href="index.php"><i class="fas fa-caret-right"></i> Home</a></li>
                    <li><a href="track.php"><i class="fas fa-caret-right"></i> Track Shipment</a></li>
                    <li><a href="contact.php"><i class="fas fa-caret-right"></i> Contact Us</a></li>
                    <li><a href="admin/signin.php"><i class="fas fa-caret-right"></i> Admin Login</a></li>
                </ul></div>
            </div></div>
            <div class="col-xl-3 col-lg-4 col-md-6"><div class="footer-widget mb-50">
                <div class="fw-title mb-30"><h5>Location</h5></div>
                <div class="f-support-content"><p>25 Ogunbiyi Street, Ajao Estate, Lagos</p></div>
                <div class="fw-title mb-30"><h5>Call Center</h5></div>
                <div class="f-support-content"><p>09052133836</p></div>
            </div></div>
        </div></div>
    </div>
    <div class="copyright-wrap">
        <div class="container"><div class="row align-items-center">
            <div class="col-lg-6 col-md-7"><div class="copyright-text"><p>Copyright &copy; <span>Turi Express Courier Services</span> | All Rights Reserved</p></div></div>
            <div class="col-lg-6 col-md-5"><div class="f-payment-method text-center text-md-right"><img src="img/images/card_img.png" alt="img"></div></div>
        </div></div>
    </div>
</footer>

<script src="js/vendor/jquery-1.12.4.min.js"></script>
<script src="js/popper.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/slick.min.js"></script>
<script src="js/jquery.meanmenu.min.js"></script>
<script src="js/wow.min.js"></script>
<script src="js/aos.js"></script>
<script src="js/jquery.scrollUp.min.js"></script>
<script src="js/main.js"></script>
<script src="js/JsBarcode.all.min.js"></script>
<script>
<?php if ($shipment): ?>
JsBarcode("#barcode","<?= htmlspecialchars($shipment['tracking_number']) ?>",{format:"CODE128",width:2,height:60,displayValue:true,fontSize:14});
<?php else: ?>
if(document.getElementById('barcode'))JsBarcode("#barcode","");
<?php endif ?>
</script>
</body>
</html>
