<?php
require_once __DIR__ . '/../helpers/auth.php';
require_role(['driver']);

$pdo = db();
$title = 'Driver App - IMS';
$user = current_user();

function h(?string $value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

$stmt = $pdo->prepare("\n    SELECT\n        d.id,\n        d.delivery_code,\n        d.status,\n        d.pickup_address,\n        d.dropoff_address,\n        d.scheduled_at,\n        c.name AS customer_name,\n        COALESCE(track.point_count, 0) AS point_count,\n        track.last_recorded_at\n    FROM deliveries d\n    LEFT JOIN customers c ON c.id = d.customer_id\n    LEFT JOIN (\n        SELECT delivery_id, COUNT(*) AS point_count, MAX(recorded_at) AS last_recorded_at\n        FROM delivery_locations\n        GROUP BY delivery_id\n    ) track ON track.delivery_id = d.id\n    WHERE d.assigned_driver_id = :driver_id\n      AND d.status <> 'CANCELLED'\n    ORDER BY\n      CASE d.status\n        WHEN 'IN_TRANSIT' THEN 1\n        WHEN 'PICKED_UP' THEN 2\n        WHEN 'ASSIGNED' THEN 3\n        WHEN 'PENDING' THEN 4\n        WHEN 'DELIVERED' THEN 5\n        ELSE 6\n      END,\n      COALESCE(d.scheduled_at, d.created_at) DESC,\n      d.id DESC\n");
$stmt->execute([':driver_id' => (int)($user['id'] ?? 0)]);
$deliveries = $stmt->fetchAll(PDO::FETCH_ASSOC);

$stats = [
    'assigned' => count($deliveries),
    'active' => 0,
    'delivered' => 0,
];
foreach ($deliveries as $deliveryRow) {
    $status = (string)$deliveryRow['status'];
    if (in_array($status, ['PICKED_UP', 'IN_TRANSIT'], true)) {
        $stats['active']++;
    }
    if ($status === 'DELIVERED') {
        $stats['delivered']++;
    }
}

require_once __DIR__ . '/../templates/header.php';
require_once __DIR__ . '/../templates/sidebar.php';
?>

<main class="col-12 col-lg-10 app-content">
  <div class="page-head">
    <div>
      <div class="page-kicker">Driver workspace</div>
      <h1 class="page-title">Driver app</h1>
      <p class="page-subtitle">Track your current route, push live GPS updates, change delivery status, open navigation, and submit proof of delivery without leaving the page.</p>
    </div>
    <div class="d-flex flex-wrap gap-2">
      <button class="btn btn-outline-secondary" id="btnOpenPod" type="button" disabled>Submit POD</button>
      <a class="btn btn-dark" href="driver_pod.php<?= !empty($deliveries) ? '?delivery_id=' . (int)$deliveries[0]['id'] : '' ?>">Standalone POD page</a>
    </div>
  </div>

  <div class="row g-3 mb-3">
    <div class="col-12 col-md-6 col-xl-3">
      <div class="stat-card">
        <div class="stat-label">Assigned deliveries</div>
        <div class="stat-value"><?= (int)$stats['assigned'] ?></div>
        <div class="stat-sub">All routes assigned to you</div>
      </div>
    </div>
    <div class="col-12 col-md-6 col-xl-3">
      <div class="stat-card">
        <div class="stat-label">Active routes</div>
        <div class="stat-value"><?= (int)$stats['active'] ?></div>
        <div class="stat-sub">Picked up or already in transit</div>
      </div>
    </div>
    <div class="col-12 col-md-6 col-xl-3">
      <div class="stat-card">
        <div class="stat-label">Delivered</div>
        <div class="stat-value"><?= (int)$stats['delivered'] ?></div>
        <div class="stat-sub">Completed routes assigned to you</div>
      </div>
    </div>
    <div class="col-12 col-md-6 col-xl-3">
      <div class="stat-card">
        <div class="stat-label">Tracking state</div>
        <div class="mt-2"><span class="status-pill status-neutral" id="trackingState">Idle</span></div>
        <div class="stat-sub" id="trackingDetail">Start tracking to send GPS points.</div>
      </div>
    </div>
  </div>

  <div class="row g-3">
    <div class="col-12 col-xl-4">
      <div class="card mb-3">
        <div class="card-body p-4">
          <h5 class="mb-3">Select delivery</h5>
          <select id="delivery_id" class="form-select mb-3">
            <option value="0">Choose a delivery</option>
            <?php foreach ($deliveries as $delivery): ?>
              <option value="<?= (int)$delivery['id'] ?>">
                <?= h($delivery['delivery_code']) ?> · <?= h((string)$delivery['status']) ?>
              </option>
            <?php endforeach; ?>
          </select>
          <div class="soft-panel">
            <div class="fw-semibold mb-2">Selected route</div>
            <div class="metric-inline"><span>Code</span><strong id="infoCode">-</strong></div>
            <div class="metric-inline"><span>Status</span><strong id="infoStatus">-</strong></div>
            <div class="metric-inline"><span>Customer</span><strong id="infoCustomer">-</strong></div>
            <div class="metric-inline"><span>Scheduled</span><strong id="infoScheduled">-</strong></div>
            <div class="metric-inline"><span>Latest GPS</span><strong id="infoGps">-</strong></div>
            <div class="metric-inline"><span>Coordinates</span><strong id="infoCoords">-</strong></div>
          </div>
          <div class="d-grid gap-2 mt-3">
            <button id="btnNavPickup" class="btn btn-outline-secondary" type="button" disabled>Navigate to pickup</button>
            <button id="btnNavDropoff" class="btn btn-outline-secondary" type="button" disabled>Navigate to dropoff</button>
            <button id="btnOpenRoute" class="btn btn-dark" type="button" disabled>Open route in Google Maps</button>
          </div>
        </div>
      </div>

      <div class="card mb-3">
        <div class="card-body p-4">
          <div class="d-flex justify-content-between align-items-start mb-3">
            <div>
              <h5 class="mb-1">Status actions</h5>
              <div class="text-muted small">Use the route stages below as you progress.</div>
            </div>
            <div id="statusMessage" class="text-muted small">-</div>
          </div>
          <div class="d-grid gap-2">
            <button id="btnPickedUp" class="btn btn-outline-primary" type="button" disabled>Mark picked up</button>
            <button id="btnInTransit" class="btn btn-outline-warning" type="button" disabled>Mark in transit</button>
            <button id="btnDelivered" class="btn btn-outline-success" type="button" disabled>Mark delivered</button>
          </div>
          <div class="soft-panel mt-3">
            <div class="small text-muted">Inventory for the delivery is released automatically once you successfully mark the route as <strong>DELIVERED</strong>.</div>
          </div>
        </div>
      </div>

      <div class="card">
        <div class="card-body p-4">
          <div class="d-flex justify-content-between align-items-start mb-3">
            <div>
              <h5 class="mb-1">Items and POD</h5>
              <div class="text-muted small">Every product on the selected delivery.</div>
            </div>
            <div class="small text-muted" id="proofSummary">No proof yet</div>
          </div>
          <div id="itemsBox" class="small text-muted">Select a delivery to see items.</div>
          <div class="soft-panel mt-3">
            <div class="fw-semibold mb-1">Notes</div>
            <div class="small" id="routeNotes">No notes.</div>
          </div>
        </div>
      </div>
    </div>

    <div class="col-12 col-xl-8">
      <div class="card map-panel mb-3">
        <div class="card-body p-4">
          <div class="d-flex flex-wrap justify-content-between align-items-start mb-3 gap-2">
            <div>
              <h5 class="mb-1">Live driver map</h5>
              <div class="text-muted small">Shows pickup, dropoff, your most recent trail, and the current position while tracking is active.</div>
            </div>
            <div class="form-check form-switch">
              <input class="form-check-input" type="checkbox" id="followDriver" checked>
              <label class="form-check-label" for="followDriver">Follow current location</label>
            </div>
          </div>
          <div id="driverMap" class="map-canvas" style="min-height: 420px;"></div>
        </div>
      </div>

      <div class="card">
        <div class="card-body p-4">
          <div class="row g-3">
            <div class="col-12 col-lg-6">
              <h5 class="mb-3">GPS tracking</h5>
              <div class="d-flex flex-wrap gap-2 mb-3">
                <button id="btnStart" class="btn btn-dark" type="button">Start tracking</button>
                <button id="btnStop" class="btn btn-outline-secondary" type="button" disabled>Stop tracking</button>
              </div>
              <div class="metric-inline"><span>Last sync</span><strong id="lastSent">-</strong></div>
              <div class="metric-inline"><span>Local coordinates</span><strong id="coords">-</strong></div>
              <div class="metric-inline"><span>Accuracy</span><strong id="coordsMeta">-</strong></div>
            </div>
            <div class="col-12 col-lg-6">
              <h5 class="mb-3">Route health</h5>
              <div class="metric-inline"><span>Points stored</span><strong id="routePoints">0</strong></div>
              <div class="metric-inline"><span>Next stop</span><strong id="nextStop">-</strong></div>
              <div class="metric-inline"><span>Inventory release</span><strong id="stockRelease">-</strong></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</main>

<div class="modal fade" id="podModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Proof of delivery</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="alert alert-warning small">POD is only accepted after the route is marked <strong>DELIVERED</strong>.</div>
        <div class="mb-3">
          <label class="form-label">Delivery photo (optional)</label>
          <input type="file" id="podPhoto" class="form-control" accept="image/*">
        </div>
        <div class="mb-3">
          <label class="form-label">Signature</label>
          <div class="border rounded p-2 bg-white">
            <canvas id="sigCanvas" width="900" height="260" style="width: 100%; height: auto; touch-action: none;"></canvas>
          </div>
          <div class="d-flex gap-2 mt-2">
            <button type="button" id="btnSigClear" class="btn btn-sm btn-outline-secondary">Clear</button>
          </div>
        </div>
        <div class="mb-3">
          <label class="form-label">Notes</label>
          <textarea id="podNotes" class="form-control" rows="3" placeholder="Receiver name, condition, remarks..."></textarea>
        </div>
        <div id="podMessage" class="small text-muted">-</div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" id="btnPodSubmit" class="btn btn-dark">Submit POD</button>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
const deliveries = <?= json_encode(array_map(static function (array $row): array {
    return [
        'id' => (int)$row['id'],
        'delivery_code' => (string)$row['delivery_code'],
        'status' => (string)$row['status'],
    ];
}, $deliveries), JSON_UNESCAPED_SLASHES) ?>;

const deliverySelect = document.getElementById('delivery_id');
const infoCode = document.getElementById('infoCode');
const infoStatus = document.getElementById('infoStatus');
const infoCustomer = document.getElementById('infoCustomer');
const infoScheduled = document.getElementById('infoScheduled');
const infoGps = document.getElementById('infoGps');
const infoCoords = document.getElementById('infoCoords');
const itemsBox = document.getElementById('itemsBox');
const routeNotes = document.getElementById('routeNotes');
const proofSummary = document.getElementById('proofSummary');
const statusMessage = document.getElementById('statusMessage');
const trackingState = document.getElementById('trackingState');
const trackingDetail = document.getElementById('trackingDetail');
const routePoints = document.getElementById('routePoints');
const nextStop = document.getElementById('nextStop');
const stockRelease = document.getElementById('stockRelease');
const lastSent = document.getElementById('lastSent');
const coords = document.getElementById('coords');
const coordsMeta = document.getElementById('coordsMeta');
const followDriver = document.getElementById('followDriver');

const btnStart = document.getElementById('btnStart');
const btnStop = document.getElementById('btnStop');
const btnPickedUp = document.getElementById('btnPickedUp');
const btnInTransit = document.getElementById('btnInTransit');
const btnDelivered = document.getElementById('btnDelivered');
const btnNavPickup = document.getElementById('btnNavPickup');
const btnNavDropoff = document.getElementById('btnNavDropoff');
const btnOpenRoute = document.getElementById('btnOpenRoute');
const btnOpenPod = document.getElementById('btnOpenPod');
const standalonePodLink = document.getElementById('standalonePodLink');

const podModal = new bootstrap.Modal(document.getElementById('podModal'));
const podPhoto = document.getElementById('podPhoto');
const sigCanvas = document.getElementById('sigCanvas');
const sigCtx = sigCanvas.getContext('2d');
const btnSigClear = document.getElementById('btnSigClear');
const podNotes = document.getElementById('podNotes');
const btnPodSubmit = document.getElementById('btnPodSubmit');
const podMessage = document.getElementById('podMessage');

let currentDelivery = null;
let refreshTimer = null;
let watchId = null;
let sendTimer = null;
let lastPosition = null;
let lastSentAt = 0;
let drawing = false;
let lastPoint = null;

const map = L.map('driverMap').setView([13.941, 121.615], 12);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  maxZoom: 19,
  attribution: '&copy; OpenStreetMap contributors'
}).addTo(map);

