35908-vm/api/alarms.php
2025-11-21 18:15:18 +00:00

102 lines
3.8 KiB
PHP

<?php
require_once __DIR__ . '/../db/config.php';
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'Invalid request'];
$pdo = db();
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action'])) {
if ($_GET['action'] === 'check') {
try {
$pdo->beginTransaction();
// Find active alarms that are due and lock the rows
$stmt = $pdo->prepare("SELECT * FROM alarms WHERE alarm_time <= CURTIME() AND is_active = 1 FOR UPDATE");
$stmt->execute();
$alarms = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($alarms) {
// Deactivate the found alarms to prevent them from ringing again
$alarmIds = array_map(function($alarm) {
return $alarm['id'];
}, $alarms);
if (!empty($alarmIds)) {
$placeholders = implode(',', array_fill(0, count($alarmIds), '?'));
$updateStmt = $pdo->prepare("UPDATE alarms SET is_active = 0 WHERE id IN ($placeholders)");
$updateStmt->execute($alarmIds);
}
$response = ['success' => true, 'alarms' => $alarms];
} else {
$response = ['success' => true, 'alarms' => []];
}
$pdo->commit();
} catch (PDOException $e) {
$pdo->rollBack();
$response['message'] = 'Database error: ' . $e->getMessage();
}
}
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Simple routing based on a POST field
$action = $_POST['action'] ?? '';
if ($action === 'create') {
$alarm_time = $_POST['alarm_time'] ?? null;
$label = $_POST['label'] ?? '';
if ($alarm_time) {
try {
$stmt = $pdo->prepare("INSERT INTO alarms (alarm_time, label) VALUES (?, ?)");
$stmt->execute([$alarm_time, $label]);
$response = ['success' => true, 'message' => 'Alarm created successfully.', 'id' => $pdo->lastInsertId()];
} catch (PDOException $e) {
$response['message'] = 'Database error: ' . $e->getMessage();
}
} else {
$response['message'] = 'Alarm time is required.';
}
} elseif ($action === 'delete') {
$alarm_id = $_POST['alarm_id'] ?? null;
if ($alarm_id) {
try {
$stmt = $pdo->prepare("DELETE FROM alarms WHERE id = ?");
$stmt->execute([$alarm_id]);
if ($stmt->rowCount()) {
$response = ['success' => true, 'message' => 'Alarm deleted successfully.'];
} else {
$response['message'] = 'Alarm not found.';
}
} catch (PDOException $e) {
$response['message'] = 'Database error: ' . $e->getMessage();
}
} else {
$response['message'] = 'Alarm ID is required.';
}
} elseif ($action === 'toggle') {
$alarm_id = $_POST['alarm_id'] ?? null;
$is_active = $_POST['is_active'] ?? null;
if ($alarm_id && $is_active !== null) {
try {
$stmt = $pdo->prepare("UPDATE alarms SET is_active = ? WHERE id = ?");
$stmt->execute([$is_active, $alarm_id]);
if ($stmt->rowCount()) {
$response = ['success' => true, 'message' => 'Alarm status updated.'];
} else {
$response['message'] = 'Alarm not found or status unchanged.';
}
} catch (PDOException $e) {
$response['message'] = 'Database error: ' . $e->getMessage();
}
} else {
$response['message'] = 'Alarm ID and active status are required.';
}
}
}
echo json_encode($response);