<?php
header('Content-Type: application/json');
require_once 'config.php';

try {
    $db = getDB();

    // Get statistics by area (kelurahan/kecamatan)
    $areaStats = $db->query('
        SELECT 
            pa.id,
            pa.name as area_name,
            pa.area_type,
            COUNT(h.id) as household_count,
            AVG(hs.skr) as avg_poverty_score,
            SUM(CASE WHEN h.verification_status = \'admin_approved\' THEN 1 ELSE 0 END) as verified_count,
            SUM(CASE WHEN ad.delivery_status = \'delivered\' THEN 1 ELSE 0 END) as assisted_count
        FROM pontianak_areas pa
        LEFT JOIN households h ON h.pontianak_area_id = pa.id
        LEFT JOIN household_scores hs ON hs.household_id = h.id
        LEFT JOIN assistance_distributions ad ON ad.household_id = h.id
        GROUP BY pa.id, pa.name, pa.area_type
        ORDER BY household_count DESC
    ')->fetchAll(PDO::FETCH_ASSOC);

    $response = [
        'success' => true,
        'areas' => $areaStats
    ];

    http_response_code(200);
    die(json_encode($response));

} catch (PDOException $e) {
    http_response_code(500);
    die(json_encode(['error' => 'Database error: ' . $e->getMessage()]));
}