let pickupMarker = null;
let dropoffMarker = null;
let driverMarker = null;
let trailLine = null;
let firstFitDone = false;

function escapeHtml(value) {
  return String(value ?? '').replace(/[&<>"']/g, (char) => ({
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  }[char]));
}

function statusHtml(status) {
  const normalized = String(status || 'PENDING').toUpperCase().replace(/[^A-Z_]/g, '') || 'PENDING';
  return `<span class="status-pill status-${normalized}">${escapeHtml(normalized.replace(/_/g, ' '))}</span>`;
}

function setTrackingUi(label, detail, type = 'neutral') {
  trackingState.className = `status-pill status-${type}`;
  trackingState.textContent = label;
  trackingDetail.textContent = detail;
}

function selectedDeliveryId() {
  return Number(deliverySelect.value || 0);
}

function ensureMarker(existing, lat, lng, label) {
  if (lat === null || lng === null || Number.isNaN(Number(lat)) || Number.isNaN(Number(lng))) return existing;
  const latlng = [Number(lat), Number(lng)];
  if (!existing) {
    existing = L.marker(latlng).addTo(map).bindPopup(label);
  } else {
    existing.setLatLng(latlng);
  }
  return existing;
}

function fitMapIfNeeded() {
  if (firstFitDone) return;
  const bounds = [];
  if (pickupMarker) bounds.push(pickupMarker.getLatLng());
  if (dropoffMarker) bounds.push(dropoffMarker.getLatLng());
  if (driverMarker) bounds.push(driverMarker.getLatLng());
  if (bounds.length >= 2) {
    map.fitBounds(L.latLngBounds(bounds), { padding: [30, 30] });
    firstFitDone = true;
  } else if (bounds.length === 1) {
    map.setView(bounds[0], 15);
    firstFitDone = true;
  }
}

