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

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

$pdo = db();
$data = json_decode(file_get_contents('php://input'), true);

$delivery_id = (int)($data['delivery_id'] ?? 0);
$lat = $data['lat'] ?? null;
$lng = $data['lng'] ?? null;
$accuracy = $data['accuracy_m'] ?? null;
$speed = $data['speed_mps'] ?? null;
$heading = $data['heading_deg'] ?? null;

if ($delivery_id <= 0 || $lat === null || $lng === null) {
    echo json_encode(['ok' => false, 'error' => 'Invalid GPS payload']);
    exit;
}

$stmt = $pdo->prepare("
    INSERT INTO delivery_locations
        (delivery_id, driver_id, lat, lng, accuracy_m, speed_mps, heading_deg, recorded_at)
    VALUES
        (:delivery_id, :driver_id, :lat, :lng, :accuracy, :speed, :heading, NOW())
");

$stmt->execute([
    ':delivery_id' => $delivery_id,
    ':driver_id'   => $_SESSION['user']['id'],
    ':lat'         => $lat,
    ':lng'         => $lng,
    ':accuracy'    => $accuracy,
    ':speed'       => $speed,
    ':heading'     => $heading
]);

echo json_encode(['ok' => true]);
