<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../app/Utils.php';
require_once __DIR__ . '/../app/Models/Parcel.php';
require_once __DIR__ . '/../includes/trackheader.php';


$parcel_model = new Parcel($pdo);
$parcel = null;
$updates = [];
$error = null;

// Get tracking code from URL or form
$tracking_code = $_GET['code'] ?? $_POST['tracking_code'] ?? null;

if ($tracking_code) {
  // $tracking_code = Utils::sanitize($tracking_code); // Utils::sanitize is good practice
  $parcel = $parcel_model->getByTrackingCode($tracking_code);

  if (!$parcel) {
    $error = 'Parcel not found. Please check your tracking code.';
  } else {
    $updates = $parcel_model->getUpdates($parcel['id']);
  }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Shipment Tracking | Routex Shipping</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <script src="https://cdn.tailwindcss.com"></script>
  <link
  rel="stylesheet"
  href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
/>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">


  <style>
    /* Map Marker Animations */
    .marker-icon {
      background: transparent;
      border: none;
    }
    .marker-pin {
      width: 40px;
      height: 40px;
      border-radius: 50% 50% 50% 0;
      background: #0B2C4D;
      position: absolute;
      transform: rotate(-45deg);
      left: 50%;
      top: 50%;
      margin: -20px 0 0 -20px;
      box-shadow: 0 3px 5px rgba(0,0,0,0.3);
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .marker-pin::after {
      content: '';
      width: 24px;
      height: 24px;
      margin: 8px 0 0 8px;
      background: #fff;
      position: absolute;
      border-radius: 50%;
    }
    .marker-icon i {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      z-index: 10;
      font-size: 16px;
      color: #0B2C4D;
    }
    .pulse {
      animation: pulse-animation 2s infinite;
    }
    @keyframes pulse-animation {
      0% { box-shadow: 0 0 0 0 rgba(249, 115, 22, 0.7); }
      70% { box-shadow: 0 0 0 15px rgba(249, 115, 22, 0); }
      100% { box-shadow: 0 0 0 0 rgba(249, 115, 22, 0); }
    }
  </style>

  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#0B2C4D',
            accent: '#F97316'
          }
        }
      }
    }
  </script>
</head>

