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

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

// Load deliveries assigned to driver (not closed)
$stmt = $pdo->prepare("
  SELECT id, delivery_code, status, pickup_address, dropoff_address
  FROM deliveries
  WHERE assigned_driver_id = :uid
    AND status NOT IN ('CANCELLED')
  ORDER BY created_at DESC
");
$stmt->execute([':uid' => (int)$user['id']]);
$deliveries = $stmt->fetchAll();

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

<main class="col-12 col-md-9 col-lg-10 p-3 p-md-4">
  <h4 class="mb-3">Driver App</h4>

  <div class="alert alert-info">
    Choose a delivery and press <b>Start Tracking</b>. Keep this page open while driving.
  </div>

  <div class="card shadow-sm">
    <div class="card-body">

      <div class="mb-2">
        <label class="form-label">Your Assigned Deliveries</label>
        <select id="delivery_id" class="form-select">
          <option value="0">-- Select delivery --</option>
          <?php foreach ($deliveries as $d): ?>
            <option value="<?= (int)$d['id'] ?>">
              <?= htmlspecialchars($d['delivery_code']) ?> (<?= htmlspecialchars($d['status']) ?>)
            </option>
          <?php endforeach; ?>
        </select>
        <div class="form-text">
          If you don’t see anything, staff/admin has not assigned you yet.
        </div>
      </div>

      <div class="d-flex gap-2 mb-3">
        <button id="btnStart" class="btn btn-success" type="button">Start Tracking</button>
        <button id="btnStop" class="btn btn-secondary" type="button" disabled>Stop</button>
      </div>

      <hr>

      <div class="mb-2"><b>Current Status:</b> <span id="curStatus">-</span></div>

      <div class="d-flex flex-wrap gap-2 mb-2">
        <button id="btnPickedUp" class="btn btn-outline-primary" type="button">Picked Up</button>
        <button id="btnInTransit" class="btn btn-outline-warning" type="button">In Transit</button>
        <button id="btnDelivered" class="btn btn-outline-success" type="button">Delivered</button>
      </div>

      <div class="small text-muted mb-3" id="statusUpdateMsg">-</div>

      <div class="card border-0 bg-light">
        <div class="card-body p-3">
          <div class="fw-semibold mb-2">Delivery Details</div>

          <div class="small text-muted">Code</div>
          <div id="infoCode" class="mb-2">-</div>

          <div class="small text-muted">Status</div>
          <div id="infoStatus" class="mb-2">-</div>

          <div class="small text-muted">Pickup</div>
          <div id="infoPickup" class="mb-2">-</div>
          <button id="btnNavPickup" type="button" class="btn btn-sm btn-outline-primary mb-3" disabled>
            Navigate to Pickup
          </button>

          <div class="small text-muted">Dropoff</div>
          <div id="infoDropoff" class="mb-2">-</div>
          <button id="btnNavDropoff" type="button" class="btn btn-sm btn-outline-success mb-2" disabled>
            Navigate to Dropoff
          </button>

          <button id="btnOpenRoute" type="button" class="btn btn-sm btn-primary mb-2" disabled>
            Open Route (Pickup → Dropoff)
          </button>

          <div class="small text-muted mt-2">Last GPS Saved</div>
          <div id="infoGps" class="mb-0">-</div>

          <hr class="my-2">
          <div class="fw-semibold mb-2">Items to Deliver</div>
          <div id="itemsBox" class="small text-muted">Select a delivery to view items.</div>

          <a id="btnPOD" class="btn btn-outline-primary btn-sm mt-2 d-none" href="#">Submit Proof of Delivery</a>


          <hr class="my-2">
          <div class="d-flex flex-wrap gap-2 align-items-center">
            <div class="fw-semibold">Proof of Delivery</div>
            <button id="btnOpenPod" type="button" class="btn btn-sm btn-dark ms-auto" disabled>
              Submit POD
            </button>
          </div>
          <div id="podBox" class="small text-muted mt-2">No proof submitted yet.</div>
        </div>
      </div>

      <hr>

      <div class="small text-muted">Tracking Status</div>
      <div id="status" class="fw-semibold">Idle</div>

      <div class="mt-3">
        <div class="small text-muted">Last Sent</div>
        <div id="lastSent">-</div>
      </div>

      <div class="mt-3">
        <div class="small text-muted">Last Coordinates</div>
        <div id="coords">-</div>
      </div>

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

<!-- POD Modal -->
<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 (POD)</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 submission is allowed after the delivery is marked <b>DELIVERED</b>.
        </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 (draw below)</label>
          <div class="border rounded p-2 bg-white">
            <canvas id="sigCanvas" width="800" height="250" 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 class="form-text">Use mouse or finger to sign.</div>
        </div>

        <div class="mb-3">
          <label class="form-label">Notes (optional)</label>
          <textarea id="podNotes" class="form-control" rows="3" placeholder="Receiver name, remarks, etc."></textarea>
        </div>

        <div id="podMsg" class="small text-muted">-</div>

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" id="btnPodSubmit" class="btn btn-primary">Submit POD</button>
      </div>
    </div>
  </div>
</div>

<script>
let watchId = null;
let intervalId = null;

const statusEl = document.getElementById('status');
const lastSentEl = document.getElementById('lastSent');
const coordsEl = document.getElementById('coords');
const deliverySelect = document.getElementById('delivery_id');
const itemsBox = document.getElementById('itemsBox');

const btnStart = document.getElementById('btnStart');
const btnStop = document.getElementById('btnStop');

const curStatusEl = document.getElementById('curStatus');
const statusMsgEl = document.getElementById('statusUpdateMsg');
const btnPickedUp = document.getElementById('btnPickedUp');
const btnInTransit = document.getElementById('btnInTransit');
const btnDelivered = document.getElementById('btnDelivered');

const infoCodeEl = document.getElementById('infoCode');
const infoStatusEl = document.getElementById('infoStatus');
const infoPickupEl = document.getElementById('infoPickup');
const infoDropoffEl = document.getElementById('infoDropoff');
const infoGpsEl = document.getElementById('infoGps');

const btnNavPickup = document.getElementById('btnNavPickup');
const btnNavDropoff = document.getElementById('btnNavDropoff');
const btnOpenRoute = document.getElementById('btnOpenRoute');

const btnOpenPod = document.getElementById('btnOpenPod');
const podBox = document.getElementById('podBox');

const podModalEl = document.getElementById('podModal');
const podPhoto = document.getElementById('podPhoto');
const sigCanvas = document.getElementById('sigCanvas');
const btnSigClear = document.getElementById('btnSigClear');
const podNotes = document.getElementById('podNotes');
const btnPodSubmit = document.getElementById('btnPodSubmit');
const podMsg = document.getElementById('podMsg');

let infoTimer = null;
let podModal = null;

function setStatus(msg) { statusEl.textContent = msg; }
function setStatusMsg(msg) { statusMsgEl.textContent = msg; }

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

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

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

// Signature drawing
const ctx = sigCanvas.getContext('2d');
ctx.lineWidth = 3;
ctx.lineCap = 'round';
let drawing = false;

function getPos(e) {
  const rect = sigCanvas.getBoundingClientRect();
  const x = (e.clientX - rect.left) * (sigCanvas.width / rect.width);
  const y = (e.clientY - rect.top) * (sigCanvas.height / rect.height);
  return {x, y};
}

function startDraw(e) {
  drawing = true;
  const p = getPos(e);
  ctx.beginPath();
  ctx.moveTo(p.x, p.y);
}

function moveDraw(e) {
  if (!drawing) return;
  const p = getPos(e);
  ctx.lineTo(p.x, p.y);
  ctx.stroke();
}

function endDraw() { drawing = false; }

sigCanvas.addEventListener('pointerdown', (e) => { e.preventDefault(); startDraw(e); });
sigCanvas.addEventListener('pointermove', (e) => { e.preventDefault(); moveDraw(e); });
sigCanvas.addEventListener('pointerup', (e) => { e.preventDefault(); endDraw(); });
sigCanvas.addEventListener('pointercancel', endDraw);

btnSigClear.addEventListener('click', () => {
  ctx.clearRect(0, 0, sigCanvas.width, sigCanvas.height);
});

async function updateDeliveryStatus(deliveryId, newStatus) {
  if (!deliveryId || deliveryId === "0") {
    alert("Select a delivery first.");
    return;
  }
  try {
    const res = await fetch('../api/driver_delivery_status.php', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({ delivery_id: Number(deliveryId), status: newStatus })
    });
    const data = await res.json();
    if (!data.ok) {
      setStatusMsg('Error: ' + (data.error || 'Unknown'));
      return;
    }
    curStatusEl.textContent = data.status;
    setStatusMsg(`Updated to ${data.status} at ${data.updated_at}`);
    refreshDeliveryInfo();
  } catch (e) {
    setStatusMsg('Network error: ' + e.message);
  }
}

