TKK_E32230273/delete_occupant.php

84 lines
2.6 KiB
PHP

<?php
include "koneksi.php";
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(["status" => "error", "message" => "Method tidak diizinkan"]);
exit;
}
if (!isset($_POST['id_occupant']) || empty($_POST['id_occupant'])) {
echo json_encode(["status" => "error", "message" => "ID tidak ditemukan"]);
exit;
}
$id = $_POST['id_occupant'];
if (!is_numeric($id)) {
echo json_encode(["status" => "error", "message" => "ID tidak valid"]);
exit;
}
try {
// Pastikan kolom occupant_name ada di tabel history
try {
$pdo->exec("ALTER TABLE history ADD COLUMN occupant_name VARCHAR(255) DEFAULT NULL");
} catch (PDOException $e) {
// Abaikan jika kolom sudah ada
}
// Ambil data occupant (foto, finger_id, name)
$getOcc = $pdo->prepare("SELECT name, foto, finger_id FROM occupant WHERE id_occupant = ?");
$getOcc->execute([$id]);
$row = $getOcc->fetch();
if ($row && !empty($row['finger_id'])) {
$qFile = __DIR__ . '/esp32_finger_delete_queue.json';
$queue = file_exists($qFile) ? json_decode(file_get_contents($qFile), true) : [];
if (!is_array($queue)) $queue = [];
$queue[] = $row['finger_id'];
file_put_contents($qFile, json_encode($queue));
}
// Simpan nama occupant ke history & pindahkan semua history ke Trash
if ($row) {
$updateHistory = $pdo->prepare("
UPDATE history
SET occupant_name = ?,
is_deleted = 1,
is_starred = 0,
is_read = 1,
deleted_at = IFNULL(deleted_at, NOW())
WHERE occupant_id = ?
");
$updateHistory->execute([$row['name'], $id]);
}
// Hapus chat yang terkait dengan occupant agar tidak ada orphaned messages
$delChats = $pdo->prepare("DELETE FROM chats WHERE id_occupant = ?");
$delChats->execute([$id]);
$stmt = $pdo->prepare("DELETE FROM occupant WHERE id_occupant = ?");
$stmt->execute([$id]);
if ($stmt->rowCount() > 0) {
// Hapus file foto jika ada (kecuali foto default)
if ($row && !empty($row['foto']) && file_exists(__DIR__ . '/' . $row['foto']) && strpos($row['foto'], 'images/faces/') === false) {
@unlink(__DIR__ . '/' . $row['foto']);
}
echo json_encode(["status" => "success"]);
} else {
echo json_encode([
"status" => "error",
"message" => "Data tidak ditemukan atau sudah dihapus"
]);
}
} catch (PDOException $e) {
echo json_encode([
"status" => "error",
"message" => "Gagal menghapus: " . $e->getMessage()
]);
}
?>