<?php
require_once __DIR__ . '/../../connect.php';
header('Content-Type: application/json; charset=utf-8');

try {
    $driver_id = filterRequest("driver_id");
    $latitude  = filterRequest("latitude");
    $longitude = filterRequest("longitude");
    $status    = filterRequest("status");
    $heading   = filterRequest("heading");
    $speed     = filterRequest("speed");

    // distance قد تأتي باسم totalDistance من التطبيق
    $distanceRaw = filterRequest("distance");
    if ($distanceRaw === null || $distanceRaw === '') {
        $distanceRaw = filterRequest("totalDistance");
    }

    // تطبيع القيم الرقمية
    $norm = function($v, $default = 0.0) {
        if ($v === null) return $default;
        $v = str_replace(',', '.', trim((string)$v));
        return is_numeric($v) ? (float)$v : $default;
    };

    $lat  = $norm($latitude, 0.0);
    $lng  = $norm($longitude, 0.0);
    $head = $norm($heading, 0.0);
    $spd  = $norm($speed, 0.0);

    // ✅ قرّب لمرتين عشريتين ليتطابق مع DECIMAL(10,2)
    $dist = round($norm($distanceRaw, 0.0), 2);

    // ✅ حارس بسيط للمدى (اختياري)
    if ($dist > 99999999.99) { $dist = 99999999.99; }
    if ($dist < -99999999.99){ $dist = -99999999.99; }

    if (empty($driver_id) || ($lat == 0.0 && $lng == 0.0)) {
        jsonError("Invalid payload");
        exit;
    }

    $created_at = date("Y-m-d H:i:s");

    $sql = "INSERT INTO `car_tracks`
        (`driver_id`,`latitude`,`longitude`,`heading`,`speed`,`distance`,`status`,`created_at`)
        VALUES
        (:driver_id,:latitude,:longitude,:heading,:speed,:distance,:status,:created_at)";

    $stmt = $con->prepare($sql);
    $ok = $stmt->execute([
        ':driver_id'  => $driver_id,
        ':latitude'   => $lat,
        ':longitude'  => $lng,
        ':heading'    => $head,
        ':speed'      => $spd,
        ':distance'   => $dist,      // ← now DECIMAL(10,2)-friendly
        ':status'     => (string)($status ?? 'on'),
        ':created_at' => $created_at,
    ]);

    if ($ok) {
        jsonSuccess(null, "car_tracks saved successfully");
    } else {
        jsonError("Failed to save car track");
    }
} catch (PDOException $e) {
    error_log("car_tracks insert error: " . $e->getMessage());
    jsonError("Database error");
} catch (Throwable $e) {
    error_log("car_tracks insert fatal: " . $e->getMessage());
    jsonError("Server error");
}