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

// Get current user to restrict access
$user = getCurrentUser();

try {
    $db = getDB();

    // Get actual need points count from database (real poor population data)
    $needPointsStats = $db->query('SELECT COUNT(*) as total FROM need_points')->fetch(PDO::FETCH_ASSOC);
    $totalNeedPoints = (int)$needPointsStats['total'];

    // Get configuration from database: population reference and target nasional
    $configStmt = $db->prepare('SELECT key_value FROM score_metadata WHERE key_name = ? LIMIT 1');
    
    $configStmt->execute(['population_reference']);
    $populationReference = (int)$configStmt->fetchColumn();
    if (!$populationReference || $populationReference <= 0) {
        $populationReference = 288315899;  // Default fallback
    }

    $configStmt->execute(['target_nasional']);
    $targetNasional = (float)$configStmt->fetchColumn();
    if (!$targetNasional || $targetNasional <= 0) {
        $targetNasional = 7.50;  // Default fallback
    }

    // Calculate poverty percentage from real data
    $currentPovertyPercentage = ($totalNeedPoints / $populationReference) * 100;

    $response = [
        'success' => true,
        'charts' => [
            // Chart 1: Absolute population comparison (real data from system)
            'chart1' => [
                'title' => 'Total Penduduk Miskin vs Total Populasi Indonesia',
                'type' => 'bar',
                'labels' => [
                    'Penduduk Miskin',
                    'Total Populasi Indonesia'
                ],
                'data' => [
                    $totalNeedPoints,
                    $populationReference
                ],
                'units' => [
                    'jiwa',
                    'jiwa'
                ]
            ],
            // Chart 2: Percentage comparison against national target (real data)
            'chart2' => [
                'title' => 'Persentase Kemiskinan vs Target Nasional',
                'type' => 'bar',
                'labels' => [
                    'Persentase Kemiskinan',
                    'Target Nasional'
                ],
                'data' => [
                    round($currentPovertyPercentage, 6),
                    $targetNasional
                ],
                'units' => [
                    '%',
                    '%'
                ],
                'current_poverty' => round($currentPovertyPercentage, 6),
                'target' => $targetNasional
            ]
        ],
        'statistics' => [
            'total_need_points' => $totalNeedPoints,
            'population_reference' => $populationReference,
            'current_poverty_percentage' => round($currentPovertyPercentage, 6),
            'national_target' => $targetNasional
        ]
    ];

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

} catch (PDOException $e) {
    http_response_code(500);
    die(json_encode([
        'success' => false,
        'error' => 'Database error: ' . $e->getMessage()
    ]));
} catch (Exception $e) {
    http_response_code(400);
    die(json_encode([
        'success' => false,
        'error' => 'Error: ' . $e->getMessage()
    ]));
}
?>