async function loadPodList(deliveryId) {
  try {
    const res = await fetch(`../api/driver_pod_list.php?delivery_id=${deliveryId}`);
    const data = await res.json();
    if (!data.ok) {
      podBox.classList.add('text-muted');
      podBox.textContent = 'Unable to load POD.';
      return;
    }

    const arr = Array.isArray(data.items) ? data.items : [];
    if (arr.length === 0) {
      podBox.classList.add('text-muted');
      podBox.textContent = 'No proof submitted yet.';
      return;
    }

    const btnPOD = document.getElementById('btnPOD');

    if (btnPOD) {
      btnPOD.href = `driver_pod.php?delivery_id=${Number(deliveryId)}`;
      btnPOD.classList.remove('d-none');
    }


    let html = '';
    for (const p of arr) {
      html += `<div class="border rounded p-2 mb-2 bg-white">
        <div class="small text-muted">Submitted by: ${escapeHtml(p.driver_name || '')} — ${escapeHtml(p.created_at || '')}</div>
        ${p.photo_path ? `<div class="mt-2"><img src="../${escapeHtml(p.photo_path)}" class="img-fluid rounded"></div>` : ''}
        ${p.signature_path ? `<div class="mt-2"><img src="../${escapeHtml(p.signature_path)}" class="img-fluid rounded" style="max-height:160px;"></div>` : ''}
        ${p.notes ? `<div class="mt-2"><b>Notes:</b> ${escapeHtml(p.notes)}</div>` : ''}
      </div>`;
    }
    podBox.classList.remove('text-muted');
    podBox.innerHTML = html;

  } catch (e) {
    podBox.classList.add('text-muted');
    podBox.textContent = 'Network error loading POD.';
  }
}

