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

require_once 'config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

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

if (!$data || !isset($data['phone_name']) || !isset($data['latitude']) || !isset($data['longitude'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid data. Required: phone_name, latitude, longitude']);
    exit;
}

$conn = getDBConnection();

$phoneName = sanitizeTableName($data['phone_name']);
$tableName = $phoneName . '_location';

// Create table if not exists
createTableIfNotExists($conn, $phoneName, 'location');

// Insert location data
$stmt = $conn->prepare("INSERT INTO `{$tableName}` (phone_name, latitude, longitude, timestamp) VALUES (?, ?, ?, ?)");

if ($stmt) {
    $timestamp = isset($data['timestamp']) ? $data['timestamp'] : time() * 1000;
    
    $stmt->bind_param("sddi", 
        $data['phone_name'],
        $data['latitude'],
        $data['longitude'],
        $timestamp
    );
    
    if ($stmt->execute()) {
        echo json_encode([
            'success' => true,
            'message' => 'Location updated successfully'
        ]);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to update location']);
    }
    
    $stmt->close();
} else {
    http_response_code(500);
    echo json_encode(['error' => 'Database error']);
}

$conn->close();
?>

