<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    echo json_encode(["status" => "error", "pesan" => "Akses ditolak. Silakan login."]);
    exit;
}

header('Content-Type: application/json');

include 'koneksi.php';

$aksi = $_GET['aksi'] ?? 'global';

if ($aksi == 'global') {
    // 1. PERBAIKAN: Menambahkan WHERE status = 'berhasil' agar donasi pending tidak ikut terhitung di index.php
    $resultMasuk = $conn->query("SELECT SUM(nominal) AS total_masuk, COUNT(id) AS jml_donatur FROM donasi_digital WHERE status = 'berhasil'");
    $dataMasuk = $resultMasuk ? $resultMasuk->fetch_assoc() : null;
    $total_donasi = $dataMasuk['total_masuk'] ?? 0;
    $jml_donatur = $dataMasuk['jml_donatur'] ?? 0;

    // 2. Tarik Semua Log Distribusi ke Warga Miskin
    $resultDistribusi = $conn->query("
        SELECT 
            h.id, h.jenis_id, h.tanggal_distribusi, h.nama_penyalur, h.jumlah, h.satuan_custom, h.catatan, 
            w.nama_kk, w.lat, w.lng 
        FROM histori_bantuan h
        JOIN warga_miskin w ON h.warga_id = w.id
        ORDER BY h.tanggal_distribusi DESC
    ");
    
    $log_distribusi = [];
    if ($resultDistribusi) {
        while ($row = $resultDistribusi->fetch_assoc()) {
            $log_distribusi[] = $row;
        }
    }

    echo json_encode([
        "total_donasi" => $total_donasi,
        "jumlah_donatur" => $jml_donatur,
        "log_distribusi" => $log_distribusi
    ]);
}
?>