<?php
header('Content-Type: application/json');
include '../config/conexion.php';

try {
    $data = json_decode(file_get_contents('php://input'), true);

    if (!isset($data['placa'], $data['lat'], $data['lng'])) {
        echo json_encode(['status' => 'error', 'msg' => 'Datos incompletos']);
        exit;
    }

    $placa = trim($data['placa']);
    $lat = floatval($data['lat']);
    $lng = floatval($data['lng']);
    // Si no llega 'fin', asumimos 0 (no final)
    $fin = isset($data['fin']) && $data['fin'] == true ? 1 : 0;

    $database = new Connection();
    $db = $database->open();

    $stmt = $db->prepare("
        INSERT INTO login_geolocalizacion (placa, lat, lng, fecha, fin)
        VALUES (:placa, :lat, :lng, NOW(), :fin)
    ");
    $stmt->bindParam(':placa', $placa);
    $stmt->bindParam(':lat', $lat);
    $stmt->bindParam(':lng', $lng);
    $stmt->bindParam(':fin', $fin);
    $stmt->execute();

    echo json_encode(['status' => 'success', 'msg' => 'Ubicación registrada correctamente']);
} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'msg' => 'Error: ' . $e->getMessage()]);
}
