<?php
require_once __DIR__ . '/../../config/cors.php';
require_once __DIR__ . '/../../config/jwt.php';

$user    = auth_required();
$user_id = (int)($user['id'] ?? 0);

if (!$user_id) { http_response_code(401); echo json_encode(['error' => 'Bad token']); exit; }

$lat      = floatval($_POST['lat']      ?? 0);
$lng      = floatval($_POST['lng']      ?? 0);
$accuracy = floatval($_POST['accuracy'] ?? 0);
$battery  = intval($_POST['battery']    ?? -1);

if ($lat === 0.0 && $lng === 0.0) {
    http_response_code(400); echo json_encode(['success' => false, 'message' => 'Invalid coords']); exit;
}

$pdo->prepare(
    "INSERT INTO user_locations (surveyor_id, latitude, longitude, accuracy, battery_level)
     VALUES (?, ?, ?, ?, ?)"
)->execute([$user_id, $lat, $lng, $accuracy, $battery]);

// Keep only 7 days per user
$pdo->prepare(
    "DELETE FROM user_locations WHERE surveyor_id = ? AND recorded_at < NOW() - INTERVAL 7 DAY"
)->execute([$user_id]);

echo json_encode(['success' => true]);
