<?php
ob_start();
// api/save_config.php
require_once '../auth.php';
require_once '../config.php';

checkApiLogin();

ob_clean();
header('Content-Type: application/json; charset=utf-8');

// Allow POST only
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(false, 'Method not allowed', null, 405);
}

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

if (!$data) {
    jsonResponse(false, 'Invalid JSON', null, 400);
}

// Ensure config directory exists
$configDir = '../config';
if (!is_dir($configDir)) {
    mkdir($configDir, 0777, true);
}

// Save to file
$file = $configDir . '/sensor_layout.json';
if (file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT))) {
    jsonResponse(true, 'Config saved successfully');
} else {
    jsonResponse(false, 'Failed to write config file', null, 500);
}