async function fetchJson(url, options = {}) {
  const response = await fetch(url, options);
  const text = await response.text();
  try {
    return JSON.parse(text);
  } catch (error) {
    throw new Error(text.substring(0, 180) || 'Invalid JSON response');
  }
}

function openGoogleMaps(address) {
  if (!address) return;
  window.open(`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(address)}`, '_blank');
}

function openGoogleRoute(origin, destination) {
  if (!origin || !destination) return;
  window.open(`https://www.google.com/maps/dir/?api=1&origin=${encodeURIComponent(origin)}&destination=${encodeURIComponent(destination)}&travelmode=driving`, '_blank');
}

function updateStatusButtons(status) {
  const normalized = String(status || '').toUpperCase();
  const hasDelivery = !!selectedDeliveryId();
  btnPickedUp.disabled = !hasDelivery || ['PICKED_UP', 'IN_TRANSIT', 'DELIVERED', 'CANCELLED'].includes(normalized);
  btnInTransit.disabled = !hasDelivery || ['IN_TRANSIT', 'DELIVERED', 'CANCELLED'].includes(normalized);
  btnDelivered.disabled = !hasDelivery || ['DELIVERED', 'CANCELLED'].includes(normalized);
}

function updateNavigationButtons(delivery) {
  const hasDelivery = !!delivery;
  btnNavPickup.disabled = !hasDelivery || !delivery.pickup_address;
  btnNavDropoff.disabled = !hasDelivery || !delivery.dropoff_address;
  btnOpenRoute.disabled = !hasDelivery || !delivery.pickup_address || !delivery.dropoff_address;
  btnOpenPod.disabled = !hasDelivery || delivery.status !== 'DELIVERED';
  if (hasDelivery) {
    standalonePodLink.href = `driver_pod.php?delivery_id=${encodeURIComponent(delivery.id)}`;
  }
}