async function refreshDeliveryInfo() {
  const deliveryId = deliverySelect.value;
  if (!deliveryId || deliveryId === "0") return;

  try {
    const res = await fetch(`../api/driver_delivery_info.php?delivery_id=${deliveryId}`);
    const data = await res.json();

    if (!data.ok) {
      infoCodeEl.textContent = '-';
      infoStatusEl.textContent = 'Error: ' + (data.error || 'Unknown');
      infoPickupEl.textContent = '-';
      infoDropoffEl.textContent = '-';
      infoGpsEl.textContent = '-';
      itemsBox.classList.add('text-muted');
      itemsBox.textContent = 'Error loading items.';
      btnNavPickup.disabled = true;
      btnNavDropoff.disabled = true;
      btnOpenRoute.disabled = true;
      btnOpenPod.disabled = true;
      return;
    }

    infoCodeEl.textContent = data.delivery.delivery_code || '-';
    infoStatusEl.textContent = data.delivery.status || '-';
    infoPickupEl.textContent = data.delivery.pickup_address || '-';
    infoDropoffEl.textContent = data.delivery.dropoff_address || '-';
    curStatusEl.textContent = data.delivery.status || '-';

    const pickup = (data.delivery.pickup_address || '').trim();
    const dropoff = (data.delivery.dropoff_address || '').trim();

    btnNavPickup.disabled = pickup === '';
    btnNavDropoff.disabled = dropoff === '';
    btnOpenRoute.disabled = (pickup === '' || dropoff === '');

    btnNavPickup.onclick = () => openGoogleMaps(pickup);
    btnNavDropoff.onclick = () => openGoogleMaps(dropoff);
    btnOpenRoute.onclick = () => openGoogleRoute(pickup, dropoff);

    if (data.last_gps) {
      infoGpsEl.textContent = `${data.last_gps.recorded_at} (${Number(data.last_gps.lat).toFixed(5)}, ${Number(data.last_gps.lng).toFixed(5)})`;
    } else {
      infoGpsEl.textContent = 'No GPS saved yet';
    }

    // Render items
    const arr = Array.isArray(data.items) ? data.items : [];

    if (arr.length > 0) {
      let html = '<div class="table-responsive"><table class="table table-sm mb-0">';
      html += '<thead><tr><th>SKU</th><th>Product</th><th class="text-end">Qty</th></tr></thead><tbody>';

      for (const it of arr) {
        html += `<tr>
          <td>${escapeHtml(it.sku || '')}</td>
          <td>${escapeHtml(it.name || '')}</td>
          <td class="text-end fw-semibold">${Number(it.quantity || 0)}</td>
        </tr>`;
      }

      html += '</tbody></table></div>';
      itemsBox.classList.remove('text-muted');
      itemsBox.innerHTML = html;
    } else {
      itemsBox.classList.add('text-muted');
      itemsBox.textContent = 'No items added yet for this delivery.';
    }

    // POD button only after delivered
    const st = (data.delivery.status || '');
    btnOpenPod.disabled = (st !== 'DELIVERED');

    // load pod list
    loadPodList(deliveryId);

  } catch (e) {
    infoStatusEl.textContent = 'Network error: ' + e.message;
    itemsBox.classList.add('text-muted');
    itemsBox.textContent = 'Network error loading items.';
    btnNavPickup.disabled = true;
    btnNavDropoff.disabled = true;
    btnOpenRoute.disabled = true;
    btnOpenPod.disabled = true;
  }
}