<body class="bg-gray-100 text-gray-800">

  <main class="max-w-5xl mx-auto bg-white my-10 p-6 md:p-10 shadow-lg rounded-lg">

    <!-- LOGO -->
    <div class="text-center mb-6">
      <h1 class="text-3xl font-bold text-primary">Routex Shipping</h1>
      <p class="text-sm text-gray-500">Global Logistics & Freight Services</p>
    </div>

    <!-- SEARCH FORM -->
    <form method="GET" class="max-w-md mx-auto mb-10 flex gap-2">
        <input type="text" name="code" value="<?= htmlspecialchars($tracking_code ?? '') ?>" class="flex-1 p-3 border border-gray-300 rounded focus:outline-none focus:border-primary" placeholder="Enter Tracking Number" required>
        <button type="submit" class="bg-accent text-white px-6 py-3 rounded font-bold hover:bg-opacity-90 transition">Track</button>
    </form>

    <?php if ($error): ?>
        <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-8 text-center" role="alert">
            <p><?= htmlspecialchars($error) ?></p>
        </div>
    <?php endif; ?>

    <?php if ($parcel): ?>
    <!-- ACTIONS -->
    <div class="flex justify-end mb-6">
        <a href="print-invoice?code=<?= urlencode($parcel['tracking_code']) ?>" target="_blank" class="inline-flex items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-md transition-colors shadow-sm">
            <i class="fas fa-file-invoice mr-2"></i> Print Invoice
        </a>
    </div>

    <!-- BARCODE -->
    <div class="flex justify-center mb-8">
      <img
        src="https://barcode.tec-it.com/barcode.ashx?data=<?= htmlspecialchars($parcel['tracking_code']) ?>&code=Code128&translate-esc=true"
        alt="Tracking Barcode"
        class="h-20"
      />
    </div>

    <!-- SHIPPER / RECEIVER -->
    <div class="grid md:grid-cols-2 gap-6 mb-8">

      <table class="w-full border">
        <thead class="bg-primary text-white">
          <tr><th class="p-2 text-left">Shipper Information</th></tr>
        </thead>
        <tbody>
          <tr><td class="p-3">
            <strong><?= htmlspecialchars($parcel['sender_name']) ?></strong><br>
            <?= htmlspecialchars($parcel['sender_address']) ?><br>
            <?= htmlspecialchars($parcel['sender_city'] . ', ' . $parcel['sender_country']) ?><br>
            <?= htmlspecialchars($parcel['sender_email']) ?>
          </td></tr>
        </tbody>
      </table>

      <table class="w-full border">
        <thead class="bg-primary text-white">
          <tr><th class="p-2 text-left">Receiver Information</th></tr>
        </thead>
        <tbody>
          <tr><td class="p-3">
            <strong><?= htmlspecialchars($parcel['receiver_name']) ?></strong><br>
            <?= htmlspecialchars($parcel['receiver_address']) ?><br>
            <?= htmlspecialchars($parcel['receiver_city'] . ', ' . $parcel['receiver_country']) ?><br>
            <?= htmlspecialchars($parcel['receiver_email']) ?>
          </td></tr>
        </tbody>
      </table>

    </div>

    <!-- SHIPMENT STATUS -->
    <table class="w-full border mb-8">
      <thead class="bg-accent text-white">
        <tr><th class="p-2 text-left">Shipment Status</th></tr>
      </thead>
      <tbody>
        <tr>
          <td class="p-3">
            <span class="<?= Utils::getStatusColor($parcel['status']) ?> px-3 py-1 rounded-full font-semibold text-sm">
                <?= Utils::getStatusLabel($parcel['status']) ?>
            </span>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- SHIPMENT INFORMATION -->
    <table class="w-full border mb-8 text-sm">
      <thead class="bg-primary text-white">
        <tr><th colspan="4" class="p-2 text-left">Shipment Information</th></tr>
      </thead>
      <tbody class="divide-y">

        <tr>
          <td class="p-2 font-medium">Origin:</td><td><?= htmlspecialchars($parcel['sender_country']) ?></td>
          <td class="p-2 font-medium">Destination:</td><td><?= htmlspecialchars($parcel['receiver_country']) ?></td>
        </tr>

        <tr>
          <td class="p-2 font-medium">Package:</td><td><?= htmlspecialchars($parcel['package_description']) ?></td>
          <td class="p-2 font-medium">Carrier:</td><td>Routex</td>
        </tr>

        <tr>
          <td class="p-2 font-medium">Service Type:</td><td class="capitalize"><?= htmlspecialchars(str_replace('_', ' ', $parcel['service_type'])) ?></td>
          <td class="p-2 font-medium">Current Location:</td><td><?= htmlspecialchars($parcel['current_location']) ?></td>
        </tr>

        <tr>
          <td class="p-2 font-medium">Weight:</td><td><?= htmlspecialchars($parcel['package_weight']) ?> kg</td>
          <td class="p-2 font-medium">Tracking No:</td><td><?= htmlspecialchars($parcel['tracking_code']) ?></td>
        </tr>

        <tr>
          <td class="p-2 font-medium">Dimensions:</td><td><?= htmlspecialchars($parcel['package_dimensions']) ?></td>
          <td class="p-2 font-medium">Qty:</td><td>1</td>
        </tr>

        <tr>
          <td class="p-2 font-medium">Created Date:</td><td><?= Utils::formatDate($parcel['created_at']) ?></td>
          <td class="p-2 font-medium">Expected Delivery:</td><td><?= Utils::formatDate($parcel['estimated_delivery']) ?></td>
        </tr>

        <tr>
          <td class="p-2 font-medium">Departure Time:</td><td><?= date('H:i A', strtotime($parcel['created_at'])) ?></td>
          <td class="p-2 font-medium">Pick-up Date:</td><td><?= Utils::formatDate($parcel['created_at']) ?></td>
        </tr>

        <tr>
          <td class="p-2 font-medium">Comments:</td>
          <td colspan="3"><?= htmlspecialchars($parcel['notes'] ?: 'No comments') ?></td>
        </tr>

      </tbody>
    </table>

    <!-- PACKAGES -->
    <div class="overflow-x-auto">
      <table class="w-full border text-sm">
        <thead class="bg-primary text-white">
          <tr>
            <th class="p-2">Qty.</th>
            <th>Piece Type</th>
            <th>Description</th>
            <th>Length (cm)</th>
            <th>Width (cm)</th>
            <th>Height (cm)</th>
            <th>Weight (kg)</th>
          </tr>
        </thead>
        <tbody>
          <tr class="text-center border-t">
            <td class="p-2">1</td>
            <td>Package</td>
            <td><?= htmlspecialchars($parcel['package_description']) ?></td>
            <td colspan="3"><?= htmlspecialchars($parcel['package_dimensions']) ?></td>
            <td><?= htmlspecialchars($parcel['package_weight']) ?> kg</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- SHIPMENT HISTORY -->
    <?php if (!empty($updates)): ?>
    <div class="mt-8">
        <h2 class="text-lg font-semibold text-primary mb-3">Shipment History</h2>
        <div class="border rounded-md overflow-hidden">
            <table class="w-full text-sm">
                <thead class="bg-gray-50 border-b">
                    <tr>
                        <th class="p-3 text-left">Date & Time</th>
                        <th class="p-3 text-left">Status</th>
                        <th class="p-3 text-left">Location</th>
                        <th class="p-3 text-left">Remarks</th>
                    </tr>
                </thead>
                <tbody class="divide-y">
                    <?php foreach ($updates as $update): ?>
                    <tr>
                        <td class="p-3"><?= Utils::formatDateTime($update['created_at']) ?></td>
                        <td class="p-3"><span class="<?= Utils::getStatusColor($update['status']) ?> px-2 py-1 rounded-full text-xs"><?= Utils::getStatusLabel($update['status']) ?></span></td>
                        <td class="p-3"><?= htmlspecialchars($update['location']) ?></td>
                        <td class="p-3"><?= htmlspecialchars($update['description']) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <!-- TOTALS -->
    <div class="mt-4 text-sm space-y-1">
      <p><strong>Total Actual Weight:</strong> <?= htmlspecialchars($parcel['package_weight']) ?> kg</p>
    </div>

    <!-- LIVE SHIPMENT LOCATION MAP -->