function updateItems(items) {
  if (!items || !items.length) {
    itemsBox.innerHTML = '<div class="text-muted">No items on this delivery yet.</div>';
    return;
  }
  itemsBox.innerHTML = items.map((item) => {
    const code = item.barcode_value || item.sku;
    return `
      <div class="soft-panel mb-2">
        <div class="fw-semibold">${escapeHtml(item.name)}</div>
        <div class="small text-muted">Qty ${escapeHtml(item.quantity)}${item.unit ? ' · ' + escapeHtml(item.unit) : ''}</div>
        <div class="small text-muted">${escapeHtml(code)}</div>
      </div>
    `;
  }).join('');
}

function updateProofSummary(payload) {
  if (!payload.latest_proof) {
    proofSummary.textContent = payload.proof_count > 0 ? `${payload.proof_count} proof record(s)` : 'No proof yet';
    return;
  }
  proofSummary.textContent = `${payload.proof_count} proof record(s) · Latest ${payload.latest_proof.created_at || ''}`;
}

async function refreshSelectedDelivery() {
  const deliveryId = selectedDeliveryId();
  if (!deliveryId) {
    currentDelivery = null;
    infoCode.textContent = '-';
    infoStatus.textContent = '-';
    infoCustomer.textContent = '-';
    infoScheduled.textContent = '-';
    infoGps.textContent = '-';
    infoCoords.textContent = '-';
    routeNotes.textContent = 'No notes.';
    routePoints.textContent = '0';
    nextStop.textContent = '-';
    stockRelease.textContent = '-';
    itemsBox.innerHTML = '<div class="text-muted">Select a delivery to see items.</div>';
    proofSummary.textContent = 'No proof yet';
    updateStatusButtons('');
    updateNavigationButtons(null);
    if (pickupMarker) { map.removeLayer(pickupMarker); pickupMarker = null; }
    if (dropoffMarker) { map.removeLayer(dropoffMarker); dropoffMarker = null; }
    if (driverMarker) { map.removeLayer(driverMarker); driverMarker = null; }
    if (trailLine) { trailLine.setLatLngs([]); }
    return;
  }

  try {
    const [info, points] = await Promise.all([
      fetchJson(`driver_delivery_info.php?delivery_id=${encodeURIComponent(deliveryId)}`, {
        headers: { 'Accept': 'application/json' }
      }),
      fetchJson(`location_points.php?delivery_id=${encodeURIComponent(deliveryId)}&limit=120`, {
        headers: { 'Accept': 'application/json' }
      })
    ]);

    if (!info.ok) {
      throw new Error(info.error || 'Unable to load delivery');
    }

    currentDelivery = info.delivery;
    infoCode.textContent = info.delivery.delivery_code || '-';
    infoStatus.innerHTML = statusHtml(info.delivery.status || '-');
    infoCustomer.textContent = info.delivery.customer_name || 'No customer';
    infoScheduled.textContent = info.delivery.scheduled_at || 'Not scheduled';
    routeNotes.textContent = info.delivery.notes || 'No notes.';
    routePoints.textContent = String((info.route_stats && info.route_stats.point_count) || 0);
    nextStop.textContent = info.delivery.next_stop ? info.delivery.next_stop.replace(/^./, (ch) => ch.toUpperCase()) : 'Complete';
    stockRelease.textContent = info.delivery.stock_released ? 'Released' : 'Pending';

    if (info.last_gps) {
      infoGps.textContent = info.last_gps.recorded_at || '-';
      infoCoords.textContent = `${Number(info.last_gps.lat).toFixed(6)}, ${Number(info.last_gps.lng).toFixed(6)}`;
    } else {
      infoGps.textContent = 'No GPS yet';
      infoCoords.textContent = '-';
    }

    updateItems(info.items || []);
    updateProofSummary(info);
    updateStatusButtons(info.delivery.status || '');
    updateNavigationButtons(info.delivery);

    if (info.delivery.pickup_lat !== null && info.delivery.pickup_lng !== null) {
      pickupMarker = ensureMarker(pickupMarker, info.delivery.pickup_lat, info.delivery.pickup_lng, 'Pickup');
    } else if (pickupMarker) {
      map.removeLayer(pickupMarker);
      pickupMarker = null;
    }
    if (info.delivery.dropoff_lat !== null && info.delivery.dropoff_lng !== null) {
      dropoffMarker = ensureMarker(dropoffMarker, info.delivery.dropoff_lat, info.delivery.dropoff_lng, 'Dropoff');
    } else if (dropoffMarker) {
      map.removeLayer(dropoffMarker);
      dropoffMarker = null;
    }
    if (info.last_gps) {
      driverMarker = ensureMarker(driverMarker, info.last_gps.lat, info.last_gps.lng, 'Driver');
      if (followDriver.checked && driverMarker) {
        map.setView(driverMarker.getLatLng(), Math.max(map.getZoom(), 15));
      }
    } else if (driverMarker) {
      map.removeLayer(driverMarker);
      driverMarker = null;
    }

    if (points.ok && Array.isArray(points.points) && points.points.length > 1) {
      const line = points.points.map((point) => [Number(point.lat), Number(point.lng)]);
      if (!trailLine) {
        trailLine = L.polyline(line).addTo(map);
      } else {
        trailLine.setLatLngs(line);
      }
    } else if (trailLine) {
      trailLine.setLatLngs([]);
    }

    fitMapIfNeeded();
  } catch (error) {
    statusMessage.textContent = error.message;
  }
}