btnPickedUp.addEventListener('click', () => updateDeliveryStatus(deliverySelect.value, 'PICKED_UP'));
btnInTransit.addEventListener('click', () => updateDeliveryStatus(deliverySelect.value, 'IN_TRANSIT'));
btnDelivered.addEventListener('click', () => updateDeliveryStatus(deliverySelect.value, 'DELIVERED'));

async function sendLocation(deliveryId, pos) {
  const payload = {
    delivery_id: Number(deliveryId),
    lat: pos.coords.latitude,
    lng: pos.coords.longitude,
    accuracy_m: pos.coords.accuracy ?? null,
    speed_mps: pos.coords.speed ?? null,
    heading_deg: pos.coords.heading ?? null
  };

  coordsEl.textContent = `${payload.lat.toFixed(6)}, ${payload.lng.toFixed(6)} (±${Math.round(payload.accuracy_m || 0)}m)`;

  try {
    const res = await fetch('../api/location_update.php', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify(payload)
    });
    const data = await res.json();

    if (!data.ok) {
      setStatus('Error: ' + (data.error || 'Unknown'));
      return;
    }
    lastSentEl.textContent = data.saved_at || new Date().toLocaleString();
    setStatus('Tracking... sending updates');
  } catch (e) {
    setStatus('Network error: ' + e.message);
  }
}

