TKK_E32230273/api_door_status.php

62 lines
2.5 KiB
PHP

<?php
session_start();
include 'koneksi.php';
include 'notification_helper.php';
require_once 'PushHelper.php';
header('Content-Type: application/json');
$statusFile = 'door_status.txt';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$action = $_POST['action'] ?? '';
if ($action === 'lock') {
file_put_contents($statusFile, 'locked');
send_notification($pdo, 'mdi-door-closed-lock', 'Door Locked', 'The FTM room door has been successfully locked.', 'System detected that the door is now closed and locked.', false);
echo json_encode(["status" => "success", "door_state" => "locked"]);
} elseif ($action === 'unlock') {
file_put_contents($statusFile, 'unlocked');
send_notification($pdo, 'mdi-door-open', 'Door Unlocked', 'The FTM room door has been opened.', 'System detected that the door is currently open.', false);
PushHelper::broadcastToAdmins($pdo, 'Door Unlocked', 'The FTM room door was accessed. Please ensure it is securely locked afterwards.', '/access.php');
echo json_encode(["status" => "success", "door_state" => "unlocked"]);
} else {
echo json_encode(["status" => "error", "message" => "Aksi tidak dikenal"]);
}
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
$state = 'locked'; // Default
$last_time = time();
$day_mapping = [
'Sunday' => 'Minggu', 'Monday' => 'Senin', 'Tuesday' => 'Selasa',
'Wednesday' => 'Rabu', 'Thursday' => 'Kamis', 'Friday' => 'Jumat', 'Saturday' => 'Sabtu'
];
$month_mapping = [
1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April', 5 => 'Mei', 6 => 'Juni',
7 => 'Juli', 8 => 'Agustus', 9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
];
if (file_exists($statusFile)) {
$state = trim(file_get_contents($statusFile));
$last_time = filemtime($statusFile);
}
if (!date_default_timezone_get() || date_default_timezone_get() != 'Asia/Jakarta') {
date_default_timezone_set('Asia/Jakarta');
}
$hari = $day_mapping[date('l', $last_time)];
$tanggal = date('d', $last_time);
$bln = $month_mapping[(int)date('n', $last_time)];
$thn = date('Y', $last_time);
$date_formatted = "$hari, $tanggal $bln $thn";
$time_formatted = date('H:i:s', $last_time);
echo json_encode([
"status" => "success",
"door_state" => $state,
"last_updated_time" => $time_formatted,
"last_updated_date" => $date_formatted
]);
}
?>