<?php
// api/statistik.php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

require_once '../config/db.php';

$stats = [];

// Total rumah ibadah per jenis
$result = $conn->query("SELECT jenis, COUNT(*) as total FROM rumah_ibadah GROUP BY jenis");
if ($result === false) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Gagal memuat statistik. Tabel "rumah_ibadah" tidak ditemukan. Pastikan Anda telah mengimpor berkas database "database/bansos_gis.sql" di phpMyAdmin Anda!'
    ]);
    exit;
}
$ibadah = [];
while ($row = $result->fetch_assoc()) $ibadah[$row['jenis']] = (int)$row['total'];
$stats['rumah_ibadah'] = $ibadah;
$stats['total_ibadah'] = array_sum($ibadah);

// Total rumah warga per kategori
$result = $conn->query("SELECT kategori_kemiskinan, COUNT(*) as total FROM rumah_warga GROUP BY kategori_kemiskinan");
$warga  = [];
while ($row = $result->fetch_assoc()) $warga[$row['kategori_kemiskinan']] = (int)$row['total'];
$stats['kategori_kemiskinan'] = $warga;
$stats['total_warga']         = array_sum($warga);

// Status bantuan
$result = $conn->query("SELECT status_bantuan, COUNT(*) as total FROM rumah_warga GROUP BY status_bantuan");
$bansos = [];
while ($row = $result->fetch_assoc()) $bansos[$row['status_bantuan']] = (int)$row['total'];
$stats['status_bansos'] = $bansos;

// Rekomendasi bantuan
$result = $conn->query("SELECT rekomendasi_bantuan, COUNT(*) as total FROM rumah_warga GROUP BY rekomendasi_bantuan");
$rek    = [];
while ($row = $result->fetch_assoc()) $rek[$row['rekomendasi_bantuan']] = (int)$row['total'];
$stats['rekomendasi_bantuan'] = $rek;

// Total jiwa
$result = $conn->query("SELECT SUM(jumlah_tanggungan) as total FROM rumah_warga");
$row    = $result->fetch_assoc();
$stats['total_jiwa'] = (int)$row['total'];

// Total anggota di DB
$result = $conn->query("SELECT COUNT(*) as total FROM anggota_keluarga");
$row    = $result->fetch_assoc();
$stats['total_anggota_db'] = (int)$row['total'];

// Rata-rata penghasilan
$result = $conn->query("SELECT AVG(penghasilan_bulanan) as avg_ph FROM rumah_warga");
$row    = $result->fetch_assoc();
$stats['rata_penghasilan'] = round((float)$row['avg_ph'], 0);

echo json_encode(['success' => true, 'data' => $stats]);
$conn->close();