Files

53 lines
1.8 KiB
PHP

<?php
header('Content-Type: application/json; charset=UTF-8');
require_once '../auth_helper.php';
requireAdmin();
require_once '../db_connect.php';
$data = json_decode(file_get_contents('php://input'), true);
$id = intval($data['id'] ?? 0);
$username = trim($data['username'] ?? '');
$password = trim($data['password'] ?? '');
$role = trim($data['role'] ?? 'pengelola');
$ibadah_id = !empty($data['ibadah_id']) ? intval($data['ibadah_id']) : null;
if (!$id || empty($username)) {
echo json_encode(['status' => 'error', 'message' => 'Data tidak lengkap']);
exit;
}
if ($role !== 'admin' && $role !== 'pengelola') {
echo json_encode(['status' => 'error', 'message' => 'Role tidak valid']);
exit;
}
// Cek apakah username sudah ada di user lain
$stmt = $conn->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
$stmt->bind_param('si', $username, $id);
$stmt->execute();
if ($stmt->get_result()->num_rows > 0) {
echo json_encode(['status' => 'error', 'message' => 'Username sudah digunakan oleh user lain']);
exit;
}
if (!empty($password)) {
// Hash new password
$hashed_password = password_hash($password, PASSWORD_BCRYPT);
$stmt = $conn->prepare("UPDATE users SET username = ?, password = ?, role = ?, ibadah_id = ? WHERE id = ?");
$stmt->bind_param('ssssi', $username, $hashed_password, $role, $ibadah_id, $id);
} else {
// Keep existing password
$stmt = $conn->prepare("UPDATE users SET username = ?, role = ?, ibadah_id = ? WHERE id = ?");
$stmt->bind_param('sssi', $username, $role, $ibadah_id, $id);
}
if ($stmt->execute()) {
echo json_encode(['status' => 'success', 'message' => 'User berhasil diperbarui']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Gagal memperbarui user: ' . $conn->error]);
}
$conn->close();
?>