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

require_once '../config.php';

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

if (empty($data['machine_id'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing machine_id']);
    exit;
}

try {
    $db = getDB();
    $stmt = $db->prepare("INSERT INTO analytics (machine_id, event_type, event_data, timestamp) VALUES (?, ?, ?, ?)");
    $stmt->execute([$data['machine_id'], $data['event_type'] ?? 'general', json_encode($data), $data['timestamp'] ?? date('Y-m-d H:i:s')]);
    echo json_encode(['success' => true]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
}
