chore: prepare docker webgis deployment

This commit is contained in:
Andrie
2026-06-11 18:14:21 +07:00
parent d2214ad9c8
commit a90748d9c1
149 changed files with 20844 additions and 5 deletions
@@ -0,0 +1,47 @@
<?php
// api/auth/change_password.php — POST: ganti password akun sendiri
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('viewer');
require_csrf();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
exit;
}
$new_password = $_POST['new_password'] ?? '';
$confirm = $_POST['confirm_password'] ?? '';
// Validasi policy: min 8 karakter, kombinasi huruf + angka
if (strlen($new_password) < 8) {
echo json_encode(['status' => 'error', 'message' => 'Password minimal 8 karakter']);
exit;
}
if (!preg_match('/[a-zA-Z]/', $new_password) || !preg_match('/[0-9]/', $new_password)) {
echo json_encode(['status' => 'error', 'message' => 'Password harus mengandung huruf dan angka']);
exit;
}
if ($new_password !== $confirm) {
echo json_encode(['status' => 'error', 'message' => 'Konfirmasi password tidak cocok']);
exit;
}
$hash = password_hash($new_password, PASSWORD_BCRYPT);
$user_id = get_user_id();
$stmt = $conn->prepare("UPDATE users SET password = ?, must_change_password = 0 WHERE id = ?");
$stmt->bind_param('si', $hash, $user_id);
if ($stmt->execute()) {
$_SESSION['must_change_password'] = 0;
echo json_encode(['status' => 'success', 'message' => 'Password berhasil diubah']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Gagal menyimpan password']);
}
$stmt->close();
$conn->close();
+105
View File
@@ -0,0 +1,105 @@
<?php
// api/auth/login.php — POST: validasi kredensial + buat sesi
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
exit;
}
$username = trim($_POST['username'] ?? '');
$password = trim($_POST['password'] ?? '');
if (!$username || !$password) {
echo json_encode(['status' => 'error', 'message' => 'Username dan password wajib diisi']);
exit;
}
// Ambil user dari DB (prepared statement — SQL injection safe)
$stmt = $conn->prepare(
"SELECT id, nama_lengkap, password, role, ibadah_id, is_active,
must_change_password, login_attempts, locked_until
FROM users WHERE username = ? LIMIT 1"
);
$stmt->bind_param('s', $username);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (!$user) {
echo json_encode(['status' => 'error', 'message' => 'Username atau password salah']);
exit;
}
if (!$user['is_active']) {
echo json_encode(['status' => 'error', 'message' => 'Akun dinonaktifkan. Hubungi Administrator.']);
exit;
}
// Cek lockout
if ($user['locked_until'] && strtotime($user['locked_until']) > time()) {
$menit = ceil((strtotime($user['locked_until']) - time()) / 60);
echo json_encode(['status' => 'error', 'message' => "Akun terkunci. Coba lagi dalam {$menit} menit."]);
exit;
}
// Verifikasi password
if (!password_verify($password, $user['password'])) {
$attempts = $user['login_attempts'] + 1;
if ($attempts >= MAX_LOGIN_ATTEMPTS) {
$locked_until = date('Y-m-d H:i:s', time() + LOCKOUT_MINUTES * 60);
$stmt = $conn->prepare("UPDATE users SET login_attempts = ?, locked_until = ? WHERE id = ?");
$stmt->bind_param('isi', $attempts, $locked_until, $user['id']);
} else {
$stmt = $conn->prepare("UPDATE users SET login_attempts = ? WHERE id = ?");
$stmt->bind_param('ii', $attempts, $user['id']);
}
$stmt->execute();
$stmt->close();
$sisa = MAX_LOGIN_ATTEMPTS - $attempts;
$msg = $sisa > 0
? "Username atau password salah. Sisa percobaan: {$sisa}"
: "Akun terkunci " . LOCKOUT_MINUTES . " menit karena terlalu banyak percobaan gagal.";
echo json_encode(['status' => 'error', 'message' => $msg]);
exit;
}
// Login berhasil — reset attempts
$stmt = $conn->prepare("UPDATE users SET login_attempts = 0, locked_until = NULL WHERE id = ?");
$stmt->bind_param('i', $user['id']);
$stmt->execute();
$stmt->close();
// Rotate session ID sebelum menulis data (cegah session fixation)
session_regenerate_id(true);
// Buat sesi
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $username;
$_SESSION['nama'] = $user['nama_lengkap'];
$_SESSION['role'] = $user['role'];
$_SESSION['ibadah_id'] = $user['ibadah_id'];
$_SESSION['must_change_password'] = (int)$user['must_change_password'];
$_SESSION['last_activity'] = time();
// Redirect target: admin → dashboard, operator/viewer → map
$redirect = ($user['role'] === 'administrator') ? '../dashboard.php' : '../index.php';
echo json_encode([
'status' => 'success',
'redirect' => $redirect,
'data' => [
'user_id' => $user['id'],
'nama' => $user['nama_lengkap'],
'role' => $user['role'],
'ibadah_id' => $user['ibadah_id'],
'must_change_password'=> (bool)$user['must_change_password'],
]
]);
$conn->close();
+8
View File
@@ -0,0 +1,8 @@
<?php
// api/auth/logout.php — Hancurkan sesi dan redirect ke login
require_once '../../config.php';
require_once '../../auth/helper.php';
session_destroy();
header('Location: ../../auth/login.php');
exit;
@@ -0,0 +1,62 @@
<?php
/**
* api/dashboard/trend.php
* Hitung tren persen cakupan 6 bulan terakhir.
* Metode: untuk tiap bulan, query penduduk yang created_at <= akhir bulan itu
* (kumulatif), lalu hitung % jiwa terjangkau vs total jiwa.
*/
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('administrator');
header('Content-Type: application/json; charset=utf-8');
// Build last 6 months (oldest first)
$months = [];
for ($i = 5; $i >= 0; $i--) {
$year = (int) date('Y');
$month = (int) date('n') - $i;
while ($month <= 0) { $month += 12; $year--; }
while ($month > 12) { $month -= 12; $year++; }
$last_day = date('Y-m-d', mktime(0, 0, 0, $month + 1, 0, $year)); // last day of month
$month_names = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Agt','Sep','Okt','Nov','Des'];
$months[] = [
'label' => $month_names[$month - 1] . ' ' . $year,
'end_dt' => $last_day,
];
}
$rows = [];
$stmt = $conn->prepare(
"SELECT
COALESCE(SUM(jumlah_jiwa), 0) AS total_jiwa,
COALESCE(SUM(CASE WHEN is_blank_spot = 0 THEN jumlah_jiwa ELSE 0 END), 0) AS jiwa_terjangkau
FROM penduduk_miskin
WHERE is_active = 1
AND deleted_at IS NULL
AND created_at <= ?"
);
foreach ($months as $m) {
$end = $m['end_dt'];
$stmt->bind_param('s', $end);
$stmt->execute();
$r = $stmt->get_result()->fetch_assoc();
$total = (int) ($r['total_jiwa'] ?? 0);
$terjangkau = (int) ($r['jiwa_terjangkau'] ?? 0);
$pct = $total > 0 ? round($terjangkau / $total * 100, 2) : 0;
$rows[] = [
'bulan' => $m['label'],
'total_jiwa' => $total,
'jiwa_terjangkau' => $terjangkau,
'pct_cakupan' => $pct,
];
}
$stmt->close();
echo json_encode(['status' => 'success', 'data' => $rows]);
+66
View File
@@ -0,0 +1,66 @@
<?php
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('administrator');
$ibadah_id = (int)($_GET['ibadah_id'] ?? 0);
if (!$ibadah_id) {
http_response_code(400);
die('ibadah_id diperlukan');
}
$r = $conn->prepare("SELECT nama FROM rumah_ibadah WHERE id=? AND deleted_at IS NULL");
$r->bind_param('i', $ibadah_id);
$r->execute();
$row = $r->get_result()->fetch_assoc();
$r->close();
if (!$row) {
http_response_code(404);
die('Rumah ibadah tidak ditemukan');
}
$nama_ibadah = preg_replace('/[^a-zA-Z0-9\-_]/', '_', $row['nama']);
$tanggal = date('Y-m-d');
$filename = "binaan_{$nama_ibadah}_{$tanggal}.csv";
header('Content-Type: text/csv; charset=utf-8');
header("Content-Disposition: attachment; filename=\"$filename\"");
$out = fopen('php://output', 'w');
fwrite($out, "\xEF\xBB\xBF");
function csv_safe_cell($value): string {
$text = (string)($value ?? '');
$trimmed = ltrim($text);
if ($trimmed !== '' && in_array($trimmed[0], ['=', '+', '-', '@'], true)) {
return "'" . $text;
}
return $text;
}
fputcsv($out, ['nama_kk', 'jumlah_jiwa', 'kategori', 'alamat', 'status_bantuan', 'catatan']);
$stmt = $conn->prepare("
SELECT nama_kk, jumlah_jiwa, kategori, alamat, status_bantuan, catatan
FROM penduduk_miskin
WHERE ibadah_id=? AND is_active=1 AND deleted_at IS NULL
ORDER BY nama_kk
");
$stmt->bind_param('i', $ibadah_id);
$stmt->execute();
$res = $stmt->get_result();
while ($w = $res->fetch_assoc()) {
fputcsv($out, [
csv_safe_cell($w['nama_kk']),
csv_safe_cell($w['jumlah_jiwa']),
csv_safe_cell($w['kategori']),
csv_safe_cell($w['alamat'] ?? ''),
csv_safe_cell($w['status_bantuan']),
csv_safe_cell($w['catatan'] ?? ''),
]);
}
$stmt->close();
fclose($out);
$conn->close();
+109
View File
@@ -0,0 +1,109 @@
<?php
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('administrator');
$ibadah_id = (int)($_GET['ibadah_id'] ?? 0);
if (!$ibadah_id) { http_response_code(400); die('ibadah_id diperlukan'); }
$r = $conn->prepare("SELECT * FROM rumah_ibadah WHERE id=? AND deleted_at IS NULL");
$r->bind_param('i', $ibadah_id);
$r->execute();
$ib = $r->get_result()->fetch_assoc();
$r->close();
if (!$ib) { http_response_code(404); die('Tidak ditemukan'); }
$s = $conn->prepare("
SELECT COUNT(*) AS jml_kk,
COALESCE(SUM(jumlah_jiwa), 0) AS jml_jiwa,
COALESCE(SUM(CASE WHEN status_bantuan='Sudah Ditangani' THEN 1 ELSE 0 END), 0) AS ditangani
FROM penduduk_miskin
WHERE ibadah_id=? AND is_active=1 AND deleted_at IS NULL
");
$s->bind_param('i', $ibadah_id);
$s->execute();
$st = $s->get_result()->fetch_assoc();
$s->close();
$pct = $st['jml_kk'] > 0 ? round($st['ditangani'] / $st['jml_kk'] * 100) : 0;
$w = $conn->prepare("
SELECT nama_kk, jumlah_jiwa, kategori, status_bantuan
FROM penduduk_miskin
WHERE ibadah_id=? AND is_active=1 AND deleted_at IS NULL
ORDER BY nama_kk
");
$w->bind_param('i', $ibadah_id);
$w->execute();
$warga_res = $w->get_result();
$warga_list = [];
while ($row = $warga_res->fetch_assoc()) $warga_list[] = $row;
$w->close();
$conn->close();
$tanggal = date('d F Y');
header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Laporan Binaan — <?= htmlspecialchars($ib['nama']) ?></title>
<style>
* { box-sizing:border-box; margin:0; padding:0; }
body { font-family: Arial, sans-serif; font-size: 12px; color: #111; padding: 20px; }
.header { border-bottom: 2px solid #333; margin-bottom: 16px; padding-bottom: 10px; }
.header h1 { font-size: 16px; margin-bottom: 4px; }
.header p { font-size: 11px; color: #555; margin-top: 2px; }
.cards { display: flex; gap: 16px; margin-bottom: 16px; }
.card { border: 1px solid #ddd; border-radius: 6px; padding: 10px 16px; text-align: center; flex: 1; }
.card .val { font-size: 22px; font-weight: 700; color: #1a1a1a; }
.card .lbl { font-size: 10px; color: #777; margin-top: 2px; }
table { width: 100%; border-collapse: collapse; }
th, td { border: 1px solid #ddd; padding: 6px 10px; text-align: left; font-size: 11px; }
th { background: #f0f0f0; font-weight: 700; }
tr:nth-child(even) td { background: #fafafa; }
.status-done { color: #166534; font-weight: 700; }
.status-process { color: #92400e; font-weight: 700; }
.status-none { color: #6b7280; }
.footer { margin-top: 20px; font-size: 10px; color: #999; text-align: right; }
@media print { body { padding: 0; } }
</style>
</head>
<body>
<div class="header">
<h1>Laporan Warga Binaan — <?= htmlspecialchars($ib['nama']) ?></h1>
<p><?= htmlspecialchars($ib['jenis']) ?> · <?= htmlspecialchars($ib['alamat'] ?? '-') ?></p>
<p>Digenerate: <?= $tanggal ?></p>
</div>
<div class="cards">
<div class="card"><div class="val"><?= $st['jml_kk'] ?></div><div class="lbl">Total KK</div></div>
<div class="card"><div class="val"><?= $st['jml_jiwa']?></div><div class="lbl">Total Jiwa</div></div>
<div class="card"><div class="val"><?= $pct ?>%</div> <div class="lbl">Sudah Ditangani</div></div>
</div>
<table>
<thead>
<tr><th>#</th><th>Nama KK</th><th>Jiwa</th><th>Kategori</th><th>Status Bantuan</th></tr>
</thead>
<tbody>
<?php foreach ($warga_list as $i => $warga): ?>
<?php $cls = match($warga['status_bantuan']) {
'Sudah Ditangani' => 'status-done',
'Dalam Proses' => 'status-process',
default => 'status-none',
}; ?>
<tr>
<td><?= $i + 1 ?></td>
<td><?= htmlspecialchars($warga['nama_kk']) ?></td>
<td><?= $warga['jumlah_jiwa'] ?></td>
<td><?= $warga['kategori'] ?></td>
<td class="<?= $cls ?>"><?= $warga['status_bantuan'] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="footer"><?= APP_NAME ?> · <?= $tanggal ?></div>
<script>window.onload = () => window.print();</script>
</body>
</html>
+33
View File
@@ -0,0 +1,33 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
// Public viewer boleh akses — tidak perlu require_auth
// Hanya tampilkan warga yang sudah Terverifikasi di agregat publik
$sql = "
SELECT ri.id, ri.nama, ri.jenis, ri.alamat, ri.lat, ri.lng,
ri.radius_m, ri.kontak, ri.created_at, ri.updated_at,
COUNT(pm.id) AS total_kk,
COALESCE(SUM(pm.jumlah_jiwa), 0) AS total_jiwa,
COALESCE(SUM(CASE WHEN pm.is_blank_spot = 0 THEN pm.jumlah_jiwa ELSE 0 END), 0) AS jiwa_terjangkau,
COALESCE(SUM(CASE WHEN pm.is_blank_spot = 1 THEN pm.jumlah_jiwa ELSE 0 END), 0) AS jiwa_blankspot
FROM rumah_ibadah ri
LEFT JOIN penduduk_miskin pm
ON pm.ibadah_id = ri.id
AND pm.is_active = 1
AND pm.deleted_at IS NULL
AND pm.status_verifikasi = 'Terverifikasi'
WHERE ri.deleted_at IS NULL
GROUP BY ri.id
ORDER BY ri.created_at DESC
";
$result = $conn->query($sql);
$data = [];
while ($row = $result->fetch_assoc()) $data[] = $row;
echo json_encode(['status' => 'success', 'total' => count($data), 'data' => $data]);
$conn->close();
+102
View File
@@ -0,0 +1,102 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('administrator');
require_csrf();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Method not allowed']); exit;
}
$id = (int) ($_POST['id'] ?? 0);
if (!$id) { echo json_encode(['status' => 'error', 'message' => 'ID tidak valid']); exit; }
$active_stmt = $conn->prepare("SELECT id FROM rumah_ibadah WHERE id = ? AND deleted_at IS NULL LIMIT 1");
$active_stmt->bind_param('i', $id);
$active_stmt->execute();
$active_row = $active_stmt->get_result()->fetch_assoc();
$active_stmt->close();
if (!$active_row) {
http_response_code(404);
echo json_encode(['status' => 'error', 'message' => 'Data tidak ditemukan atau sudah dihapus']); exit;
}
// Cek operator yang terkait
$stmt = $conn->prepare(
"SELECT nama_lengkap FROM users WHERE ibadah_id = ? AND is_active = 1 LIMIT 5"
);
$stmt->bind_param('i', $id);
$stmt->execute();
$ops_result = $stmt->get_result();
$operators = [];
while ($op = $ops_result->fetch_assoc()) $operators[] = $op['nama_lengkap'];
$stmt->close();
// Jika belum konfirmasi dan ada operator terkait, kembalikan warning
$confirmed = ($_POST['confirmed'] ?? '0') === '1';
if (!$confirmed && count($operators) > 0) {
echo json_encode([
'status' => 'warning',
'operators' => $operators,
'message' => 'Rumah ibadah ini dikaitkan dengan akun Operator: ' . implode(', ', $operators)
. '. Operator tidak akan bisa login sampai dikaitkan ke rumah ibadah lain.',
]);
exit;
}
$conn->begin_transaction();
try {
// Soft delete
$stmt = $conn->prepare("UPDATE rumah_ibadah SET deleted_at = NOW() WHERE id = ? AND deleted_at IS NULL");
if (!$stmt) {
throw new RuntimeException('prepare delete failed: ' . $conn->error);
}
$stmt->bind_param('i', $id);
if (!$stmt->execute()) {
throw new RuntimeException('delete failed: ' . $stmt->error);
}
$deleted = $stmt->affected_rows > 0;
$stmt->close();
if (!$deleted) {
$conn->rollback();
http_response_code(404);
echo json_encode(['status' => 'error', 'message' => 'Data tidak ditemukan atau sudah dihapus']);
$conn->close();
exit;
}
$recalc = $conn->query("SELECT id, lat, lng FROM penduduk_miskin WHERE is_active=1 AND deleted_at IS NULL");
if (!$recalc) {
throw new RuntimeException('read penduduk failed: ' . $conn->error);
}
while ($warga = $recalc->fetch_assoc()) {
_recalc_proximity($conn, $warga['id'], $warga['lat'], $warga['lng']);
}
$conn->commit();
echo json_encode(['status' => 'success', 'message' => 'Rumah ibadah berhasil dihapus']);
} catch (Throwable $e) {
$conn->rollback();
error_log('ibadah/hapus transaction failed: ' . $e->getMessage());
http_response_code(500);
echo json_encode(['status' => 'error', 'message' => 'Gagal menghapus rumah ibadah.']);
}
function _recalc_proximity($conn, $penduduk_id, $lat, $lng) {
$p = calc_proximity($conn, (float)$lat, (float)$lng);
$s = $conn->prepare(
"UPDATE penduduk_miskin SET ibadah_id=?, jarak_m=?, is_blank_spot=? WHERE id=?"
);
if (!$s) {
throw new RuntimeException('prepare recalc failed: ' . $conn->error);
}
$s->bind_param('idii', $p['ibadah_id'], $p['jarak_m'], $p['is_blank_spot'], $penduduk_id);
if (!$s->execute()) {
throw new RuntimeException('recalc update failed: ' . $s->error);
}
$s->close();
}
$conn->close();
@@ -0,0 +1,51 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('administrator');
require_csrf();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Method not allowed']); exit;
}
$conn->begin_transaction();
try {
$warga_list = $conn->query(
"SELECT id, lat, lng FROM penduduk_miskin WHERE is_active=1 AND deleted_at IS NULL"
);
if (!$warga_list) {
throw new RuntimeException('read penduduk failed: ' . $conn->error);
}
$updated = 0;
while ($warga = $warga_list->fetch_assoc()) {
$p = calc_proximity($conn, (float)$warga['lat'], (float)$warga['lng']);
$s = $conn->prepare(
"UPDATE penduduk_miskin SET ibadah_id=?, jarak_m=?, is_blank_spot=? WHERE id=?"
);
if (!$s) {
throw new RuntimeException('prepare recalc failed: ' . $conn->error);
}
$s->bind_param('idii', $p['ibadah_id'], $p['jarak_m'], $p['is_blank_spot'], $warga['id']);
if (!$s->execute()) {
throw new RuntimeException('recalc update failed: ' . $s->error);
}
$s->close();
$updated++;
}
$conn->commit();
echo json_encode([
'status' => 'success',
'updated' => $updated,
'message' => "$updated data penduduk berhasil diperbarui",
]);
} catch (Throwable $e) {
$conn->rollback();
error_log('ibadah/recalculate transaction failed: ' . $e->getMessage());
http_response_code(500);
echo json_encode(['status' => 'error', 'message' => 'Gagal menghitung ulang proximity.']);
}
$conn->close();
@@ -0,0 +1,48 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../includes/validation.php';
require_once '../../koneksi.php';
require_auth('administrator');
require_csrf();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Method not allowed']); exit;
}
$nama = trim($_POST['nama'] ?? '');
$jenis = trim($_POST['jenis'] ?? 'Masjid');
$alamat = trim($_POST['alamat'] ?? '');
$kontak = trim($_POST['kontak'] ?? '');
$coord = validate_lat_lng($_POST['lat'] ?? null, $_POST['lng'] ?? null);
if (!$coord['ok']) {
echo json_encode(['status' => 'error', 'message' => $coord['message']]); exit;
}
$lat = $coord['lat'];
$lng = $coord['lng'];
$radius = (int) ($_POST['radius_m'] ?? 500);
if (!$nama) {
echo json_encode(['status' => 'error', 'message' => 'Nama ibadah tidak boleh kosong']); exit;
}
if ($radius < 100 || $radius > 5000) {
echo json_encode(['status' => 'error', 'message' => 'Radius minimum 100 meter, maksimum 5.000 meter']); exit;
}
$valid_jenis = ['Masjid','Mushola','Gereja','Pura','Vihara','Klenteng'];
if (!in_array($jenis, $valid_jenis)) $jenis = 'Masjid';
$stmt = $conn->prepare(
"INSERT INTO rumah_ibadah (nama, jenis, alamat, lat, lng, radius_m, kontak) VALUES (?,?,?,?,?,?,?)"
);
$stmt->bind_param('sssddis', $nama, $jenis, $alamat, $lat, $lng, $radius, $kontak);
if ($stmt->execute()) {
echo json_encode(['status' => 'success', 'message' => 'Data berhasil disimpan',
'data' => ['id'=>$conn->insert_id,'nama'=>$nama,'jenis'=>$jenis,
'alamat'=>$alamat,'kontak'=>$kontak,'lat'=>$lat,'lng'=>$lng,'radius_m'=>$radius]]);
} else {
echo json_encode(['status' => 'error', 'message' => 'Gagal menyimpan: '.$stmt->error]);
}
$stmt->close(); $conn->close();
@@ -0,0 +1,90 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../includes/validation.php';
require_once '../../koneksi.php';
require_auth('administrator');
require_csrf();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Method not allowed']); exit;
}
$id = (int) ($_POST['id'] ?? 0);
$nama = trim( $_POST['nama'] ?? '');
$jenis = trim( $_POST['jenis'] ?? 'Masjid');
$alamat = trim( $_POST['alamat'] ?? '');
$kontak = trim( $_POST['kontak'] ?? '');
$coord = validate_lat_lng($_POST['lat'] ?? null, $_POST['lng'] ?? null);
if (!$coord['ok']) {
echo json_encode(['status' => 'error', 'message' => $coord['message']]);
$conn->close(); exit;
}
$lat = $coord['lat'];
$lng = $coord['lng'];
$radius = (int) ($_POST['radius_m'] ?? 500);
$valid_jenis = ['Masjid', 'Mushola', 'Gereja', 'Pura', 'Vihara', 'Klenteng'];
if (!$id) { echo json_encode(['status' => 'error', 'message' => 'ID tidak valid']); exit; }
if (!$nama) { echo json_encode(['status' => 'error', 'message' => 'Nama wajib diisi']); exit; }
if (!in_array($jenis, $valid_jenis)) { echo json_encode(['status' => 'error', 'message' => 'Jenis tidak valid']); exit; }
if ($radius < 100 || $radius > 5000) { echo json_encode(['status' => 'error', 'message' => 'Radius minimum 100 meter, maksimum 5.000 meter']); exit; }
$active_stmt = $conn->prepare("SELECT id FROM rumah_ibadah WHERE id = ? AND deleted_at IS NULL LIMIT 1");
$active_stmt->bind_param('i', $id);
$active_stmt->execute();
$active_row = $active_stmt->get_result()->fetch_assoc();
$active_stmt->close();
if (!$active_row) {
http_response_code(404);
echo json_encode(['status' => 'error', 'message' => 'Data tidak ditemukan atau sudah dihapus']);
$conn->close(); exit;
}
$conn->begin_transaction();
try {
$stmt = $conn->prepare(
"UPDATE rumah_ibadah SET nama=?, jenis=?, alamat=?, kontak=?, lat=?, lng=?, radius_m=? WHERE id=? AND deleted_at IS NULL"
);
if (!$stmt) {
throw new RuntimeException('prepare update failed: ' . $conn->error);
}
$stmt->bind_param('ssssddii', $nama, $jenis, $alamat, $kontak, $lat, $lng, $radius, $id);
if (!$stmt->execute()) {
throw new RuntimeException('update failed: ' . $stmt->error);
}
$changed = $stmt->affected_rows > 0;
$stmt->close();
// Recalculate proximity for all active penduduk (radius may have changed)
if ($changed) {
$warga = $conn->query("SELECT id, lat, lng FROM penduduk_miskin WHERE is_active=1 AND deleted_at IS NULL");
if (!$warga) {
throw new RuntimeException('read penduduk failed: ' . $conn->error);
}
while ($w = $warga->fetch_assoc()) {
if ($w['lat'] === null || $w['lng'] === null) continue;
$p = calc_proximity($conn, (float)$w['lat'], (float)$w['lng']);
$s = $conn->prepare("UPDATE penduduk_miskin SET ibadah_id=?, jarak_m=?, is_blank_spot=? WHERE id=?");
if (!$s) {
throw new RuntimeException('prepare recalc failed: ' . $conn->error);
}
$s->bind_param('idii', $p['ibadah_id'], $p['jarak_m'], $p['is_blank_spot'], $w['id']);
if (!$s->execute()) {
throw new RuntimeException('recalc update failed: ' . $s->error);
}
$s->close();
}
}
$conn->commit();
echo json_encode(['status' => 'success', 'message' => 'Rumah ibadah berhasil diperbarui']);
} catch (Throwable $e) {
$conn->rollback();
error_log('ibadah/update transaction failed: ' . $e->getMessage());
http_response_code(500);
echo json_encode(['status' => 'error', 'message' => 'Gagal memproses perubahan rumah ibadah.']);
}
$conn->close();
@@ -0,0 +1,44 @@
<?php
// api/ibadah/update_kontak.php — Update kontak rumah ibadah
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('administrator');
require_csrf();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
exit;
}
$id = (int) ($_POST['id'] ?? 0);
$kontak = trim($_POST['kontak'] ?? '');
if (!$id) {
echo json_encode(['status' => 'error', 'message' => 'ID tidak valid']);
exit;
}
$active_stmt = $conn->prepare("SELECT id FROM rumah_ibadah WHERE id = ? AND deleted_at IS NULL LIMIT 1");
$active_stmt->bind_param('i', $id);
$active_stmt->execute();
$active_row = $active_stmt->get_result()->fetch_assoc();
$active_stmt->close();
if (!$active_row) {
http_response_code(404);
echo json_encode(['status' => 'error', 'message' => 'Data tidak ditemukan atau sudah dihapus']);
exit;
}
$stmt = $conn->prepare("UPDATE rumah_ibadah SET kontak = ? WHERE id = ? AND deleted_at IS NULL");
$stmt->bind_param('si', $kontak, $id);
if ($stmt->execute()) {
echo json_encode(['status' => 'success', 'message' => 'Kontak berhasil diperbarui']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Gagal mengupdate kontak: ' . $stmt->error]);
}
$stmt->close();
$conn->close();
@@ -0,0 +1,84 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../includes/validation.php';
require_once '../../koneksi.php';
require_auth('administrator');
require_csrf();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
exit;
}
$id = (int) ($_POST['id'] ?? 0);
$coord = validate_lat_lng($_POST['lat'] ?? null, $_POST['lng'] ?? null);
if (!$coord['ok']) {
echo json_encode(['status' => 'error', 'message' => $coord['message']]);
exit;
}
$lat = $coord['lat'];
$lng = $coord['lng'];
if (!$id) {
echo json_encode(['status' => 'error', 'message' => 'ID tidak valid']);
exit;
}
$active_stmt = $conn->prepare("SELECT id FROM rumah_ibadah WHERE id = ? AND deleted_at IS NULL LIMIT 1");
$active_stmt->bind_param('i', $id);
$active_stmt->execute();
$active_row = $active_stmt->get_result()->fetch_assoc();
$active_stmt->close();
if (!$active_row) {
http_response_code(404);
echo json_encode(['status' => 'error', 'message' => 'Data tidak ditemukan atau sudah dihapus']);
exit;
}
$conn->begin_transaction();
try {
$stmt = $conn->prepare("UPDATE rumah_ibadah SET lat = ?, lng = ? WHERE id = ? AND deleted_at IS NULL");
if (!$stmt) {
throw new RuntimeException('prepare update failed: ' . $conn->error);
}
$stmt->bind_param('ddi', $lat, $lng, $id);
if (!$stmt->execute()) {
throw new RuntimeException('update failed: ' . $stmt->error);
}
$changed = $stmt->affected_rows > 0;
$stmt->close();
// Recalculate proximity for all active penduduk
if ($changed) {
$warga_list = $conn->query(
"SELECT id, lat, lng FROM penduduk_miskin WHERE is_active=1 AND deleted_at IS NULL"
);
if (!$warga_list) {
throw new RuntimeException('read penduduk failed: ' . $conn->error);
}
while ($warga = $warga_list->fetch_assoc()) {
$p = calc_proximity($conn, (float)$warga['lat'], (float)$warga['lng']);
$s = $conn->prepare("UPDATE penduduk_miskin SET ibadah_id=?, jarak_m=?, is_blank_spot=? WHERE id=?");
if (!$s) {
throw new RuntimeException('prepare recalc failed: ' . $conn->error);
}
$s->bind_param('idii', $p['ibadah_id'], $p['jarak_m'], $p['is_blank_spot'], $warga['id']);
if (!$s->execute()) {
throw new RuntimeException('recalc update failed: ' . $s->error);
}
$s->close();
}
}
$conn->commit();
echo json_encode(['status' => 'success', 'message' => 'Posisi berhasil diperbarui']);
} catch (Throwable $e) {
$conn->rollback();
error_log('ibadah/update_posisi transaction failed: ' . $e->getMessage());
http_response_code(500);
echo json_encode(['status' => 'error', 'message' => 'Gagal memproses perubahan posisi.']);
}
$conn->close();
@@ -0,0 +1,77 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('administrator');
require_csrf();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Method not allowed']); exit;
}
$id = (int) ($_POST['id'] ?? 0);
$radius = (int) ($_POST['radius_m'] ?? 500);
if (!$id) { echo json_encode(['status' => 'error', 'message' => 'ID tidak valid']); exit; }
if ($radius < 100 || $radius > 5000) {
echo json_encode(['status' => 'error', 'message' => 'Radius minimum 100 meter, maksimum 5.000 meter']); exit;
}
$active_stmt = $conn->prepare("SELECT id FROM rumah_ibadah WHERE id = ? AND deleted_at IS NULL LIMIT 1");
$active_stmt->bind_param('i', $id);
$active_stmt->execute();
$active_row = $active_stmt->get_result()->fetch_assoc();
$active_stmt->close();
if (!$active_row) {
http_response_code(404);
echo json_encode(['status' => 'error', 'message' => 'Data tidak ditemukan atau sudah dihapus']);
exit;
}
$conn->begin_transaction();
try {
$stmt = $conn->prepare("UPDATE rumah_ibadah SET radius_m = ? WHERE id = ? AND deleted_at IS NULL");
if (!$stmt) {
throw new RuntimeException('prepare update failed: ' . $conn->error);
}
$stmt->bind_param('ii', $radius, $id);
if (!$stmt->execute()) {
throw new RuntimeException('update failed: ' . $stmt->error);
}
$changed = $stmt->affected_rows > 0;
$stmt->close();
// Recalculate proximity for all active penduduk
if ($changed) {
$warga_list = $conn->query(
"SELECT id, lat, lng FROM penduduk_miskin WHERE is_active=1 AND deleted_at IS NULL"
);
if (!$warga_list) {
throw new RuntimeException('read penduduk failed: ' . $conn->error);
}
while ($warga = $warga_list->fetch_assoc()) {
$p = calc_proximity($conn, (float)$warga['lat'], (float)$warga['lng']);
$s = $conn->prepare("UPDATE penduduk_miskin SET ibadah_id=?, jarak_m=?, is_blank_spot=? WHERE id=?");
if (!$s) {
throw new RuntimeException('prepare recalc failed: ' . $conn->error);
}
$s->bind_param('idii', $p['ibadah_id'], $p['jarak_m'], $p['is_blank_spot'], $warga['id']);
if (!$s->execute()) {
throw new RuntimeException('recalc update failed: ' . $s->error);
}
$s->close();
}
}
$conn->commit();
echo json_encode(['status' => 'success', 'message' => 'Radius berhasil diperbarui', 'radius_m' => $radius]);
} catch (Throwable $e) {
$conn->rollback();
error_log('ibadah/update_radius transaction failed: ' . $e->getMessage());
http_response_code(500);
echo json_encode(['status' => 'error', 'message' => 'Gagal memproses perubahan radius.']);
}
$conn->close();
+189
View File
@@ -0,0 +1,189 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../includes/validation.php';
require_once '../../koneksi.php';
require_auth('administrator');
require_csrf();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
exit;
}
$mode = trim($_POST['mode'] ?? 'preview'); // 'preview' | 'import'
$max_rows = 500;
$file = $_FILES['csv_file'] ?? null;
if (!$file || empty($file['tmp_name'])) {
echo json_encode(['status' => 'error', 'message' => 'File CSV tidak ditemukan']);
exit;
}
if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
echo json_encode(['status' => 'error', 'message' => 'Upload CSV gagal']);
exit;
}
$max_bytes = 2 * 1024 * 1024;
if (($file['size'] ?? 0) <= 0 || $file['size'] > $max_bytes) {
echo json_encode(['status' => 'error', 'message' => 'Ukuran CSV maksimal 2 MB']);
exit;
}
$ext = strtolower(pathinfo($file['name'] ?? '', PATHINFO_EXTENSION));
if ($ext !== 'csv') {
echo json_encode(['status' => 'error', 'message' => 'File harus berformat .csv']);
exit;
}
$handle = fopen($file['tmp_name'], 'r');
if (!$handle) {
echo json_encode(['status' => 'error', 'message' => 'Gagal membuka file']);
exit;
}
// Deteksi dan lewati BOM UTF-8
$bom = fread($handle, 3);
if ($bom !== "\xEF\xBB\xBF") rewind($handle);
$header = fgetcsv($handle);
if (!$header) {
echo json_encode(['status' => 'error', 'message' => 'File kosong atau format salah']);
exit;
}
$header = array_map(fn($h) => strtolower(trim($h)), $header);
$required_cols = ['nama_kk', 'jumlah_jiwa', 'kategori', 'lat', 'lng'];
foreach ($required_cols as $col) {
if (!in_array($col, $header)) {
echo json_encode([
'status' => 'error',
'message' => "Kolom '$col' tidak ditemukan. Gunakan template yang disediakan.",
]);
exit;
}
}
$col = array_flip($header);
$rows_ok = [];
$rows_error = [];
$row_num = 1;
while (($raw = fgetcsv($handle)) !== false) {
$row_num++;
if ($row_num > $max_rows + 1) {
$rows_error[] = ['row' => $row_num, 'error' => 'Batas 500 baris terlampaui'];
continue;
}
if (count($raw) < count($header)) {
$rows_error[] = ['row' => $row_num, 'error' => 'Jumlah kolom tidak sesuai'];
continue;
}
$get = fn($name) => isset($col[$name]) ? trim($raw[$col[$name]] ?? '') : '';
$nama_kk = $get('nama_kk');
$nik = $get('nik');
$jumlah_jiwa = max(1, (int)$get('jumlah_jiwa'));
$kategori = $get('kategori');
$alamat = $get('alamat');
$catatan = $get('catatan');
$lat_raw = $get('lat');
$lng_raw = $get('lng');
$errors = [];
if (!$nama_kk) $errors[] = 'nama_kk kosong';
$coord = validate_lat_lng($lat_raw, $lng_raw);
if (!$coord['ok']) {
$errors[] = $coord['message'];
} else {
$lat = $coord['lat'];
$lng = $coord['lng'];
}
$valid_kat = ['Sangat Miskin', 'Miskin', 'Hampir Miskin'];
if (!in_array($kategori, $valid_kat)) {
if ($kategori === '') $kategori = 'Miskin';
else $errors[] = "kategori '$kategori' tidak valid";
}
if ($nik !== '' && !preg_match('/^\d{16}$/', $nik)) {
$errors[] = 'NIK harus 16 digit jika diisi';
}
if ($errors) {
$rows_error[] = ['row' => $row_num, 'nama_kk' => $nama_kk, 'error' => implode('; ', $errors)];
continue;
}
$rows_ok[] = compact('nama_kk', 'nik', 'jumlah_jiwa', 'kategori', 'alamat', 'catatan', 'lat', 'lng');
}
fclose($handle);
if ($mode === 'preview') {
echo json_encode([
'status' => 'success',
'total_ok' => count($rows_ok),
'total_error' => count($rows_error),
'preview' => array_slice($rows_ok, 0, 10),
'errors' => $rows_error,
]);
exit;
}
// Mode import: INSERT semua baris valid
$imported = 0;
$skipped = 0;
$status_verif = 'Terverifikasi';
$verified_by = get_user_id();
$verified_at = date('Y-m-d H:i:s');
foreach ($rows_ok as $r) {
// Cek duplikat NIK pada semua data, termasuk arsip/inactive.
if ($r['nik'] !== '') {
$chk = $conn->prepare(
"SELECT id FROM penduduk_miskin WHERE nik=? LIMIT 1"
);
$chk->bind_param('s', $r['nik']);
$chk->execute();
if ($chk->get_result()->num_rows > 0) {
$skipped++;
$chk->close();
continue;
}
$chk->close();
}
// PRD-correct proximity (sama dengan simpan.php)
$p = calc_proximity($conn, $r['lat'], $r['lng']);
$nik_val = $r['nik'] !== '' ? $r['nik'] : null;
$stmt = $conn->prepare(
"INSERT INTO penduduk_miskin
(nama_kk, nik, jumlah_jiwa, kategori, alamat, catatan, lat, lng, ibadah_id, jarak_m, is_blank_spot,
status_verifikasi, verified_by, verified_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
);
$stmt->bind_param(
'ssisssddidisis',
$r['nama_kk'], $nik_val, $r['jumlah_jiwa'], $r['kategori'],
$r['alamat'], $r['catatan'], $r['lat'], $r['lng'],
$p['ibadah_id'], $p['jarak_m'], $p['is_blank_spot'],
$status_verif, $verified_by, $verified_at
);
if ($stmt->execute()) $imported++;
$stmt->close();
}
echo json_encode([
'status' => 'success',
'imported' => $imported,
'skipped' => $skipped,
'message' => "$imported baris berhasil diimport sebagai Terverifikasi, $skipped dilewati (NIK pernah terdaftar/duplikat)",
]);
$conn->close();
@@ -0,0 +1,15 @@
<?php
require_once '../../config.php';
require_once '../../auth/helper.php';
require_auth('administrator');
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="template_penduduk_miskin.csv"');
$out = fopen('php://output', 'w');
fwrite($out, "\xEF\xBB\xBF"); // BOM UTF-8 agar Excel membaca dengan benar
fputcsv($out, ['nama_kk', 'nik', 'jumlah_jiwa', 'kategori', 'alamat', 'catatan', 'lat', 'lng']);
fputcsv($out, ['Budi Santoso', '3271011234567890', '4', 'Miskin', 'Jl. Merdeka No. 1', 'Rumah semi permanen', '-0.0557', '109.3487']);
fputcsv($out, ['Siti Rahayu', '', '2', 'Sangat Miskin', 'Jl. Damai No. 5', '', '-0.0560', '109.3490']);
fclose($out);
@@ -0,0 +1,49 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('operator');
$penduduk_id = (int)($_GET['penduduk_id'] ?? 0);
if ($penduduk_id <= 0) {
echo json_encode(['status' => 'error', 'message' => 'Parameter tidak valid.']);
exit;
}
// Operator hanya boleh lihat kebutuhan warga dalam ibadah-nya
if (!has_role('administrator')) {
$op_ibadah = get_ibadah_id();
$stmt = $conn->prepare(
"SELECT ibadah_id FROM penduduk_miskin
WHERE id=? AND is_active=1 AND deleted_at IS NULL"
);
$stmt->bind_param('i', $penduduk_id);
$stmt->execute();
$r = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (!$r || (int)$r['ibadah_id'] !== (int)$op_ibadah) {
http_response_code(403);
echo json_encode(['status' => 'error', 'message' => 'Akses ditolak.']);
exit;
}
}
$stmt = $conn->prepare("
SELECT k.id, k.kategori, k.deskripsi, k.status, k.created_at,
u.nama_lengkap AS created_by_nama
FROM kebutuhan k
LEFT JOIN users u ON u.id = k.created_by
WHERE k.penduduk_id = ?
ORDER BY k.created_at DESC
");
$stmt->bind_param('i', $penduduk_id);
$stmt->execute();
$res = $stmt->get_result();
$rows = [];
while ($r = $res->fetch_assoc()) $rows[] = $r;
$stmt->close();
echo json_encode(['status' => 'success', 'data' => $rows]);
$conn->close();
@@ -0,0 +1,65 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('operator');
require_csrf();
$penduduk_id = (int)($_POST['penduduk_id'] ?? 0);
$kategori = trim($_POST['kategori'] ?? '');
$deskripsi = trim($_POST['deskripsi'] ?? '');
$valid_kategori = ['Sembako','Biaya Sekolah','Biaya Kesehatan','Modal Usaha',
'Renovasi Rumah','Perlengkapan Rumah','Pakaian','Lainnya'];
if ($penduduk_id <= 0 || !in_array($kategori, $valid_kategori, true)) {
echo json_encode(['status' => 'error', 'message' => 'Parameter tidak valid.']);
exit;
}
// Verifikasi akses warga
$stmt = $conn->prepare(
"SELECT ibadah_id, status_verifikasi FROM penduduk_miskin
WHERE id=? AND is_active=1 AND deleted_at IS NULL"
);
$stmt->bind_param('i', $penduduk_id);
$stmt->execute();
$warga = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (!$warga) {
echo json_encode(['status' => 'error', 'message' => 'Data warga tidak ditemukan.']);
exit;
}
if (!has_role('administrator')) {
$op_ibadah = get_ibadah_id();
if ($warga['ibadah_id'] === null || (int)$warga['ibadah_id'] !== (int)$op_ibadah) {
http_response_code(403);
echo json_encode(['status' => 'error', 'message' => 'Anda tidak memiliki akses untuk warga ini.']);
exit;
}
}
if ($warga['status_verifikasi'] !== 'Terverifikasi') {
echo json_encode(['status' => 'error', 'message' => 'Data warga belum terverifikasi']);
exit;
}
$user_id = (int)$_SESSION['user_id'];
$deskripsi = $deskripsi !== '' ? mb_substr($deskripsi, 0, 300) : null;
$stmt = $conn->prepare(
"INSERT INTO kebutuhan (penduduk_id, kategori, deskripsi, created_by) VALUES (?,?,?,?)"
);
$stmt->bind_param('issi', $penduduk_id, $kategori, $deskripsi, $user_id);
if ($stmt->execute()) {
echo json_encode(['status' => 'success', 'id' => $conn->insert_id]);
} else {
echo json_encode(['status' => 'error', 'message' => 'Gagal menyimpan: ' . $stmt->error]);
}
$stmt->close();
$conn->close();
@@ -0,0 +1,73 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('operator');
require_csrf();
$id = (int)($_POST['id'] ?? 0);
$status = trim($_POST['status'] ?? '');
$catatan = trim($_POST['catatan'] ?? '');
$valid_status = ['Belum Terpenuhi', 'Dalam Proses', 'Terpenuhi'];
if ($id <= 0 || !in_array($status, $valid_status, true)) {
echo json_encode(['status' => 'error', 'message' => 'Parameter tidak valid.']);
exit;
}
// Ambil kebutuhan + ibadah warga untuk cek akses
$stmt = $conn->prepare("
SELECT k.id, k.status AS status_lama, pm.ibadah_id, pm.status_verifikasi
FROM kebutuhan k
JOIN penduduk_miskin pm ON pm.id = k.penduduk_id
AND pm.is_active = 1
AND pm.deleted_at IS NULL
WHERE k.id = ?
");
$stmt->bind_param('i', $id);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (!$row) {
echo json_encode(['status' => 'error', 'message' => 'Data tidak ditemukan.']);
exit;
}
if (!has_role('administrator')) {
$op_ibadah = get_ibadah_id();
if ($row['ibadah_id'] === null || (int)$row['ibadah_id'] !== (int)$op_ibadah) {
http_response_code(403);
echo json_encode(['status' => 'error', 'message' => 'Akses ditolak.']);
exit;
}
}
if ($row['status_verifikasi'] !== 'Terverifikasi') {
echo json_encode(['status' => 'error', 'message' => 'Data warga belum terverifikasi']);
exit;
}
$user_id = (int)$_SESSION['user_id'];
$old_status = $row['status_lama'];
$stmt = $conn->prepare(
"UPDATE kebutuhan SET status=?, updated_by=?, updated_at=NOW() WHERE id=?"
);
$stmt->bind_param('sii', $status, $user_id, $id);
$stmt->execute();
$stmt->close();
$stmt = $conn->prepare(
"INSERT INTO riwayat_kebutuhan (kebutuhan_id, operator_id, status_lama, status_baru, catatan)
VALUES (?,?,?,?,?)"
);
$catatan_val = $catatan !== '' ? $catatan : null;
$stmt->bind_param('iisss', $id, $user_id, $old_status, $status, $catatan_val);
$stmt->execute();
$stmt->close();
echo json_encode(['status' => 'success', 'status_baru' => $status]);
$conn->close();
+102
View File
@@ -0,0 +1,102 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
if (!is_logged_in()) {
echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
exit;
}
$is_admin = has_role('administrator');
$is_op = has_role('operator');
$items = [];
// ── Admin only ───────────────────────────────────────────────────────
if ($is_admin) {
$r = $conn->query("
SELECT COUNT(*) AS n FROM penduduk_miskin
WHERE is_active=1 AND deleted_at IS NULL AND status_verifikasi='Pending'
");
if ($r && ($n = (int)$r->fetch_assoc()['n'])) {
$items[] = [
'type' => 'pending_verif',
'label' => "$n penduduk menunggu verifikasi",
'count' => $n,
'page' => 'pages/penduduk.php',
'icon' => 'clock',
];
}
$de = $conn->query(
"SELECT 1 FROM information_schema.TABLES
WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='kontak_donatur' LIMIT 1"
)->num_rows > 0;
if ($de) {
$r = $conn->query("SELECT COUNT(*) AS n FROM kontak_donatur WHERE is_read=0");
if ($r && ($n = (int)$r->fetch_assoc()['n'])) {
$items[] = [
'type' => 'donatur',
'label' => "$n pesan donatur belum dibaca",
'count' => $n,
'page' => 'pages/kebutuhan.php',
'icon' => 'mail',
];
}
}
}
// ── Admin + Operator ────────────────────────────────────────────────
if ($is_admin || $is_op) {
$scope = '';
if ($is_op && !$is_admin) {
$iid = (int)get_ibadah_id();
$scope = $iid > 0 ? " AND pm.ibadah_id = $iid" : " AND 1=0";
}
$ke = $conn->query(
"SELECT 1 FROM information_schema.TABLES
WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='kebutuhan' LIMIT 1"
)->num_rows > 0;
if ($ke) {
$r = $conn->query("
SELECT COUNT(*) AS n FROM kebutuhan k
JOIN penduduk_miskin pm
ON pm.id = k.penduduk_id AND pm.is_active=1 AND pm.deleted_at IS NULL
WHERE k.status = 'Belum Terpenuhi' $scope
");
if ($r && ($n = (int)$r->fetch_assoc()['n'])) {
$items[] = [
'type' => 'kebutuhan',
'label' => "$n kebutuhan belum terpenuhi",
'count' => $n,
'page' => 'pages/kebutuhan.php',
'icon' => 'heart',
];
}
}
$r = $conn->query("
SELECT COUNT(*) AS n FROM penduduk_miskin pm
WHERE pm.is_active=1 AND pm.deleted_at IS NULL
AND pm.status_verifikasi = 'Terverifikasi'
AND pm.status_bantuan = 'Belum Ditangani'
$scope
");
if ($r && ($n = (int)$r->fetch_assoc()['n'])) {
$items[] = [
'type' => 'belum_ditangani',
'label' => "$n data belum ditangani",
'count' => $n,
'page' => 'pages/status-bantuan.php',
'icon' => 'clipboard-list',
];
}
}
echo json_encode([
'status' => 'success',
'items' => $items,
'total' => array_sum(array_column($items, 'count')),
]);
+35
View File
@@ -0,0 +1,35 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../koneksi.php';
// Publik — tidak perlu auth
// Agregasi kebutuhan Belum Terpenuhi per kategori × rumah ibadah (area)
$rows = $conn->query("
SELECT
k.kategori,
COALESCE(ri.nama, 'Di luar radius ibadah') AS area,
COUNT(DISTINCT k.penduduk_id) AS jumlah_kk
FROM kebutuhan k
JOIN penduduk_miskin pm ON pm.id = k.penduduk_id
AND pm.is_active = 1
AND pm.deleted_at IS NULL
AND pm.status_verifikasi = 'Terverifikasi'
LEFT JOIN rumah_ibadah ri ON ri.id = pm.ibadah_id AND ri.deleted_at IS NULL
WHERE k.status = 'Belum Terpenuhi'
GROUP BY k.kategori, pm.ibadah_id, ri.nama
ORDER BY jumlah_kk DESC, k.kategori ASC
");
$data = [];
while ($r = $rows->fetch_assoc()) {
$data[] = [
'kategori' => $r['kategori'],
'area' => $r['area'],
'jumlah_kk' => (int)$r['jumlah_kk'],
];
}
echo json_encode(['status' => 'success', 'data' => $data]);
$conn->close();
@@ -0,0 +1,61 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('administrator');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
require_csrf();
$action = trim($_POST['action'] ?? 'mark_all');
$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
if ($action === 'hapus') {
if ($id <= 0) {
echo json_encode(['status' => 'error', 'message' => 'ID tidak valid.']);
$conn->close(); exit;
}
$stmt = $conn->prepare("DELETE FROM kontak_donatur WHERE id=?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->close();
echo json_encode(['status' => 'success']);
$conn->close(); exit;
}
if ($action === 'mark_one') {
if ($id <= 0) {
echo json_encode(['status' => 'error', 'message' => 'ID tidak valid.']);
$conn->close(); exit;
}
$stmt = $conn->prepare("UPDATE kontak_donatur SET is_read=1 WHERE id=?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->close();
echo json_encode(['status' => 'success']);
$conn->close(); exit;
}
// mark_all — default, also handles legacy calls without action param
$conn->query("UPDATE kontak_donatur SET is_read=1 WHERE is_read=0");
echo json_encode(['status' => 'success', 'marked_read' => $conn->affected_rows]);
$conn->close();
exit;
}
$rows = $conn->query("
SELECT id, nama, kontak, kategori_minat, pesan, is_read, created_at
FROM kontak_donatur
ORDER BY is_read ASC, created_at DESC
LIMIT 100
");
$data = [];
while ($r = $rows->fetch_assoc()) {
$data[] = $r;
}
echo json_encode(['status' => 'success', 'data' => $data]);
$conn->close();
@@ -0,0 +1,66 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../koneksi.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Method not allowed.']);
exit;
}
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
$now = time();
$rate_window = 60;
$client_ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$rate_dir = dirname(__DIR__, 2) . '/tmp/donor-rate-limit';
if (!is_dir($rate_dir)) {
@mkdir($rate_dir, 0775, true);
}
$rate_file = $rate_dir . '/' . hash('sha256', $client_ip) . '.txt';
$last_submit = max(
(int)($_SESSION['donor_last_submit'] ?? 0),
is_file($rate_file) ? (int)filemtime($rate_file) : 0
);
if ($last_submit > 0 && ($now - $last_submit) < $rate_window) {
http_response_code(429);
echo json_encode([
'status' => 'error',
'message' => 'Terlalu sering mengirim. Coba lagi dalam 1 menit.',
]);
exit;
}
$nama = trim($_POST['nama'] ?? '');
$kontak = trim($_POST['kontak'] ?? '');
$kategori_minat = trim($_POST['kategori_minat'] ?? '');
$pesan = trim($_POST['pesan'] ?? '');
if (!$nama || !$kontak) {
echo json_encode(['status' => 'error', 'message' => 'Nama dan kontak wajib diisi.']);
exit;
}
$valid_kategori = ['Sembako','Biaya Sekolah','Biaya Kesehatan','Modal Usaha',
'Renovasi Rumah','Perlengkapan Rumah','Pakaian','Lainnya'];
$kat = in_array($kategori_minat, $valid_kategori, true) ? $kategori_minat : null;
$pesan_val = $pesan !== '' ? mb_substr($pesan, 0, 1000) : null;
$nama_safe = mb_substr($nama, 0, 150);
$kontak_safe = mb_substr($kontak, 0, 150);
$stmt = $conn->prepare(
"INSERT INTO kontak_donatur (nama, kontak, kategori_minat, pesan) VALUES (?,?,?,?)"
);
$stmt->bind_param('ssss', $nama_safe, $kontak_safe, $kat, $pesan_val);
if ($stmt->execute()) {
$_SESSION['donor_last_submit'] = time();
@file_put_contents($rate_file, (string)$_SESSION['donor_last_submit'], LOCK_EX);
echo json_encode(['status' => 'success']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Gagal menyimpan.']);
}
$stmt->close();
$conn->close();
+105
View File
@@ -0,0 +1,105 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
$is_authenticated = is_logged_in();
$is_privileged = $is_authenticated && has_role('operator');
$role = $is_authenticated ? get_role() : 'viewer';
$is_admin = $is_authenticated && has_role('administrator');
$can_see_sensitive = $is_privileged;
$can_see_coords = $is_privileged;
$public_verif_sql = $is_privileged ? "" : " AND pm.status_verifikasi = 'Terverifikasi'";
// Publik: hanya data Terverifikasi
// Operator: semua data ibadahnya sendiri (semua status)
// Admin: semua data tanpa filter
$operator_scope_sql = '';
if ($is_privileged && !$is_admin) {
$linked_ibadah_id = get_ibadah_id();
$operator_scope_sql = $linked_ibadah_id
? ' AND pm.ibadah_id = ' . (int)$linked_ibadah_id
: ' AND 1 = 0';
// operator lihat semua status miliknya (termasuk Pending/Ditolak)
}
// Cek apakah tabel kebutuhan sudah ada (migrasi F14 sudah dijalankan)
$kebutuhan_exists = $conn->query(
"SELECT 1 FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'kebutuhan' LIMIT 1"
)->num_rows > 0;
if ($kebutuhan_exists) {
$sql = "
SELECT
pm.id, pm.nama_kk, pm.nik, pm.kategori, pm.alamat, pm.catatan,
pm.jumlah_jiwa, pm.lat, pm.lng, pm.ibadah_id, pm.jarak_m,
pm.is_blank_spot, pm.status_bantuan, pm.status_verifikasi, pm.created_at,
ri.nama AS nama_ibadah,
ri.jenis AS jenis_ibadah,
COALESCE(kstat.kebutuhan_open, 0) AS kebutuhan_open,
COALESCE(kstat.kebutuhan_proses, 0) AS kebutuhan_proses,
COALESCE(kstat.kebutuhan_terpenuhi,0) AS kebutuhan_terpenuhi,
kstat.kebutuhan_kategori_open
FROM penduduk_miskin pm
LEFT JOIN rumah_ibadah ri ON pm.ibadah_id = ri.id AND ri.deleted_at IS NULL
LEFT JOIN (
SELECT
penduduk_id,
SUM(CASE WHEN status='Belum Terpenuhi' THEN 1 ELSE 0 END) AS kebutuhan_open,
SUM(CASE WHEN status='Dalam Proses' THEN 1 ELSE 0 END) AS kebutuhan_proses,
SUM(CASE WHEN status='Terpenuhi' THEN 1 ELSE 0 END) AS kebutuhan_terpenuhi,
GROUP_CONCAT(DISTINCT CASE WHEN status='Belum Terpenuhi' THEN kategori ELSE NULL END
ORDER BY kategori SEPARATOR ',') AS kebutuhan_kategori_open
FROM kebutuhan
GROUP BY penduduk_id
) kstat ON kstat.penduduk_id = pm.id
WHERE pm.is_active = 1 AND pm.deleted_at IS NULL {$public_verif_sql} {$operator_scope_sql}
ORDER BY pm.created_at DESC
";
} else {
$sql = "
SELECT
pm.id, pm.nama_kk, pm.nik, pm.kategori, pm.alamat, pm.catatan,
pm.jumlah_jiwa, pm.lat, pm.lng, pm.ibadah_id, pm.jarak_m,
pm.is_blank_spot, pm.status_bantuan, pm.status_verifikasi, pm.created_at,
ri.nama AS nama_ibadah,
ri.jenis AS jenis_ibadah,
0 AS kebutuhan_open, 0 AS kebutuhan_proses,
0 AS kebutuhan_terpenuhi, NULL AS kebutuhan_kategori_open
FROM penduduk_miskin pm
LEFT JOIN rumah_ibadah ri ON pm.ibadah_id = ri.id AND ri.deleted_at IS NULL
WHERE pm.is_active = 1 AND pm.deleted_at IS NULL {$public_verif_sql} {$operator_scope_sql}
ORDER BY pm.created_at DESC
";
}
$result = $conn->query($sql);
if (!$result) {
error_log('penduduk/ambil query failed: ' . $conn->error);
echo json_encode(['status' => 'error', 'message' => 'Gagal memuat data penduduk.']);
exit;
}
$data = [];
while ($row = $result->fetch_assoc()) {
if (!$can_see_sensitive) {
// Publik tidak boleh lihat data pribadi
$row['nik'] = null;
$row['nama_kk'] = null;
$row['alamat'] = null;
$row['catatan'] = null;
}
if (!$can_see_coords) {
// Publik tidak boleh lihat koordinat rumah warga
$row['lat'] = null;
$row['lng'] = null;
}
$data[] = $row;
}
echo json_encode(['status' => 'success', 'total' => count($data), 'data' => $data]);
$conn->close();
@@ -0,0 +1,28 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('administrator');
// Return inactive (is_active=0) AND soft-deleted warga for admin audit
$stmt = $conn->prepare("
SELECT pm.id, pm.nama_kk, pm.jumlah_jiwa, pm.kategori, pm.status_bantuan,
pm.is_active, pm.deleted_at,
ri.nama AS nama_ibadah,
(SELECT COUNT(*) FROM riwayat_bantuan WHERE penduduk_id = pm.id) AS jml_riwayat
FROM penduduk_miskin pm
LEFT JOIN rumah_ibadah ri ON ri.id = pm.ibadah_id
WHERE pm.is_active = 0 OR pm.deleted_at IS NOT NULL
ORDER BY COALESCE(pm.deleted_at, pm.updated_at) DESC
LIMIT 200
");
$stmt->execute();
$res = $stmt->get_result();
$rows = [];
while ($r = $res->fetch_assoc()) $rows[] = $r;
$stmt->close();
echo json_encode(['status' => 'success', 'data' => $rows]);
$conn->close();
@@ -0,0 +1,32 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('administrator');
require_csrf();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
exit;
}
$id = (int) ($_POST['id'] ?? 0);
if (!$id) {
echo json_encode(['status' => 'error', 'message' => 'ID tidak valid']);
exit;
}
$stmt = $conn->prepare(
"UPDATE penduduk_miskin SET deleted_at = NOW() WHERE id = ? AND deleted_at IS NULL"
);
$stmt->bind_param('i', $id);
if ($stmt->execute() && $stmt->affected_rows > 0) {
echo json_encode(['status' => 'success', 'message' => 'Data berhasil dihapus']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Data tidak ditemukan atau sudah dihapus']);
}
$stmt->close();
$conn->close();
@@ -0,0 +1,29 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('administrator');
require_csrf();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Method not allowed']); exit;
}
$id = (int)($_POST['id'] ?? 0);
if (!$id) {
echo json_encode(['status' => 'error', 'message' => 'ID tidak valid']); exit;
}
$stmt = $conn->prepare(
"UPDATE penduduk_miskin SET is_active = 0 WHERE id = ? AND is_active = 1 AND deleted_at IS NULL"
);
$stmt->bind_param('i', $id);
if ($stmt->execute() && $stmt->affected_rows > 0) {
echo json_encode(['status' => 'success', 'message' => 'Warga berhasil dinonaktifkan']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Data tidak ditemukan atau sudah tidak aktif']);
}
$stmt->close();
$conn->close();
@@ -0,0 +1,50 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('operator');
$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
echo json_encode(['status' => 'error', 'message' => 'ID tidak valid.']);
exit;
}
// Operator hanya boleh lihat riwayat warga dalam ibadah-nya
if (!has_role('administrator')) {
$op_ibadah = get_ibadah_id();
$stmt = $conn->prepare(
"SELECT ibadah_id FROM penduduk_miskin
WHERE id=? AND is_active=1 AND deleted_at IS NULL"
);
$stmt->bind_param('i', $id);
$stmt->execute();
$r = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (!$r || (int)$r['ibadah_id'] !== (int)$op_ibadah) {
http_response_code(403);
echo json_encode(['status' => 'error', 'message' => 'Akses ditolak.']);
exit;
}
}
$stmt = $conn->prepare("
SELECT r.id, r.status_lama, r.status_baru, r.catatan, r.created_at,
u.nama_lengkap AS user_nama
FROM riwayat_bantuan r
LEFT JOIN users u ON u.id = r.operator_id
WHERE r.penduduk_id = ?
ORDER BY r.created_at DESC
LIMIT 20
");
$stmt->bind_param('i', $id);
$stmt->execute();
$res = $stmt->get_result();
$rows = [];
while ($r = $res->fetch_assoc()) $rows[] = $r;
$stmt->close();
echo json_encode(['status' => 'success', 'data' => $rows]);
$conn->close();
@@ -0,0 +1,143 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../includes/validation.php';
require_once '../../koneksi.php';
require_auth('operator');
require_csrf();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
exit;
}
$nama_kk = trim($_POST['nama_kk'] ?? '');
$nik = trim($_POST['nik'] ?? '');
$jumlah_jiwa = max(1, (int)($_POST['jumlah_jiwa'] ?? 1));
$kategori = trim($_POST['kategori'] ?? 'Miskin');
$alamat = trim($_POST['alamat'] ?? '');
$catatan = trim($_POST['catatan'] ?? '');
$coord = validate_lat_lng($_POST['lat'] ?? null, $_POST['lng'] ?? null);
if (!$coord['ok']) {
echo json_encode(['status' => 'error', 'message' => $coord['message']]);
exit;
}
$lat = $coord['lat'];
$lng = $coord['lng'];
if (!$nama_kk) {
echo json_encode(['status' => 'error', 'message' => 'Nama Kepala Keluarga tidak boleh kosong']);
exit;
}
$valid_kategori = ['Sangat Miskin', 'Miskin', 'Hampir Miskin'];
if (!in_array($kategori, $valid_kategori)) $kategori = 'Miskin';
// Validasi & dedup NIK
$nik_val = $nik !== '' ? $nik : null;
if ($nik_val !== null) {
if (!preg_match('/^\d{16}$/', $nik_val)) {
echo json_encode(['status' => 'error', 'message' => 'NIK harus 16 digit angka']);
exit;
}
$stmt_nik = $conn->prepare(
"SELECT id, nama_kk FROM penduduk_miskin
WHERE nik = ? LIMIT 1"
);
$stmt_nik->bind_param('s', $nik_val);
$stmt_nik->execute();
$existing = $stmt_nik->get_result()->fetch_assoc();
$stmt_nik->close();
if ($existing) {
echo json_encode([
'status' => 'error',
'message' => "NIK {$nik_val} pernah terdaftar atas nama {$existing['nama_kk']}. Cek arsip sebelum menambah ulang.",
]);
exit;
}
}
// PRD-correct proximity calculation
$p = calc_proximity($conn, $lat, $lng);
if (!has_role('administrator')) {
$op_ibadah_id = get_ibadah_id();
if (!$op_ibadah_id) {
http_response_code(403);
echo json_encode([
'status' => 'error',
'message' => 'Operator belum dikaitkan dengan rumah ibadah'
]);
exit;
}
if (empty($p['ibadah_id']) || (int)$p['ibadah_id'] !== $op_ibadah_id) {
http_response_code(403);
echo json_encode([
'status' => 'error',
'message' => 'Lokasi warga berada di luar wilayah rumah ibadah operator'
]);
exit;
}
}
// Admin langsung Terverifikasi; operator masuk Pending untuk direview
$status_verif = has_role('administrator') ? 'Terverifikasi' : 'Pending';
$verified_by = has_role('administrator') ? get_user_id() : null;
$verified_at = has_role('administrator') ? date('Y-m-d H:i:s') : null;
$stmt = $conn->prepare(
"INSERT INTO penduduk_miskin
(nama_kk, nik, jumlah_jiwa, kategori, alamat, catatan, lat, lng,
ibadah_id, jarak_m, is_blank_spot, status_verifikasi, verified_by, verified_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
);
$stmt->bind_param(
'ssisssddidisis',
$nama_kk, $nik_val, $jumlah_jiwa, $kategori, $alamat, $catatan,
$lat, $lng, $p['ibadah_id'], $p['jarak_m'], $p['is_blank_spot'],
$status_verif, $verified_by, $verified_at
);
if ($stmt->execute()) {
$new_id = $conn->insert_id;
$nama_ibadah = null;
$jenis_ibadah = null;
if ($p['ibadah_id']) {
$s2 = $conn->prepare("SELECT nama, jenis FROM rumah_ibadah WHERE id = ? AND deleted_at IS NULL");
$s2->bind_param('i', $p['ibadah_id']);
$s2->execute();
$ri = $s2->get_result()->fetch_assoc();
$s2->close();
if ($ri) { $nama_ibadah = $ri['nama']; $jenis_ibadah = $ri['jenis']; }
}
echo json_encode([
'status' => 'success',
'message' => 'Data berhasil disimpan',
'data' => [
'id' => $new_id,
'nama_kk' => $nama_kk,
'nik' => $nik_val,
'kategori' => $kategori,
'alamat' => $alamat,
'catatan' => $catatan,
'jumlah_jiwa' => $jumlah_jiwa,
'lat' => $lat,
'lng' => $lng,
'ibadah_id' => $p['ibadah_id'],
'jarak_m' => $p['jarak_m'],
'is_blank_spot' => $p['is_blank_spot'],
'status_verifikasi' => $status_verif,
'nama_ibadah' => $nama_ibadah,
'jenis_ibadah' => $jenis_ibadah,
]
]);
} else {
error_log('penduduk/simpan insert failed: ' . $stmt->error);
echo json_encode(['status' => 'error', 'message' => 'Gagal menyimpan data penduduk.']);
}
$stmt->close();
$conn->close();
@@ -0,0 +1,93 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('operator');
require_csrf();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
exit;
}
$id = (int)($_POST['id'] ?? 0);
$nama_kk = trim($_POST['nama_kk'] ?? '');
$nik = trim($_POST['nik'] ?? '');
$jumlah_jiwa = max(1, (int)($_POST['jumlah_jiwa'] ?? 1));
$kategori = trim($_POST['kategori'] ?? 'Miskin');
$alamat = trim($_POST['alamat'] ?? '');
$catatan = trim($_POST['catatan'] ?? '');
if ($id <= 0 || !$nama_kk) {
echo json_encode(['status' => 'error', 'message' => 'ID dan nama kepala keluarga wajib diisi.']);
exit;
}
$valid_kategori = ['Sangat Miskin', 'Miskin', 'Hampir Miskin'];
if (!in_array($kategori, $valid_kategori)) $kategori = 'Miskin';
// Ambil data existing untuk scope check
$stmt = $conn->prepare(
"SELECT ibadah_id FROM penduduk_miskin WHERE id=? AND is_active=1 AND deleted_at IS NULL"
);
$stmt->bind_param('i', $id);
$stmt->execute();
$warga = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (!$warga) {
echo json_encode(['status' => 'error', 'message' => 'Data warga tidak ditemukan.']);
exit;
}
// Operator hanya boleh edit warga dalam ibadah-nya
if (!has_role('administrator')) {
$op_ibadah = get_ibadah_id();
if ($warga['ibadah_id'] === null || (int)$warga['ibadah_id'] !== (int)$op_ibadah) {
http_response_code(403);
echo json_encode(['status' => 'error', 'message' => 'Anda tidak memiliki akses untuk warga ini.']);
exit;
}
}
// Validasi & dedup NIK (exclude diri sendiri)
$nik_val = $nik !== '' ? $nik : null;
if ($nik_val !== null) {
if (!preg_match('/^\d{16}$/', $nik_val)) {
echo json_encode(['status' => 'error', 'message' => 'NIK harus 16 digit angka.']);
exit;
}
$stmt_nik = $conn->prepare(
"SELECT id, nama_kk FROM penduduk_miskin WHERE nik=? AND id != ? LIMIT 1"
);
$stmt_nik->bind_param('si', $nik_val, $id);
$stmt_nik->execute();
$existing = $stmt_nik->get_result()->fetch_assoc();
$stmt_nik->close();
if ($existing) {
echo json_encode([
'status' => 'error',
'message' => "NIK {$nik_val} sudah terdaftar atas nama {$existing['nama_kk']}.",
]);
exit;
}
}
$catatan_val = $catatan !== '' ? $catatan : null;
$stmt = $conn->prepare(
"UPDATE penduduk_miskin
SET nama_kk=?, nik=?, jumlah_jiwa=?, kategori=?, alamat=?, catatan=?, updated_at=NOW()
WHERE id=? AND is_active=1 AND deleted_at IS NULL"
);
$stmt->bind_param('ssisssi', $nama_kk, $nik_val, $jumlah_jiwa, $kategori, $alamat, $catatan_val, $id);
if ($stmt->execute() && $stmt->affected_rows >= 0) {
echo json_encode(['status' => 'success', 'message' => 'Data berhasil diperbarui.']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Gagal memperbarui data: ' . $stmt->error]);
}
$stmt->close();
$conn->close();
@@ -0,0 +1,89 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../includes/validation.php';
require_once '../../koneksi.php';
require_auth('operator');
require_csrf();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
exit;
}
$id = (int) ($_POST['id'] ?? 0);
$coord = validate_lat_lng($_POST['lat'] ?? null, $_POST['lng'] ?? null);
if (!$coord['ok']) {
echo json_encode(['status' => 'error', 'message' => $coord['message']]);
exit;
}
$lat = $coord['lat'];
$lng = $coord['lng'];
if (!$id) {
echo json_encode(['status' => 'error', 'message' => 'ID tidak valid']);
exit;
}
if (!has_role('administrator')) {
$linked_ibadah_id = get_ibadah_id();
if (!$linked_ibadah_id) {
http_response_code(403);
echo json_encode(['status' => 'error', 'message' => 'Akses ditolak untuk data warga ini']);
exit;
}
$scope = $conn->prepare(
"SELECT id FROM penduduk_miskin
WHERE id = ? AND ibadah_id = ? AND is_active = 1 AND deleted_at IS NULL"
);
$scope->bind_param('ii', $id, $linked_ibadah_id);
$scope->execute();
$allowed = $scope->get_result()->fetch_assoc();
$scope->close();
if (!$allowed) {
http_response_code(403);
echo json_encode(['status' => 'error', 'message' => 'Akses ditolak untuk data warga ini']);
exit;
}
}
// PRD-correct proximity calculation
$p = calc_proximity($conn, $lat, $lng);
if (!has_role('administrator')) {
if (empty($p['ibadah_id']) || (int)$p['ibadah_id'] !== $linked_ibadah_id) {
http_response_code(403);
echo json_encode([
'status' => 'error',
'message' => 'Posisi baru berada di luar wilayah rumah ibadah operator'
]);
exit;
}
}
$stmt = $conn->prepare(
"UPDATE penduduk_miskin
SET lat = ?, lng = ?, ibadah_id = ?, jarak_m = ?, is_blank_spot = ?
WHERE id = ? AND deleted_at IS NULL"
);
$stmt->bind_param('ddidii', $lat, $lng, $p['ibadah_id'], $p['jarak_m'], $p['is_blank_spot'], $id);
if ($stmt->execute() && $stmt->affected_rows > 0) {
echo json_encode([
'status' => 'success',
'message' => 'Posisi berhasil diperbarui',
'data' => [
'ibadah_id' => $p['ibadah_id'],
'jarak_m' => $p['jarak_m'],
'is_blank_spot' => $p['is_blank_spot'],
]
]);
} else {
echo json_encode(['status' => 'error', 'message' => 'Gagal update atau data tidak ditemukan']);
}
$stmt->close();
$conn->close();
@@ -0,0 +1,68 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('operator');
require_csrf();
$id = (int)($_POST['id'] ?? 0);
$status = trim($_POST['status'] ?? '');
$catatan = trim($_POST['catatan'] ?? '');
$allowed = ['Belum Ditangani', 'Dalam Proses', 'Sudah Ditangani'];
if ($id <= 0 || !in_array($status, $allowed, true)) {
echo json_encode(['status' => 'error', 'message' => 'Parameter tidak valid.']);
exit;
}
$stmt = $conn->prepare(
"SELECT id, ibadah_id, status_bantuan, status_verifikasi FROM penduduk_miskin
WHERE id=? AND is_active=1 AND deleted_at IS NULL"
);
$stmt->bind_param('i', $id);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (!$row) {
echo json_encode(['status' => 'error', 'message' => 'Data tidak ditemukan.']);
exit;
}
// Operator hanya boleh update warga dalam ibadah-nya sendiri
if (!has_role('administrator')) {
$op_ibadah = get_ibadah_id();
if ($row['ibadah_id'] === null || (int)$row['ibadah_id'] !== (int)$op_ibadah) {
http_response_code(403);
echo json_encode(['status' => 'error', 'message' => 'Anda tidak memiliki akses untuk warga ini.']);
exit;
}
}
if ($row['status_verifikasi'] !== 'Terverifikasi') {
echo json_encode(['status' => 'error', 'message' => 'Data warga belum terverifikasi']);
exit;
}
$old_status = $row['status_bantuan'];
$user_id = (int)$_SESSION['user_id'];
$stmt = $conn->prepare(
"UPDATE penduduk_miskin SET status_bantuan=?, updated_at=NOW() WHERE id=?"
);
$stmt->bind_param('si', $status, $id);
$stmt->execute();
$stmt->close();
$stmt = $conn->prepare(
"INSERT INTO riwayat_bantuan (penduduk_id, operator_id, status_lama, status_baru, catatan)
VALUES (?,?,?,?,?)"
);
$stmt->bind_param('iisss', $id, $user_id, $old_status, $status, $catatan);
$stmt->execute();
$stmt->close();
echo json_encode(['status' => 'success', 'status_baru' => $status]);
$conn->close();
@@ -0,0 +1,43 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('administrator');
require_csrf();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
exit;
}
$id = (int)trim($_POST['id'] ?? 0);
$aksi = trim($_POST['aksi'] ?? ''); // 'approve' | 'reject'
$catatan = trim($_POST['catatan'] ?? '');
if ($id <= 0 || !in_array($aksi, ['approve', 'reject'], true)) {
echo json_encode(['status' => 'error', 'message' => 'Parameter tidak valid.']);
exit;
}
$status_baru = $aksi === 'approve' ? 'Terverifikasi' : 'Ditolak';
$admin_id = get_user_id();
$catatan_val = $catatan !== '' ? mb_substr($catatan, 0, 500) : null;
$stmt = $conn->prepare("
UPDATE penduduk_miskin
SET status_verifikasi = ?,
verified_by = ?,
verified_at = NOW(),
catatan_verifikasi = ?
WHERE id = ? AND deleted_at IS NULL
");
$stmt->bind_param('sisi', $status_baru, $admin_id, $catatan_val, $id);
if ($stmt->execute() && $stmt->affected_rows > 0) {
echo json_encode(['status' => 'success', 'status_verifikasi' => $status_baru, 'id' => $id]);
} else {
echo json_encode(['status' => 'error', 'message' => 'Data tidak ditemukan atau tidak ada perubahan.']);
}
$stmt->close();
$conn->close();
+143
View File
@@ -0,0 +1,143 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
$is_auth = is_logged_in();
$is_privileged = $is_auth && has_role('operator');
$is_admin = $is_auth && has_role('administrator');
$public_verif_sql = $is_privileged ? "" : " AND status_verifikasi = 'Terverifikasi'";
$public_verif_pm_sql = $is_privileged ? "" : " AND pm.status_verifikasi = 'Terverifikasi'";
$operator_ibadah_id = null;
$operator_scope_sql = '';
$operator_scope_pm_sql = '';
if ($is_privileged && !$is_admin) {
$operator_ibadah_id = (int)get_ibadah_id();
if ($operator_ibadah_id > 0) {
$operator_scope_sql = " AND ibadah_id = {$operator_ibadah_id}";
$operator_scope_pm_sql = " AND pm.ibadah_id = {$operator_ibadah_id}";
} else {
$operator_scope_sql = " AND 1 = 0";
$operator_scope_pm_sql = " AND 1 = 0";
}
}
// ── Statistik dasar (semua role) ────────────────────────────────────────────
$r = $conn->query("
SELECT
COUNT(*) AS total_kk,
COALESCE(SUM(jumlah_jiwa), 0) AS total_jiwa,
COALESCE(SUM(CASE WHEN is_blank_spot=1 THEN jumlah_jiwa ELSE 0 END), 0) AS jiwa_blank_spot,
COALESCE(SUM(CASE WHEN is_blank_spot=0 THEN jumlah_jiwa ELSE 0 END), 0) AS jiwa_terjangkau
FROM penduduk_miskin pm
WHERE pm.is_active = 1 AND pm.deleted_at IS NULL {$public_verif_pm_sql} {$operator_scope_pm_sql}
");
$base = $r->fetch_assoc();
$total_jiwa = (int)$base['total_jiwa'];
$jiwa_terjangkau = (int)$base['jiwa_terjangkau'];
$jiwa_blank_spot = (int)$base['jiwa_blank_spot'];
$pct_cakupan = $total_jiwa > 0 ? round($jiwa_terjangkau / $total_jiwa * 100, 1) : 0;
// ── Sebaran kategori ────────────────────────────────────────────────────────
$kat_rows = $conn->query("
SELECT kategori, COUNT(*) AS jml_kk, COALESCE(SUM(jumlah_jiwa),0) AS jml_jiwa
FROM penduduk_miskin pm
WHERE pm.is_active=1 AND pm.deleted_at IS NULL {$public_verif_pm_sql} {$operator_scope_pm_sql}
GROUP BY kategori
");
$kategori = [];
while ($row = $kat_rows->fetch_assoc()) $kategori[] = $row;
// ── Total ibadah aktif ──────────────────────────────────────────────────────
if ($is_privileged && !$is_admin) {
$total_ibadah = $operator_ibadah_id
? (int)$conn->query("SELECT COUNT(*) AS n FROM rumah_ibadah WHERE deleted_at IS NULL AND id = {$operator_ibadah_id}")->fetch_assoc()['n']
: 0;
} else {
$total_ibadah = (int)$conn->query(
"SELECT COUNT(*) AS n FROM rumah_ibadah WHERE deleted_at IS NULL"
)->fetch_assoc()['n'];
}
$payload = [
'total_ibadah' => $total_ibadah,
'total_kk' => (int)$base['total_kk'],
'total_jiwa' => $total_jiwa,
'jiwa_terjangkau' => $jiwa_terjangkau,
'jiwa_blank_spot' => $jiwa_blank_spot,
'pct_cakupan' => $pct_cakupan,
'kategori' => $kategori,
];
// ── Tabel rekapitulasi per ibadah (admin only) ──────────────────────────────
if ($is_admin) {
$rekap_rows = $conn->query("
SELECT
ri.id,
ri.nama,
ri.jenis,
COUNT(pm.id) AS jml_kk,
COALESCE(SUM(pm.jumlah_jiwa), 0) AS jml_jiwa,
COALESCE(SUM(CASE WHEN pm.status_bantuan='Sudah Ditangani' THEN 1 ELSE 0 END), 0) AS jml_ditangani
FROM rumah_ibadah ri
LEFT JOIN penduduk_miskin pm
ON pm.ibadah_id = ri.id
AND pm.is_active = 1
AND pm.deleted_at IS NULL
WHERE ri.deleted_at IS NULL
GROUP BY ri.id
ORDER BY jml_jiwa DESC
");
$rekap = [];
while ($row = $rekap_rows->fetch_assoc()) $rekap[] = $row;
$payload['rekap_ibadah'] = $rekap;
}
// ── Kebutuhan stats (hanya jika tabel sudah ada) ───────────────────────────
$kebutuhan_exists = $conn->query(
"SELECT 1 FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'kebutuhan' LIMIT 1"
)->num_rows > 0;
$payload['kk_kebutuhan_open'] = 0;
if ($kebutuhan_exists) {
$payload['kk_kebutuhan_open'] = (int)$conn->query("
SELECT COUNT(DISTINCT penduduk_id) AS n
FROM kebutuhan k
JOIN penduduk_miskin pm ON pm.id = k.penduduk_id
AND pm.is_active = 1
AND pm.deleted_at IS NULL
{$public_verif_pm_sql}
{$operator_scope_pm_sql}
WHERE k.status = 'Belum Terpenuhi'
")->fetch_assoc()['n'];
if ($is_admin) {
$rekap_kat = $conn->query("
SELECT kategori,
COUNT(*) AS total,
SUM(CASE WHEN status='Belum Terpenuhi' THEN 1 ELSE 0 END) AS belum,
SUM(CASE WHEN status='Dalam Proses' THEN 1 ELSE 0 END) AS proses,
SUM(CASE WHEN status='Terpenuhi' THEN 1 ELSE 0 END) AS terpenuhi
FROM kebutuhan
GROUP BY kategori ORDER BY belum DESC, kategori ASC
");
$rekap_kebutuhan = [];
while ($r = $rekap_kat->fetch_assoc()) $rekap_kebutuhan[] = $r;
$payload['rekap_kebutuhan'] = $rekap_kebutuhan;
$donatur_exists = $conn->query(
"SELECT 1 FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'kontak_donatur' LIMIT 1"
)->num_rows > 0;
$payload['donatur_unread'] = $donatur_exists
? (int)$conn->query("SELECT COUNT(*) AS n FROM kontak_donatur WHERE is_read=0")->fetch_assoc()['n']
: 0;
}
}
echo json_encode(['status' => 'success', 'data' => $payload]);
$conn->close();
+21
View File
@@ -0,0 +1,21 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('administrator');
$sql = "
SELECT u.id, u.username, u.nama_lengkap, u.role, u.ibadah_id,
u.is_active, u.must_change_password, u.created_at,
ri.nama AS nama_ibadah
FROM users u
LEFT JOIN rumah_ibadah ri ON u.ibadah_id = ri.id AND ri.deleted_at IS NULL
ORDER BY u.created_at DESC
";
$result = $conn->query($sql);
$data = [];
while ($row = $result->fetch_assoc()) $data[] = $row;
echo json_encode(['status' => 'success', 'data' => $data]);
$conn->close();
@@ -0,0 +1,38 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('administrator');
require_csrf();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Method not allowed']); exit;
}
$id = (int) ($_POST['id'] ?? 0);
if (!$id) { echo json_encode(['status' => 'error', 'message' => 'ID tidak valid']); exit; }
$chars = 'abcdefghjkmnpqrstuvwxyz';
$digits = '23456789';
$temp_pw = '';
for ($i = 0; $i < 4; $i++) $temp_pw .= $chars[random_int(0, strlen($chars)-1)];
for ($i = 0; $i < 4; $i++) $temp_pw .= $digits[random_int(0, strlen($digits)-1)];
$temp_pw = str_shuffle($temp_pw);
$hash = password_hash($temp_pw, PASSWORD_BCRYPT);
$stmt = $conn->prepare(
"UPDATE users SET password=?, must_change_password=1, login_attempts=0, locked_until=NULL WHERE id=?"
);
$stmt->bind_param('si', $hash, $id);
if ($stmt->execute()) {
echo json_encode([
'status' => 'success',
'temp_password' => $temp_pw,
'message' => 'Password direset. Sampaikan password sementara ini ke pengguna secara langsung.',
]);
} else {
echo json_encode(['status' => 'error', 'message' => $stmt->error]);
}
$stmt->close(); $conn->close();
+57
View File
@@ -0,0 +1,57 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('administrator');
require_csrf();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Method not allowed']); exit;
}
$username = trim($_POST['username'] ?? '');
$nama_lengkap = trim($_POST['nama_lengkap'] ?? '');
$password = trim($_POST['password'] ?? '');
$role = trim($_POST['role'] ?? '');
$ibadah_id = ($_POST['ibadah_id'] ?? '') !== '' ? (int)$_POST['ibadah_id'] : null;
$valid_roles = ['administrator', 'operator', 'viewer'];
if (!$username || !$nama_lengkap || !$password || !in_array($role, $valid_roles)) {
echo json_encode(['status' => 'error', 'message' => 'Data tidak lengkap atau role tidak valid']); exit;
}
if (strlen($password) < 8 || !preg_match('/[a-zA-Z]/', $password) || !preg_match('/[0-9]/', $password)) {
echo json_encode(['status' => 'error', 'message' => 'Password min 8 karakter, kombinasi huruf dan angka']); exit;
}
if ($role === 'operator' && !$ibadah_id) {
echo json_encode(['status' => 'error', 'message' => 'Operator harus dikaitkan ke rumah ibadah']); exit;
}
if ($role !== 'operator') {
$ibadah_id = null;
}
if ($role === 'operator') {
$ri_stmt = $conn->prepare("SELECT id FROM rumah_ibadah WHERE id = ? AND deleted_at IS NULL LIMIT 1");
$ri_stmt->bind_param('i', $ibadah_id);
$ri_stmt->execute();
$ri = $ri_stmt->get_result()->fetch_assoc();
$ri_stmt->close();
if (!$ri) {
echo json_encode(['status' => 'error', 'message' => 'Rumah ibadah operator tidak valid atau sudah dihapus']); exit;
}
}
$hash = password_hash($password, PASSWORD_BCRYPT);
$stmt = $conn->prepare(
"INSERT INTO users (username, nama_lengkap, password, role, ibadah_id, must_change_password)
VALUES (?, ?, ?, ?, ?, 1)"
);
$stmt->bind_param('ssssi', $username, $nama_lengkap, $hash, $role, $ibadah_id);
if ($stmt->execute()) {
echo json_encode(['status' => 'success', 'message' => 'Akun berhasil dibuat', 'id' => $conn->insert_id]);
} else {
$msg = str_contains($conn->error, 'Duplicate') ? "Username '$username' sudah digunakan" : $conn->error;
echo json_encode(['status' => 'error', 'message' => $msg]);
}
$stmt->close(); $conn->close();
@@ -0,0 +1,59 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('administrator');
require_csrf();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Method not allowed']); exit;
}
$id = (int) ($_POST['id'] ?? 0);
if (!$id) { echo json_encode(['status' => 'error', 'message' => 'ID tidak valid']); exit; }
if ($id === get_user_id()) {
echo json_encode(['status' => 'error', 'message' => 'Tidak dapat menonaktifkan akun sendiri']); exit;
}
$target_stmt = $conn->prepare("SELECT role, is_active FROM users WHERE id = ? LIMIT 1");
$target_stmt->bind_param('i', $id);
$target_stmt->execute();
$target = $target_stmt->get_result()->fetch_assoc();
$target_stmt->close();
if (!$target) {
echo json_encode(['status' => 'error', 'message' => 'Akun tidak ditemukan']); exit;
}
if ($target['role'] === 'administrator' && (int)$target['is_active'] === 1) {
$admin_stmt = $conn->prepare(
"SELECT COUNT(*) AS n FROM users WHERE role='administrator' AND is_active=1 AND id <> ?"
);
$admin_stmt->bind_param('i', $id);
$admin_stmt->execute();
$other_admins = (int)$admin_stmt->get_result()->fetch_assoc()['n'];
$admin_stmt->close();
if ($other_admins === 0) {
echo json_encode(['status' => 'error', 'message' => 'Tidak dapat menonaktifkan administrator aktif terakhir']); exit;
}
}
$stmt = $conn->prepare("UPDATE users SET is_active = NOT is_active WHERE id = ?");
$stmt->bind_param('i', $id);
if ($stmt->execute()) {
$s2 = $conn->prepare("SELECT is_active FROM users WHERE id = ?");
$s2->bind_param('i', $id);
$s2->execute();
$r = $s2->get_result()->fetch_assoc();
$s2->close();
echo json_encode([
'status' => 'success',
'is_active' => (int)$r['is_active'],
'message' => $r['is_active'] ? 'Akun diaktifkan' : 'Akun dinonaktifkan',
]);
} else {
echo json_encode(['status' => 'error', 'message' => $stmt->error]);
}
$stmt->close(); $conn->close();
+73
View File
@@ -0,0 +1,73 @@
<?php
header('Content-Type: application/json');
require_once '../../config.php';
require_once '../../auth/helper.php';
require_once '../../koneksi.php';
require_auth('administrator');
require_csrf();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Method not allowed']); exit;
}
$id = (int) ($_POST['id'] ?? 0);
$nama_lengkap = trim($_POST['nama_lengkap'] ?? '');
$role = trim($_POST['role'] ?? '');
$ibadah_id = ($_POST['ibadah_id'] ?? '') !== '' ? (int)$_POST['ibadah_id'] : null;
if (!$id || !$nama_lengkap || !in_array($role, ['administrator','operator','viewer'])) {
echo json_encode(['status' => 'error', 'message' => 'Data tidak valid']); exit;
}
if ($role === 'operator' && !$ibadah_id) {
echo json_encode(['status' => 'error', 'message' => 'Operator harus dikaitkan ke rumah ibadah']); exit;
}
if ($role !== 'operator') {
$ibadah_id = null;
}
$current_stmt = $conn->prepare("SELECT role, is_active FROM users WHERE id = ? LIMIT 1");
$current_stmt->bind_param('i', $id);
$current_stmt->execute();
$current = $current_stmt->get_result()->fetch_assoc();
$current_stmt->close();
if (!$current) {
echo json_encode(['status' => 'error', 'message' => 'Akun tidak ditemukan']); exit;
}
if ($id === get_user_id() && $current['role'] === 'administrator' && $role !== 'administrator') {
echo json_encode(['status' => 'error', 'message' => 'Tidak dapat menurunkan role akun sendiri']); exit;
}
if ($current['role'] === 'administrator' && (int)$current['is_active'] === 1 && $role !== 'administrator') {
$admin_stmt = $conn->prepare(
"SELECT COUNT(*) AS n FROM users WHERE role='administrator' AND is_active=1 AND id <> ?"
);
$admin_stmt->bind_param('i', $id);
$admin_stmt->execute();
$other_admins = (int)$admin_stmt->get_result()->fetch_assoc()['n'];
$admin_stmt->close();
if ($other_admins === 0) {
echo json_encode(['status' => 'error', 'message' => 'Tidak dapat mengubah administrator aktif terakhir']); exit;
}
}
if ($role === 'operator') {
$ri_stmt = $conn->prepare("SELECT id FROM rumah_ibadah WHERE id = ? AND deleted_at IS NULL LIMIT 1");
$ri_stmt->bind_param('i', $ibadah_id);
$ri_stmt->execute();
$ri = $ri_stmt->get_result()->fetch_assoc();
$ri_stmt->close();
if (!$ri) {
echo json_encode(['status' => 'error', 'message' => 'Rumah ibadah operator tidak valid atau sudah dihapus']); exit;
}
}
$stmt = $conn->prepare("UPDATE users SET nama_lengkap=?, role=?, ibadah_id=? WHERE id=?");
$stmt->bind_param('ssii', $nama_lengkap, $role, $ibadah_id, $id);
if ($stmt->execute()) {
echo json_encode(['status' => 'success', 'message' => 'Akun berhasil diperbarui']);
} else {
echo json_encode(['status' => 'error', 'message' => $stmt->error]);
}
$stmt->close(); $conn->close();