btnStart.addEventListener('click', () => {
  const deliveryId = deliverySelect.value;

  if (!deliveryId || deliveryId === "0") {
    alert("Please select a delivery.");
    return;
  }
  if (!navigator.geolocation) {
    alert("Geolocation is not supported on this device.");
    return;
  }

  btnStart.disabled = true;
  btnStop.disabled = false;
  deliverySelect.disabled = true;

  setStatus('Requesting GPS permission...');

  watchId = navigator.geolocation.watchPosition(
    (pos) => sendLocation(deliveryId, pos),
    (err) => setStatus('GPS error: ' + err.message),
    { enableHighAccuracy: true, maximumAge: 2000, timeout: 10000 }
  );

  intervalId = setInterval(() => {
    navigator.geolocation.getCurrentPosition(
      (pos) => sendLocation(deliveryId, pos),
      (err) => setStatus('GPS error: ' + err.message),
      { enableHighAccuracy: true, maximumAge: 2000, timeout: 10000 }
    );
  }, 10000);

  setStatus('Tracking started...');
});

btnStop.addEventListener('click', () => {
  if (watchId !== null) navigator.geolocation.clearWatch(watchId);
  if (intervalId !== null) clearInterval(intervalId);

  watchId = null;
  intervalId = null;

  btnStart.disabled = false;
  btnStop.disabled = true;
  deliverySelect.disabled = false;

  setStatus('Stopped');
});

// POD modal open
btnOpenPod.addEventListener('click', () => {
  podMsg.textContent = '-';
  podPhoto.value = '';
  podNotes.value = '';
  ctx.clearRect(0, 0, sigCanvas.width, sigCanvas.height);

  if (!podModal) {
    podModal = new bootstrap.Modal(podModalEl);
  }
  podModal.show();
});

// Submit POD
btnPodSubmit.addEventListener('click', async () => {
  const deliveryId = deliverySelect.value;
  if (!deliveryId || deliveryId === "0") {
    podMsg.textContent = 'Select a delivery first.';
    return;
  }

  const sigData = sigCanvas.toDataURL('image/png');

  const fd = new FormData();
  fd.append('delivery_id', String(deliveryId));
  fd.append('notes', podNotes.value || '');
  fd.append('signature_data', sigData);

  if (podPhoto.files && podPhoto.files[0]) {
    fd.append('photo', podPhoto.files[0]);
  }

  btnPodSubmit.disabled = true;
  podMsg.textContent = 'Uploading...';

  try {
    const res = await fetch('../api/driver_pod_upload.php', {
      method: 'POST',
      body: fd
    });
    const data = await res.json();

    if (!data.ok) {
      podMsg.textContent = 'Error: ' + (data.error || 'Unknown');
      btnPodSubmit.disabled = false;
      return;
    }

    podMsg.textContent = 'POD submitted successfully.';
    await loadPodList(deliveryId);
    btnPodSubmit.disabled = false;
    setTimeout(() => { if (podModal) podModal.hide(); }, 700);

  } catch (e) {
    podMsg.textContent = 'Network error: ' + e.message;
    btnPodSubmit.disabled = false;
  }
});

// Nice UX: when driver selects a delivery, reset UI
deliverySelect.addEventListener('change', () => {
  curStatusEl.textContent = '-';
  setStatusMsg('-');

  infoCodeEl.textContent = '-';
  infoStatusEl.textContent = '-';
  infoPickupEl.textContent = '-';
  infoDropoffEl.textContent = '-';
  infoGpsEl.textContent = '-';

  itemsBox.classList.add('text-muted');
  itemsBox.textContent = 'Loading items...';

  podBox.classList.add('text-muted');
  podBox.textContent = 'Loading POD...';

  btnNavPickup.disabled = true;
  btnNavDropoff.disabled = true;
  btnOpenRoute.disabled = true;
  btnOpenPod.disabled = true;

  if (infoTimer) clearInterval(infoTimer);
  infoTimer = null;

  if (deliverySelect.value !== "0") {
    refreshDeliveryInfo();
    infoTimer = setInterval(refreshDeliveryInfo, 5000);
  } else {
    itemsBox.textContent = 'Select a delivery to view items.';
    podBox.textContent = 'Select a delivery to view POD.';
  }
});
</script>

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