<?php
// backend/api/location.php

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

require_once '../config/db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method Not Allowed']);
    exit;
}

$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, true);

if (!$input || !isset($input['fingerprint']) || !isset($input['locations'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid data structure. Fingerprint and locations required.']);
    exit;
}

$fingerprint = $input['fingerprint'];
$locations = $input['locations'];

try {
    $pdo->beginTransaction();

    $sql = "INSERT INTO driver_locations (fingerprint, latitude, longitude, speed, recorded_at, uploaded_at) 
            VALUES (:fingerprint, :latitude, :longitude, :speed, :recorded_at, NOW())";
    $stmt = $pdo->prepare($sql);

    $insertedCount = 0;
    foreach ($locations as $loc) {
        $latitude = $loc['latitude'] ?? null;
        $longitude = $loc['longitude'] ?? null;
        $speed = $loc['speed'] ?? 0;
        $timestamp = $loc['timestamp'] ?? null;

        if ($latitude !== null && $longitude !== null && $timestamp !== null) {
            $stmt->execute([
                ':fingerprint' => $fingerprint,
                ':latitude' => $latitude,
                ':longitude' => $longitude,
                ':speed' => $speed,
                ':recorded_at' => date('Y-m-d H:i:s', $timestamp / 1000)
            ]);
            $insertedCount++;
        }
    }

    $pdo->commit();

    http_response_code(201);
    echo json_encode([
        'success' => true, 
        'message' => "Bulk location sync successful", 
        'synced_count' => $insertedCount
    ]);
} catch (PDOException $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
