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

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

try {
    $pdo = db();
    $user = current_user();
    $driverId = (int)($user['id'] ?? 0);
    $payload = json_decode(file_get_contents('php://input'), true);

    if (!is_array($payload)) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'Invalid JSON payload']);
        exit;
    }

    $deliveryId = (int)($payload['delivery_id'] ?? 0);
    $lat = isset($payload['lat']) ? (float)$payload['lat'] : null;
    $lng = isset($payload['lng']) ? (float)$payload['lng'] : null;
    $accuracy = isset($payload['accuracy_m']) && $payload['accuracy_m'] !== null ? (float)$payload['accuracy_m'] : null;
    $speed = isset($payload['speed_mps']) && $payload['speed_mps'] !== null ? (float)$payload['speed_mps'] : null;
    $heading = isset($payload['heading_deg']) && $payload['heading_deg'] !== null ? (float)$payload['heading_deg'] : null;

    if ($deliveryId <= 0 || $lat === null || $lng === null) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'Invalid GPS payload']);
        exit;
    }
    if ($lat < -90 || $lat > 90 || $lng < -180 || $lng > 180) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'Latitude or longitude is out of range']);
        exit;
    }

    $delivery = delivery_load($pdo, $deliveryId);
    if (!$delivery || (int)($delivery['assigned_driver_id'] ?? 0) !== $driverId) {
        http_response_code(404);
        echo json_encode(['ok' => false, 'error' => 'Delivery not found or not assigned to you']);
        exit;
    }
    if ((string)($delivery['status'] ?? '') === 'CANCELLED') {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'Cancelled deliveries cannot receive tracking updates']);
        exit;
    }

    $stmt = $pdo->prepare("\n        INSERT INTO delivery_locations\n            (delivery_id, driver_id, lat, lng, accuracy_m, speed_mps, heading_deg, recorded_at)\n        VALUES\n            (:delivery_id, :driver_id, :lat, :lng, :accuracy_m, :speed_mps, :heading_deg, NOW())\n    ");
    $stmt->execute([
        ':delivery_id' => $deliveryId,
        ':driver_id' => $driverId,
        ':lat' => $lat,
        ':lng' => $lng,
        ':accuracy_m' => $accuracy,
        ':speed_mps' => $speed,
        ':heading_deg' => $heading,
    ]);

    $routeStats = delivery_route_stats($pdo, $deliveryId);
    echo json_encode([
        'ok' => true,
        'saved_at' => date('Y-m-d H:i:s'),
        'delivery_status' => $delivery['status'],
        'point_count' => $routeStats['point_count'],
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}