<div class="mt-10">
  <h2 class="text-lg font-semibold text-primary mb-3">
    Live Shipment Location
  </h2>

  <div
    id="shipmentMap"
    class="w-full border rounded-md" style="height: 360px;"
  ></div>
</div>
<?php endif; ?>

  </main>

<?php if ($parcel): ?>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
  document.addEventListener('DOMContentLoaded', function() {
    const trackingCode = "<?= $parcel['tracking_code'] ?>";
    
    // Initial Coordinates (Fallback if 0)
    let currentLat = <?= $parcel['current_latitude'] ? $parcel['current_latitude'] : '51.505' ?>;
    let currentLng = <?= $parcel['current_longitude'] ? $parcel['current_longitude'] : '-0.09' ?>;
    
    // Initialize Map
    const map = L.map('shipmentMap').setView([currentLat, currentLng], 5);

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '&copy; OpenStreetMap contributors'
    }).addTo(map);

    // Marker Icons
    const getIcon = (type, status) => {
      let iconClass = 'fa-box';
      if (type === 'air_freight') iconClass = 'fa-plane';
      else if (type === 'sea_freight') iconClass = 'fa-ship';
      else if (type === 'road_transport') iconClass = 'fa-truck';

      let markerColor = '#0B2C4D'; // Default Primary
      let pulseClass = '';

      if (status === 'in_transit') {
        markerColor = '#F97316'; // Orange
        pulseClass = 'pulse';
      } else if (status === 'delivered') {
        markerColor = '#10B981'; // Green
      } else if (status === 'on_hold') {
        markerColor = '#EF4444'; // Red
      }

      return L.divIcon({
        className: 'marker-icon',
        html: `<div class="marker-pin ${pulseClass}" style="background-color: ${markerColor}"></div><i class="fas ${iconClass}"></i>`,
        iconSize: [40, 40],
        iconAnchor: [20, 40],
        popupAnchor: [0, -45]
      });
    };

    let marker = L.marker([currentLat, currentLng], {
      icon: getIcon("<?= $parcel['service_type'] ?>", "<?= $parcel['status'] ?>")
    }).addTo(map);

    marker.bindPopup(`
      <div class="text-center">
        <h3 class="font-bold text-primary">Current Location</h3>
        <p class="text-sm"><?= htmlspecialchars($parcel['current_location']) ?></p>
        <span class="text-xs font-semibold uppercase text-gray-500"><?= Utils::getStatusLabel($parcel['status']) ?></span>
      </div>
    `).openPopup();

    // Route Polyline (Simulated for demo as we don't have sender/receiver coords in DB yet)
    // In a real scenario, you would fetch sender_latitude/longitude and receiver_latitude/longitude
    // For now, we visualize the current point.
    
    // --- Live Update Logic ---
    function updateMap() {
      fetch(`/routex/api/track?code=${trackingCode}`)
        .then(response => response.json())
        .then(data => {
          if (data.error) return;

          const newLat = data.current_latitude;
          const newLng = data.current_longitude;
          const status = data.status;
          const type = data.service_type;

          // Update Marker Position
          if (newLat && newLng && (newLat !== 0 || newLng !== 0)) {
            const newLatLng = new L.LatLng(newLat, newLng);
            marker.setLatLng(newLatLng);
            map.panTo(newLatLng);
          }

          // Update Icon based on status
          marker.setIcon(getIcon(type, status));

          // Update Popup
          let popupContent = `
            <div class="text-center">
              <h3 class="font-bold text-primary">Current Location</h3>
              <p class="text-sm">${data.current_location}</p>
              <span class="text-xs font-semibold uppercase text-gray-500">${status.replace('_', ' ')}</span>
            </div>
          `;
          
          // Status specific tooltips
          if (status === 'on_hold') {
             popupContent += `<div class="mt-2 bg-yellow-100 text-yellow-800 text-xs p-1 rounded border border-yellow-300"><i class="fas fa-exclamation-triangle"></i> Shipment On Hold</div>`;
          } else if (status === 'delivered') {
             popupContent += `<div class="mt-2 bg-green-100 text-green-800 text-xs p-1 rounded border border-green-300"><i class="fas fa-check-circle"></i> Successfully Delivered</div>`;
          }

          marker.setPopupContent(popupContent);
        })
        .catch(err => console.error('Error fetching tracking data:', err));
    }

    // Poll every 10 seconds
    setInterval(updateMap, 10000);
  });
</script>
<?php endif; ?>
<footer class="bg-white border-t mt-20 no-print">
  <div class="max-w-7xl mx-auto px-4 py-6 text-center text-sm text-slate-500">
    © 2026 RoutexShipping. All rights reserved.
  </div>
</footer>
</body>
</html>