async function updateDeliveryStatus(status) {
  const deliveryId = selectedDeliveryId();
  if (!deliveryId) {
    statusMessage.textContent = 'Select a delivery first.';
    return;
  }

  statusMessage.textContent = 'Saving status...';
  try {
    const response = await fetchJson('driver_delivery_status.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({ delivery_id: deliveryId, status })
    });

    if (!response.ok) {
      throw new Error(response.error || 'Unable to update status');
    }

    statusMessage.textContent = `Updated to ${response.status}.`;
    await refreshSelectedDelivery();
  } catch (error) {
    statusMessage.textContent = error.message;
  }
}

async function sendLatestPosition(force = false) {
  const deliveryId = selectedDeliveryId();
  if (!deliveryId || !lastPosition) {
    return;
  }
  const now = Date.now();
  if (!force && (now - lastSentAt) < 8000) {
    return;
  }

  const coordsData = lastPosition.coords;
  lastSentAt = now;

  try {
    const response = await fetchJson('location_update.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({
        delivery_id: deliveryId,
        lat: coordsData.latitude,
        lng: coordsData.longitude,
        accuracy_m: coordsData.accuracy ?? null,
        speed_mps: coordsData.speed ?? null,
        heading_deg: coordsData.heading ?? null
      })
    });

    if (!response.ok) {
      throw new Error(response.error || 'Failed to save GPS');
    }

    lastSent.textContent = response.saved_at || new Date().toLocaleString();
    if (response.point_count !== undefined) {
      routePoints.textContent = String(response.point_count);
    }
    setTrackingUi('Running', 'GPS updates are being sent successfully.', 'ok');
    refreshSelectedDelivery();
  } catch (error) {
    setTrackingUi('Warning', error.message, 'low');
  }
}

