esp/api/api_reglas.php

207 lines
5.7 KiB
PHP

<?php
// API para gestión de reglas de automatización
// Rutas:
// - GET /api/index.php?r=get_reglas&chipid=XXXX
// - POST /api/index.php?r=save_reglas (body: {chipid, rules})
// - POST /api/index.php?r=delete_regla (body: {chipid, ruleId})
require_once __DIR__ . '/bootstrap.php';
// Archivo de reglas
$file = __DIR__ . '/../data/reglas.json';
// Asegurar que el archivo existe
if (!file_exists($file)) {
file_put_contents($file, json_encode([], JSON_PRETTY_PRINT));
}
// Leer reglas
function loadRules() {
global $file;
if (!file_exists($file)) return [];
$content = @file_get_contents($file);
if ($content === false) return [];
$data = json_decode($content, true);
if (json_last_error() !== JSON_ERROR_NONE) return [];
return is_array($data) ? $data : [];
}
// Guardar reglas
function saveRules($data) {
global $file;
$json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
return file_put_contents($file, $json) !== false;
}
// Obtener ruta desde parámetro
$route = $_GET['r'] ?? null;
// Si viene por POST, revisar en el body también
if (!$route && $_SERVER['REQUEST_METHOD'] === 'POST') {
$input = file_get_contents('php://input');
$postData = json_decode($input, true);
$route = $postData['r'] ?? 'save_reglas';
}
// Fallback: detectar por método y parámetros
if (!$route) {
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
if ($method === 'GET' && isset($_GET['chipid'])) {
$route = 'get_reglas';
}
}
// Si aún no hay ruta, error
if (!$route) {
json_error('Ruta no especificada. Use ?r=get_reglas o ?r=save_reglas', 400);
}
switch ($route) {
case 'get_reglas': {
$chipid = $_GET['chipid'] ?? '';
if (empty($chipid)) {
json_error('ChipID requerido', 400);
}
$allRules = loadRules();
$rules = $allRules[$chipid] ?? [];
json_response(true, $rules, 'Reglas cargadas correctamente');
break;
}
case 'save_reglas': {
// Leer body JSON
$input = file_get_contents('php://input');
$data = json_decode($input, true);
if (json_last_error() !== JSON_ERROR_NONE) {
json_error('JSON inválido', 400);
}
$chipid = $data['chipid'] ?? '';
$rules = $data['rules'] ?? [];
if (empty($chipid)) {
json_error('ChipID requerido', 400);
}
if (!is_array($rules)) {
json_error('Rules debe ser un array', 400);
}
// Validar estructura básica de reglas
foreach ($rules as $rule) {
if (!isset($rule['id']) || !isset($rule['name'])) {
json_error('Cada regla debe tener id y name', 400);
}
}
// Cargar todas las reglas
$allRules = loadRules();
// Actualizar reglas del dispositivo
$allRules[$chipid] = $rules;
// Guardar
if (!saveRules($allRules)) {
json_error('Error al guardar reglas', 500);
}
json_response(true, ['count' => count($rules)], 'Reglas guardadas correctamente');
break;
}
case 'delete_regla': {
// Leer body JSON
$input = file_get_contents('php://input');
$data = json_decode($input, true);
if (json_last_error() !== JSON_ERROR_NONE) {
json_error('JSON inválido', 400);
}
$chipid = $data['chipid'] ?? '';
$ruleId = $data['ruleId'] ?? '';
if (empty($chipid) || empty($ruleId)) {
json_error('ChipID y ruleId requeridos', 400);
}
// Cargar todas las reglas
$allRules = loadRules();
if (!isset($allRules[$chipid])) {
json_error('No hay reglas para este dispositivo', 404);
}
// Filtrar la regla a eliminar
$allRules[$chipid] = array_values(array_filter($allRules[$chipid], function($rule) use ($ruleId) {
return $rule['id'] !== $ruleId;
}));
// Guardar
if (!saveRules($allRules)) {
json_error('Error al guardar reglas', 500);
}
json_response(true, null, 'Regla eliminada correctamente');
break;
}
case 'toggle_regla': {
// Activar/desactivar una regla
$input = file_get_contents('php://input');
$data = json_decode($input, true);
if (json_last_error() !== JSON_ERROR_NONE) {
json_error('JSON inválido', 400);
}
$chipid = $data['chipid'] ?? '';
$ruleId = $data['ruleId'] ?? '';
$enabled = $data['enabled'] ?? true;
if (empty($chipid) || empty($ruleId)) {
json_error('ChipID y ruleId requeridos', 400);
}
// Cargar todas las reglas
$allRules = loadRules();
if (!isset($allRules[$chipid])) {
json_error('No hay reglas para este dispositivo', 404);
}
// Buscar y actualizar la regla
$found = false;
foreach ($allRules[$chipid] as &$rule) {
if ($rule['id'] === $ruleId) {
$rule['enabled'] = (bool)$enabled;
$found = true;
break;
}
}
unset($rule);
if (!$found) {
json_error('Regla no encontrada', 404);
}
// Guardar
if (!saveRules($allRules)) {
json_error('Error al guardar reglas', 500);
}
json_response(true, null, 'Estado de regla actualizado');
break;
}
default:
json_error('Ruta no encontrada: ' . $route, 404);
}