46 lines
1.6 KiB
PHP
46 lines
1.6 KiB
PHP
<?php
|
|
// api/delete_office.php
|
|
header('Content-Type: application/json');
|
|
require_once '../db/config.php';
|
|
session_start();
|
|
|
|
// Authentication and Authorization check
|
|
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'super_admin') {
|
|
echo json_encode(['success' => false, 'message' => 'Unauthorized']);
|
|
exit;
|
|
}
|
|
|
|
if (empty($_POST['id'])) {
|
|
echo json_encode(['success' => false, 'message' => 'Office ID is required.']);
|
|
exit;
|
|
}
|
|
|
|
$id = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT);
|
|
|
|
try {
|
|
// The foreign key constraints in `users` and `aset` tables are set to
|
|
// `ON DELETE SET NULL` and `ON DELETE RESTRICT` respectively.
|
|
// We should check for assets before deleting.
|
|
|
|
$stmt_check = db()->prepare("SELECT COUNT(*) FROM aset WHERE id_kantor_lokasi = ?");
|
|
$stmt_check->execute([$id]);
|
|
if ($stmt_check->fetchColumn() > 0) {
|
|
echo json_encode(['success' => false, 'message' => 'Cannot delete office. It is still associated with existing assets. Please reassign assets first.']);
|
|
exit;
|
|
}
|
|
|
|
// If no assets are linked, proceed with deletion.
|
|
// Users linked to this office will have their id_kantor set to NULL.
|
|
$stmt_delete = db()->prepare("DELETE FROM kantor WHERE id = ?");
|
|
$stmt_delete->execute([$id]);
|
|
|
|
if ($stmt_delete->rowCount() > 0) {
|
|
echo json_encode(['success' => true, 'message' => 'Office deleted successfully.']);
|
|
} else {
|
|
echo json_encode(['success' => false, 'message' => 'Office not found or could not be deleted.']);
|
|
}
|
|
|
|
} catch (PDOException $e) {
|
|
echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
|
|
}
|
|
?>
|