<?php require './partials/head.php';
require './config/message/error_success.php'; ?>
<!-- Brand Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">

<style>
  body { font-family: 'Roboto', sans-serif; }
  .brand-logo { height: 40px; }
</style>

<body>
<?php require './partials/header.php'; ?>
<!--/.main-header-->

<div id="popup-search-box">
  <div class="box-inner-wrap d-flex align-items-center">
    <form id="form" action="#" method="get" role="search">
      <input id="popup-search" type="text" name="s" placeholder="Type keywords here..." />
      <button id="popup-search-button" type="submit" name="submit">
        <i class="fa-sharp fa-light fa-magnifying-glass"></i>
      </button>
    </form>
    <div class="search-close"><i class="fa-regular fa-xmark"></i></div>
  </div>
</div>

<style>
  :root {
    --accent: #df1119;
    --bg-soft: #f7f7f8;
    --text-muted: #6b7280;
    --card-radius: 16px;
  }

  .page-hero {
    background: linear-gradient(135deg, rgba(223,17,25,0.08), rgba(0,0,0,0.04));
    border-bottom: 1px solid #ececec;
  }
  .page-hero .hero-inner {
    padding: 48px 0 24px;
  }
  .hero-title {
    font-weight: 800;
    letter-spacing: -0.02em;
  }
  .hero-sub {
    color: var(--text-muted);
  }

  .track-card {
    border: 1px solid #eee;
    border-radius: var(--card-radius);
    box-shadow: 0 6px 24px rgba(16,24,40,0.06);
  }

  .track-input {
    height: 52px;
    padding: 10px 14px;
    border: 2px solid var(--accent);
    font-weight: 600;
    border-radius: 12px;
  }
  .track-btn {
    height: 52px;
    font-weight: 700;
    border-radius: 12px;
    background: var(--accent);
    border: 0;
  }
  .track-btn:disabled {
    opacity: .7;
    cursor: not-allowed;
  }

  /* Summary card */
  .summary-card {
    border: 1px solid #eee;
    border-radius: var(--card-radius);
  }
  .summary-badge {
    font-size: .82rem;
    font-weight: 700;
    padding: .4rem .7rem;
    border-radius: 999px;
  }

  .badge-delivered { background: #ecfdf5; color: #065f46; }
  .badge-transit   { background: #fffbeb; color: #92400e; }
  .badge-shipped   { background: #eef2ff; color: #3730a3; }
  .badge-pending   { background: #ffe4e6; color: #9f1239; }
  .badge-default   { background: #f1f5f9; color: #0f172a; }

  /* Progress steps */
  .steps {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 12px;
    margin-top: 16px;
  }
  .step {
    text-align: center;
  }
  .step .dot {
    width: 12px; height: 12px; border-radius: 999px; margin: 0 auto 8px;
    background: #e5e7eb;
  }
  .step.active .dot { background: var(--accent); }
  .step .label { font-size: .78rem; color: #111827; font-weight: 600; }
  .step .hint  { font-size: .72rem; color: var(--text-muted); }

  .progress-wrap {
    height: 8px; background: #f1f5f9; border-radius: 999px; overflow: hidden;
  }
  .progress-barx {
    height: 100%; width: 0%;
    background: var(--accent);
    transition: width .5s ease;
  }

  /* Timeline */
  .timeline {
    border-left: 2px solid #e5e7eb;
    padding-left: 16px;
  }
  .timeline .tl-item {
    position: relative; margin-bottom: 18px;
  }
  .timeline .tl-item::before {
    content: ""; position: absolute; left: -7px; top: 4px;
    width: 10px; height: 10px; border-radius: 999px; background: var(--accent);
  }
  .timeline .tl-title { font-weight: 700; }
  .timeline .tl-meta  { font-size: .8rem; color: var(--text-muted); }

  /* Table */
  .result-table th, .result-table td {
    vertical-align: middle;
  }

  /* Skeleton loader */
  .skeleton {
    border-radius: 12px;
    background: linear-gradient(90deg,#f4f4f5 25%, #eaeaea 37%, #f4f4f5 63%);
    background-size: 400% 100%;
    animation: shimmer 1.2s infinite;
  }
  @keyframes shimmer {
    0% { background-position: 100% 0; }
    100% { background-position: -100% 0; }
  }

  /* Map */
  #mapFrame { border:0; width:100%; height: 420px; border-radius: 12px; }

  /* Accessibility live region */
  .sr-live {
    position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden;
  }
</style>

<div id="searchbox-overlay"></div>

<!-- HERO -->
<section class="page-hero">
  <div class="container hero-inner">
    <div class="row align-items-center g-3">
      <div class="col-lg-7">
        <h1 class="hero-title display-5 mb-2">Track your delivery</h1>
        <p class="hero-sub mb-0">Enter your tracking ID to view live status, route, and delivery milestones.</p>
      </div>
      <div class="col-lg-5">
        <div class="p-3 p-md-4 bg-white track-card">
          <div class="row gx-2 gy-2">
            <div class="col-12 col-md-8">
              <label for="trackInput" class="visually-hidden">Tracking number</label>
              <input type="text" id="trackInput" class="form-control track-input"
                     placeholder="e.g. WL-1234-5678" autocomplete="off" />
            </div>
            <div class="col-12 col-md-4 d-grid">
              <button id="trackButton" class="btn btn-danger track-btn">
                <i class="fa-regular fa-truck-fast me-1"></i> Track
              </button>
            </div>
          </div>
          <div class="mt-2 small text-muted">
            Tip: You can also press <kbd>Enter</kbd> to search.
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

<!-- RESULTS -->
<section class="py-4 py-md-5">
  <div class="container">
    <!-- Live region for screen readers -->
    <div id="liveRegion" class="sr-live" aria-live="polite"></div>

    <!-- Loading skeleton -->
    <div id="loadingCard" class="skeleton p-4 mb-4" style="display:none; height: 120px;"></div>

    <!-- Summary -->
    <!-- Summary -->
<div id="summaryContainer" class="summary-card p-3 p-md-4 mb-4" style="display:none;">
  <div class="d-flex align-items-start justify-content-between gap-3 flex-wrap">
    
    <!-- Package Image -->
    <div class="text-center">
      <img id="sumPkgImg" src="" alt="Package image" class="img-fluid rounded border" style="max-width:120px; display:none;">
      <div class="small text-muted mt-1">Package</div>
    </div>

    <!-- Tracking ID -->
    <div>
      <div class="text-uppercase text-muted fw-bold small">Tracking ID</div>
      <div class="fs-5 fw-bold" id="sumTrackNo">—</div>
      <div class="small text-muted" id="sumPkgName">—</div>
    </div>

    <!-- Current Location -->
    <div>
      <div class="text-uppercase text-muted fw-bold small">Current Location</div>
      <div class="fw-semibold" id="sumCurrentLoc">—</div>
      <div class="small text-muted">Destination: <span id="sumDest">—</span></div>
    </div>

    <!-- Status -->
    <div class="text-end">
      <span id="sumBadge" class="summary-badge badge-default">—</span>
      <div class="small text-muted mt-1">Last update: <span id="sumUpdated">—</span></div>
    </div>
  </div>

  <!-- Progress Steps -->
  <div class="mt-3">
    <div class="progress-wrap mb-2">
      <div id="progressBar" class="progress-barx"></div>
    </div>
    <div class="steps">
      <div class="step" id="st-0"><div class="dot"></div><div class="label">Ordered</div><div class="hint" id="st-0-hint"></div></div>
      <div class="step" id="st-1"><div class="dot"></div><div class="label">Shipped</div><div class="hint" id="st-1-hint"></div></div>
      <div class="step" id="st-2"><div class="dot"></div><div class="label">In Transit</div><div class="hint" id="st-2-hint"></div></div>
      <div class="step" id="st-3"><div class="dot"></div><div class="label">Out for Delivery</div><div class="hint" id="st-3-hint"></div></div>
      <div class="step" id="st-4"><div class="dot"></div><div class="label">Delivered</div><div class="hint" id="st-4-hint"></div></div>
    </div>
  </div>
</div>


    <!-- Table -->
    <div id="trackTableContainer" class="table-responsive" style="display:none;">
      <table class="table table-hover result-table">
        <thead class="table-light">
          <tr>
            <th>Tracking ID</th>
            <th>Email</th>
            <th>Current Location</th>
            <th>Package</th>
            <th>Status</th>
            <th style="width: 1%"></th>
          </tr>
        </thead>
        <tbody id="trackTable"></tbody>
      </table>
    </div>

    <!-- Timeline & Map -->
    <div id="detailRow" class="row g-4 mt-1" style="display:none;">
      <div class="col-lg-6">
        <div class="card h-100">
          <div class="card-body">
            <div class="d-flex align-items-center justify-content-between mb-2">
              <h5 class="mb-0">Shipment timeline</h5>
              <i class="fa-regular fa-clock"></i>
            </div>
            <div id="timeline" class="timeline"></div>
          </div>
        </div>
      </div>
      <div class="col-lg-6">
        <div class="card h-100">
          <div class="card-body">
            <h5 class="mb-3">Live route map</h5>
            <iframe id="mapFrame" loading="lazy" referrerpolicy="no-referrer-when-downgrade" allowfullscreen></iframe>
          </div>
        </div>
      </div>
    </div>

  </div>
</section>

<footer class="footer-section">
  <div class="map-pattern"></div>
  <div class="footer-wrapper">
    <div class="container">
      <div class="row gy-lg-0 gy-4"></div>
    </div>
    <div class="running-truck">
      <div class="truck"></div>
      <div class="truck-2"></div>
      <div class="truck-3"></div>
    </div>
  </div>
  <div class="copyright-area">
    © <span id="currentYear"></span> Swift Way Logistics, All Rights Reserved. Design By
    <a href="javascript:void(0);" target="_blank">primeportgloballogistics.org</a>
  </div>
</footer>

<div id="scrollup">
  <button id="scroll-top" class="scroll-to-top"><i class="fa-regular fa-arrow-up"></i></button>
</div>

<?php require './partials/scripts.php'; ?>

<script>
  // Utility: escape HTML
  function esc(str) {
    return String(str ?? "").replace(/[&<>"']/g, s => ({
      "&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"
    }[s]));
  }

  // Status helpers
  const STATUSES = ["ordered","shipped","in transit","out for delivery","delivered"];

  function statusIndex(status) {
    const s = (status || "").toLowerCase().trim();
    const idx = STATUSES.indexOf(s);
    if (idx >= 0) return idx;
    if (s.includes("transit")) return 2;
    if (s.includes("out")) return 3;
    if (s.includes("deliver")) return 4;
    if (s.includes("ship")) return 1;
    if (s.includes("pend")) return 0;
    return 0;
  }

  function statusBadgeClass(status) {
    const s = (status || "").toLowerCase();
    if (s.includes("deliver") && !s.includes("out")) return "badge-delivered";
    if (s.includes("transit") || s.includes("out")) return "badge-transit";
    if (s.includes("ship")) return "badge-shipped";
    if (s.includes("pend")) return "badge-pending";
    return "badge-default";
  }

  // UI elements
  const input = document.getElementById("trackInput");
  const btn = document.getElementById("trackButton");
  const live = document.getElementById("liveRegion");
  const loadingCard = document.getElementById("loadingCard");

  const summary = document.getElementById("summaryContainer");
  const sumTrackNo = document.getElementById("sumTrackNo");
  const sumPkgName = document.getElementById("sumPkgName");
  const sumCurrentLoc = document.getElementById("sumCurrentLoc");
  const sumDest = document.getElementById("sumDest");
  const sumBadge = document.getElementById("sumBadge");
  const sumUpdated = document.getElementById("sumUpdated");
  const progressBar = document.getElementById("progressBar");

  const tableWrap = document.getElementById("trackTableContainer");
  const tableBody = document.getElementById("trackTable");

  const timeline = document.getElementById("timeline");
  const detailRow = document.getElementById("detailRow");
  const mapFrame = document.getElementById("mapFrame");

  // Activate steps
  function paintSteps(idx, hints = {}) {
    for (let i = 0; i < 5; i++) {
      const el = document.getElementById(`st-${i}`);
      const hintEl = document.getElementById(`st-${i}-hint`);
      if (!el) continue;
      if (i <= idx) el.classList.add("active"); else el.classList.remove("active");
      if (hintEl) hintEl.textContent = hints[i] || "";
    }
    const pct = ((idx) / 4) * 100;
    progressBar.style.width = pct + "%";
  }

  // Build timeline from data.history (array of {title, meta})
  function buildTimeline(history = []) {
    timeline.innerHTML = "";
    if (!Array.isArray(history) || !history.length) {
      timeline.innerHTML = '<div class="text-muted small">No timeline events yet.</div>';
      return;
    }
    history.forEach(item => {
      const wrap = document.createElement("div");
      wrap.className = "tl-item";
      wrap.innerHTML = `
        <div class="tl-title">${esc(item.title || "Update")}</div>
        <div class="tl-meta">${esc(item.meta || "")}</div>
      `;
      timeline.appendChild(wrap);
    });
  }

  function setMap(origin, destination) {
    const o = encodeURIComponent(origin || "");
    const d = encodeURIComponent(destination || "");
    if (!o || !d) { mapFrame.removeAttribute("src"); return; }
    mapFrame.src = `https://www.google.com/maps?q=${o}+to+${d}&output=embed`;
  }

  function setLoading(on) {
    loadingCard.style.display = on ? "block" : "none";
    btn.disabled = on;
  }

  function validateTrackNo(val) {
    return !!(val && val.trim().length >= 4);
  }

  // Render result
  function renderShipment(data) {
    // Summary
    sumTrackNo.textContent = data.trackNo || "—";
    sumPkgName.textContent = data.package_name || data.package || "—";
    sumCurrentLoc.textContent = data.current_location || "—";
    sumDest.textContent = data.destination || "—";
    sumBadge.textContent = data.status || "—";
    sumBadge.className = `summary-badge ${statusBadgeClass(data.status)}`;
    sumUpdated.textContent = data.updated_at || data.updatedAt || new Date().toLocaleString();

    // Add package image if available
    const imgEl = document.getElementById("sumPkgImg");
    if (data.package_image) {
      imgEl.src = "uploads/" + esc(data.package_image);
      imgEl.style.display = "block";
    } else {
      imgEl.style.display = "none";
    }

    const idx = statusIndex(data.status);
    paintSteps(idx, {
      0: data.ordered_at ? new Date(data.ordered_at).toLocaleDateString() : "",
      1: data.shipped_at ? new Date(data.shipped_at).toLocaleDateString() : "",
      2: data.in_transit_at ? new Date(data.in_transit_at).toLocaleDateString() : "",
      3: data.out_for_delivery_at ? new Date(data.out_for_delivery_at).toLocaleDateString() : "",
      4: data.delivered_at ? new Date(data.delivered_at).toLocaleDateString() : ""
    });

    summary.style.display = "block";

    // Table (add thumbnail in package column)
    const row = `
      <tr>
        <td class="fw-bold">${esc(data.trackNo)}</td>
        <td>${esc(data.user_email || data.email || "—")}</td>
        <td>${esc(data.current_location || "—")}</td>
        <td>
          ${esc(data.package_name || data.package || "—")}
          ${data.package_image ? `<br><img src="uploads/${esc(data.package_image)}" alt="Package" style="max-height:40px;" />` : ""}
        </td>
        <td class="fw-bold ${statusBadgeClass(data.status).replace('badge-','text-')}">${esc(data.status || "—")}</td>
        <td>
          <button class="btn btn-sm btn-outline-primary" onclick="window.location.href='view/${encodeURIComponent(data.trackNo)}'">
            View
          </button>
        </td>
      </tr>
    `;
    tableBody.innerHTML = row;
    tableWrap.style.display = "block";

    // Timeline & Map
    buildTimeline(Array.isArray(data.history) ? data.history : []);
    setMap(data.current_location, data.destination);
    detailRow.style.display = "flex";
  }

  function clearResults() {
    summary.style.display = "none";
    tableWrap.style.display = "none";
    detailRow.style.display = "none";
    tableBody.innerHTML = "";
    timeline.innerHTML = "";
    mapFrame.removeAttribute("src");
  }

  async function doTrack() {
    const trackNo = input.value.trim();
    if (!validateTrackNo(trackNo)) {
      toastr.error("Please enter a valid tracking number.", "Invalid");
      input.focus();
      return;
    }

    clearResults();
    setLoading(true);
    live.textContent = "Searching for tracking information…";

    try {
      const resp = await fetch("trackOrder?trackNo=" + encodeURIComponent(trackNo), {
        headers: { "Accept": "application/json" }
      });

      if (!resp.ok) throw new Error("Network error: " + resp.status);

      const data = await resp.json();

      if (data && data.success) {
        renderShipment(data);
        live.textContent = "Tracking information found.";
        toastr.success("Tracking information found!", "Success");
        // Persist last search
        try { localStorage.setItem("lastTrackNo", trackNo); } catch(e){}
      } else {
        live.textContent = "Tracking number not found.";
        toastr.warning("Tracking number not found.", "Not found");
      }
    } catch (err) {
      console.error("Error fetching tracking data:", err);
      live.textContent = "Error fetching tracking data.";
      toastr.error("Error fetching tracking data. Please try again.", "Error");
    } finally {
      setLoading(false);
    }
  }

  // Events
  btn.addEventListener("click", doTrack);
  input.addEventListener("keyup", (e) => {
    if (e.key === "Enter") doTrack();
  });

  // Autofill last searched tracking number
  (function init() {
    const y = document.getElementById("currentYear");
    if (y) y.textContent = new Date().getFullYear();
    try {
      const last = localStorage.getItem("lastTrackNo");
      if (last && !input.value) input.value = last;
    } catch(e){}
  })();
</script>


</body>
</html>
