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

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

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

    $data = json_decode(file_get_contents('php://input'), true);
    if (!is_array($data)) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'Invalid JSON payload']);
        exit;
    }

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

    if ($delivery_id <= 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;
    }

    $check = $pdo->prepare("\n        SELECT id, status\n        FROM deliveries\n        WHERE id = :id AND assigned_driver_id = :driver_id\n        LIMIT 1\n    ");
    $check->execute([
        ':id' => $delivery_id,
        ':driver_id' => (int)$user['id'],
    ]);
    $delivery = $check->fetch(PDO::FETCH_ASSOC);

    if (!$delivery) {
        http_response_code(404);
        echo json_encode(['ok' => false, 'error' => 'Delivery not found or not assigned to this driver']);
        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, :speed, :heading, NOW())\n    ");

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

    echo json_encode([
        'ok' => true,
        'saved_at' => date('Y-m-d H:i:s'),
        'delivery_status' => $delivery['status'],
    ]);
    exit;

} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
    exit;
}
