Files
2026-09-16 23:20:08 +07:00

68 lines
2.6 KiB
PHP

<?php
require_once 'config.php';
header('Content-Type: application/json');
checkAdmin();
$log_db = getDB(DB_LOG_HOST, DB_LOG_NAME, DB_LOG_USER, DB_LOG_PASS);
$action = $_REQUEST['action'] ?? '';
try {
if ($action === 'list') {
$stmt = $log_db->query("SELECT * FROM system_admins ORDER BY id DESC");
$admins = $stmt->fetchAll();
foreach ($admins as &$admin) {
$admin['created_at'] = formatThaiDate($admin['created_at']);
}
echo json_encode(['data' => $admins]);
}
elseif ($action === 'save') {
$cid = trim($_POST['cid'] ?? '');
$name = trim($_POST['name'] ?? '');
if (empty($cid) || empty($name)) {
echo json_encode(['status' => 'error', 'message' => 'กรุณากรอกข้อมูลให้ครบถ้วน']);
exit;
}
// Check if CID already exists
$stmt = $log_db->prepare("SELECT id FROM system_admins WHERE cid = ?");
$stmt->execute([$cid]);
if ($stmt->fetch()) {
echo json_encode(['status' => 'error', 'message' => 'เลขบัตรประชาชนนี้ถูกเพิ่มเป็นผู้ดูแลระบบไปแล้ว']);
exit;
}
// Insert
$stmt = $log_db->prepare("INSERT INTO system_admins (cid, name) VALUES (?, ?)");
$stmt->execute([$cid, $name]);
addSystemLog('ADD_ADMIN', "เพิ่มผู้ดูแลระบบ: $name ($cid)");
echo json_encode(['status' => 'success', 'message' => 'เพิ่มผู้ดูแลระบบสำเร็จ']);
}
elseif ($action === 'delete') {
$id = $_POST['id'] ?? 0;
// Get name before delete
$stmt = $log_db->prepare("SELECT name, cid FROM system_admins WHERE id = ?");
$stmt->execute([$id]);
$admin = $stmt->fetch();
if ($admin) {
$stmt = $log_db->prepare("DELETE FROM system_admins WHERE id = ?");
$stmt->execute([$id]);
addSystemLog('DELETE_ADMIN', "ลบสิทธิ์ผู้ดูแลระบบ: {$admin['name']} ({$admin['cid']})");
}
echo json_encode(['status' => 'success', 'message' => 'ลบสิทธิ์ผู้ดูแลระบบสำเร็จ']);
}
else {
echo json_encode(['status' => 'error', 'message' => 'Unknown action']);
}
} catch (Exception $e) {
echo json_encode(['status' => 'error', 'message' => 'Database Error: ' . $e->getMessage()]);
}