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

header('Content-Type: application/json');

$pdo = db();
$user = current_user();

function json_fail($msg, $code = 400) {
  http_response_code($code);
  echo json_encode(['ok' => false, 'error' => $msg]);
  exit;
}

$delivery_id = (int)($_POST['delivery_id'] ?? 0);
$notes = trim((string)($_POST['notes'] ?? ''));
$signature_data = (string)($_POST['signature_data'] ?? ''); // base64 png

if ($delivery_id <= 0) json_fail('Invalid delivery_id');

// Check assigned
$chk = $pdo->prepare("SELECT id FROM deliveries WHERE id = :id AND assigned_driver_id = :uid LIMIT 1");
$chk->execute([':id' => $delivery_id, ':uid' => (int)$user['id']]);
if (!$chk->fetch()) json_fail('Delivery not found or not assigned to you', 404);

// Ensure upload dirs
$root = realpath(__DIR__ . '/..'); // project root
$photoDir = $root . '/uploads/pod/photos';
$sigDir   = $root . '/uploads/pod/signatures';

if (!is_dir($photoDir)) @mkdir($photoDir, 0777, true);
if (!is_dir($sigDir)) @mkdir($sigDir, 0777, true);

$photo_path = null;
$signature_path = null;

// ---- Handle photo upload (optional but recommended) ----
if (!empty($_FILES['photo']) && $_FILES['photo']['error'] !== UPLOAD_ERR_NO_FILE) {
  if ($_FILES['photo']['error'] !== UPLOAD_ERR_OK) {
    json_fail('Photo upload failed.');
  }

  $tmp = $_FILES['photo']['tmp_name'];
  $mime = mime_content_type($tmp);

  $allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];
  if (!isset($allowed[$mime])) {
    json_fail('Photo must be JPG/PNG/WebP.');
  }

  $ext = $allowed[$mime];
  $filename = 'pod_' . $delivery_id . '_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
  $dest = $photoDir . '/' . $filename;

  if (!move_uploaded_file($tmp, $dest)) {
    json_fail('Failed to save photo.');
  }

  $photo_path = 'uploads/pod/photos/' . $filename; // relative for <img src="../...">
}

// ---- Handle signature (required) ----
$signature_data = trim($signature_data);
if ($signature_data === '') {
  json_fail('Signature is required.');
}
if (!str_starts_with($signature_data, 'data:image/png;base64,')) {
  json_fail('Invalid signature format.');
}

$raw = base64_decode(substr($signature_data, strlen('data:image/png;base64,')));
if ($raw === false || strlen($raw) < 50) {
  json_fail('Signature data is invalid.');
}

$sigFilename = 'sig_' . $delivery_id . '_' . time() . '_' . bin2hex(random_bytes(4)) . '.png';
$sigDest = $sigDir . '/' . $sigFilename;

if (file_put_contents($sigDest, $raw) === false) {
  json_fail('Failed to save signature.');
}

$signature_path = 'uploads/pod/signatures/' . $sigFilename;

// Insert proof
$ins = $pdo->prepare("
  INSERT INTO delivery_proofs (delivery_id, driver_id, photo_path, signature_path, notes)
  VALUES (:did, :uid, :photo, :sig, :notes)
");
$ins->execute([
  ':did' => $delivery_id,
  ':uid' => (int)$user['id'],
  ':photo' => $photo_path,
  ':sig' => $signature_path,
  ':notes' => $notes !== '' ? $notes : null,
]);

echo json_encode([
  'ok' => true,
  'message' => 'Proof of delivery saved.',
  'photo_path' => $photo_path,
  'signature_path' => $signature_path
]);