function handlePosition(position) {
  lastPosition = position;
  const latitude = Number(position.coords.latitude);
  const longitude = Number(position.coords.longitude);
  const accuracy = position.coords.accuracy !== null ? `${Math.round(position.coords.accuracy)} m` : 'n/a';
  const speed = position.coords.speed !== null ? `${Number(position.coords.speed).toFixed(1)} m/s` : 'n/a';
  coords.textContent = `${latitude.toFixed(6)}, ${longitude.toFixed(6)}`;
  coordsMeta.textContent = `${accuracy} · ${speed}`;
  driverMarker = ensureMarker(driverMarker, latitude, longitude, 'Driver');
  if (followDriver.checked && driverMarker) {
    map.setView(driverMarker.getLatLng(), Math.max(map.getZoom(), 15));
  }
  sendLatestPosition(false);
}

function startTracking() {
  const deliveryId = selectedDeliveryId();
  if (!deliveryId) {
    setTrackingUi('Idle', 'Select a delivery before starting tracking.', 'neutral');
    return;
  }
  if (!('geolocation' in navigator)) {
    setTrackingUi('Unavailable', 'This browser does not support geolocation.', 'low');
    return;
  }
  if (watchId !== null) {
    return;
  }

  watchId = navigator.geolocation.watchPosition(handlePosition, (error) => {
    setTrackingUi('Warning', error.message || 'GPS permission denied.', 'low');
  }, {
    enableHighAccuracy: true,
    maximumAge: 5000,
    timeout: 20000
  });

  sendTimer = window.setInterval(() => sendLatestPosition(true), 12000);
  btnStart.disabled = true;
  btnStop.disabled = false;
  setTrackingUi('Starting', 'Waiting for your device to provide a location fix.', 'neutral');
}

