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

$pdo = db();
$user = current_user();
$title = "Submit Proof of Delivery - IMS";

$delivery_id = (int)($_GET['delivery_id'] ?? 0);
if ($delivery_id <= 0) {
  die("Invalid delivery.");
}

// verify assigned
$chk = $pdo->prepare("SELECT id, delivery_code FROM deliveries WHERE id = :id AND assigned_driver_id = :uid LIMIT 1");
$chk->execute([':id' => $delivery_id, ':uid' => (int)$user['id']]);
$delivery = $chk->fetch(PDO::FETCH_ASSOC);
if (!$delivery) {
  http_response_code(404);
  die("Delivery not found or not assigned to you.");
}

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">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <div>
      <h4 class="mb-0">Submit Proof of Delivery</h4>
      <div class="text-muted small">Delivery: <?= htmlspecialchars($delivery['delivery_code']) ?></div>
    </div>
    <a class="btn btn-outline-secondary btn-sm" href="driver_app.php">Back</a>
  </div>

  <div class="card shadow-sm">
    <div class="card-body">
      <div id="msg" class="alert d-none"></div>

      <form id="podForm" enctype="multipart/form-data">
        <input type="hidden" name="delivery_id" value="<?= (int)$delivery_id ?>">
        <input type="hidden" name="signature_data" id="signature_data">

        <div class="mb-3">
          <label class="form-label">Photo (optional but recommended)</label>
          <input class="form-control" type="file" name="photo" accept="image/*">
        </div>

        <div class="mb-2">
          <label class="form-label">Signature (required)</label>
          <div class="border rounded p-2 bg-light">
            <canvas id="sigCanvas" height="180" style="width:100%;"></canvas>
          </div>
          <div class="d-flex gap-2 mt-2">
            <button type="button" id="btnClear" class="btn btn-outline-secondary btn-sm">Clear</button>
          </div>
          <div class="form-text">Sign inside the box. Use mouse/finger.</div>
        </div>

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

        <button class="btn btn-primary w-100" type="submit">Submit Proof</button>
      </form>
    </div>
  </div>
</main>

<script>
const canvas = document.getElementById('sigCanvas');
const ctx = canvas.getContext('2d');
let drawing = false;
let last = null;

function fitCanvas() {
  const rect = canvas.getBoundingClientRect();
  const ratio = window.devicePixelRatio || 1;
  canvas.width = Math.floor(rect.width * ratio);
  canvas.height = Math.floor(180 * ratio);
  ctx.scale(ratio, ratio);
  ctx.lineWidth = 2;
  ctx.lineCap = 'round';
}
fitCanvas();
window.addEventListener('resize', () => location.reload()); // simplest safe way

function pos(e) {
  const r = canvas.getBoundingClientRect();
  const x = (e.touches ? e.touches[0].clientX : e.clientX) - r.left;
  const y = (e.touches ? e.touches[0].clientY : e.clientY) - r.top;
  return {x, y};
}

function start(e){ drawing=true; last=pos(e); }
function move(e){
  if(!drawing) return;
  e.preventDefault();
  const p = pos(e);
  ctx.beginPath();
  ctx.moveTo(last.x, last.y);
  ctx.lineTo(p.x, p.y);
  ctx.stroke();
  last = p;
}
function end(){ drawing=false; last=null; }

canvas.addEventListener('mousedown', start);
canvas.addEventListener('mousemove', move);
canvas.addEventListener('mouseup', end);
canvas.addEventListener('mouseleave', end);

canvas.addEventListener('touchstart', start, {passive:false});
canvas.addEventListener('touchmove', move, {passive:false});
canvas.addEventListener('touchend', end);

document.getElementById('btnClear').addEventListener('click', () => {
  ctx.clearRect(0,0,canvas.width,canvas.height);
});

function showMsg(type, text){
  const box = document.getElementById('msg');
  box.className = 'alert alert-' + type;
  box.textContent = text;
  box.classList.remove('d-none');
}

document.getElementById('podForm').addEventListener('submit', async (e) => {
  e.preventDefault();

  // export signature
  const dataUrl = canvas.toDataURL('image/png');
  document.getElementById('signature_data').value = dataUrl;

  const form = new FormData(e.target);

  try {
    const res = await fetch('../api/delivery_proof_submit.php', {
      method: 'POST',
      body: form
    });
    const data = await res.json();
    if(!data.ok){
      showMsg('danger', data.error || 'Failed to submit proof.');
      return;
    }
    showMsg('success', data.message || 'Proof saved!');
  } catch (err) {
    showMsg('danger', 'Network error: ' + err.message);
  }
});
</script>

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