function stopTracking() {
  if (watchId !== null) {
    navigator.geolocation.clearWatch(watchId);
    watchId = null;
  }
  if (sendTimer !== null) {
    window.clearInterval(sendTimer);
    sendTimer = null;
  }
  btnStart.disabled = false;
  btnStop.disabled = true;
  setTrackingUi('Idle', 'Tracking is stopped.', 'neutral');
}

function resetCanvas() {
  sigCtx.fillStyle = '#ffffff';
  sigCtx.fillRect(0, 0, sigCanvas.width, sigCanvas.height);
  sigCtx.lineWidth = 2;
  sigCtx.lineCap = 'round';
  sigCtx.strokeStyle = '#111827';
}

function canvasPoint(event) {
  const rect = sigCanvas.getBoundingClientRect();
  const source = event.touches ? event.touches[0] : event;
  return {
    x: source.clientX - rect.left,
    y: source.clientY - rect.top,
  };
}

function beginDraw(event) {
  drawing = true;
  lastPoint = canvasPoint(event);
}

function drawMove(event) {
  if (!drawing) return;
  event.preventDefault();
  const point = canvasPoint(event);
  sigCtx.beginPath();
  sigCtx.moveTo(lastPoint.x, lastPoint.y);
  sigCtx.lineTo(point.x, point.y);
  sigCtx.stroke();
  lastPoint = point;
}

function endDraw() {
  drawing = false;
  lastPoint = null;
}

sigCanvas.addEventListener('mousedown', beginDraw);
sigCanvas.addEventListener('mousemove', drawMove);
sigCanvas.addEventListener('mouseup', endDraw);
sigCanvas.addEventListener('mouseleave', endDraw);
sigCanvas.addEventListener('touchstart', beginDraw, { passive: false });
sigCanvas.addEventListener('touchmove', drawMove, { passive: false });
sigCanvas.addEventListener('touchend', endDraw);
btnSigClear.addEventListener('click', resetCanvas);
resetCanvas();

btnOpenPod.addEventListener('click', () => {
  if (!currentDelivery || currentDelivery.status !== 'DELIVERED') {
    statusMessage.textContent = 'Mark the route as delivered before submitting proof.';
    return;
  }
  podMessage.textContent = 'Ready to submit proof.';
  podModal.show();
});

btnPodSubmit.addEventListener('click', async () => {
  const deliveryId = selectedDeliveryId();
  if (!deliveryId || !currentDelivery || currentDelivery.status !== 'DELIVERED') {
    podMessage.textContent = 'Select a delivered route first.';
    return;
  }

  const form = new FormData();
  form.append('delivery_id', String(deliveryId));
  form.append('notes', podNotes.value || '');
  form.append('signature_data', sigCanvas.toDataURL('image/png'));
  if (podPhoto.files[0]) {
    form.append('photo', podPhoto.files[0]);
  }

  podMessage.textContent = 'Submitting proof...';
  try {
    const response = await fetchJson('../api/delivery_proof_submit.php', {
      method: 'POST',
      body: form,
      headers: { 'Accept': 'application/json' }
    });
    if (!response.ok) {
      throw new Error(response.error || 'Failed to submit proof');
    }
    podMessage.textContent = response.message || 'Proof saved.';
    podNotes.value = '';
    podPhoto.value = '';
    resetCanvas();
    await refreshSelectedDelivery();
  } catch (error) {
    podMessage.textContent = error.message;
  }
});

btnNavPickup.addEventListener('click', () => currentDelivery && openGoogleMaps(currentDelivery.pickup_address));
btnNavDropoff.addEventListener('click', () => currentDelivery && openGoogleMaps(currentDelivery.dropoff_address));
btnOpenRoute.addEventListener('click', () => currentDelivery && openGoogleRoute(currentDelivery.pickup_address, currentDelivery.dropoff_address));
btnPickedUp.addEventListener('click', () => updateDeliveryStatus('PICKED_UP'));
btnInTransit.addEventListener('click', () => updateDeliveryStatus('IN_TRANSIT'));
btnDelivered.addEventListener('click', () => updateDeliveryStatus('DELIVERED'));
btnStart.addEventListener('click', startTracking);
btnStop.addEventListener('click', stopTracking);

deliverySelect.addEventListener('change', () => {
  localStorage.setItem('ims_driver_delivery_id', String(selectedDeliveryId()));
  statusMessage.textContent = '-';
  firstFitDone = false;
  if (pickupMarker) { map.removeLayer(pickupMarker); pickupMarker = null; }
  if (dropoffMarker) { map.removeLayer(dropoffMarker); dropoffMarker = null; }
  if (driverMarker) { map.removeLayer(driverMarker); driverMarker = null; }
  if (trailLine) {
    trailLine.setLatLngs([]);
  }
  if (watchId !== null) {
    stopTracking();
  }
  refreshSelectedDelivery();
  if (refreshTimer !== null) {
    window.clearInterval(refreshTimer);
  }
  refreshTimer = window.setInterval(refreshSelectedDelivery, 8000);
});

const rememberedDeliveryId = Number(localStorage.getItem('ims_driver_delivery_id') || 0);
if (deliveries.some((item) => item.id === rememberedDeliveryId)) {
  deliverySelect.value = String(rememberedDeliveryId);
} else if (deliveries.length > 0) {
  const preferred = deliveries.find((item) => item.status !== 'DELIVERED') || deliveries[0];
  deliverySelect.value = String(preferred.id);
}

refreshSelectedDelivery();
refreshTimer = window.setInterval(refreshSelectedDelivery, 8000);
</script>

<?php require_once __DIR__ . '/../templates/footer.php'; ?>
