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

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

try {
    $db = getDB();

    // Get total households
    $householdTotal = $db->query('SELECT COUNT(*) as count FROM households')->fetch(PDO::FETCH_ASSOC)['count'];

    // Get households by verification status
    $statusBreakdown = $db->query('
        SELECT verification_status, COUNT(*) as count 
        FROM households 
        GROUP BY verification_status
    ')->fetchAll(PDO::FETCH_ASSOC);

    $statusMap = [];
    foreach ($statusBreakdown as $row) {
        $statusMap[$row['verification_status']] = $row['count'];
    }

    // Get average SKR (poverty score)
    $skrAvg = $db->query('
        SELECT 
            AVG(skr) as avg_skr,
            COUNT(*) as scored_count
        FROM household_scores
    ')->fetch(PDO::FETCH_ASSOC);

    // Get households assisted
    $assistedCount = $db->query('
        SELECT COUNT(DISTINCT household_id) as count 
        FROM assistance_distributions 
        WHERE delivery_status = \'delivered\'
    ')->fetch(PDO::FETCH_ASSOC)['count'];

    // Get priority level breakdown
    $priorityBreakdown = $db->query('
        SELECT priority_level, COUNT(*) as count 
        FROM household_scores 
        GROUP BY priority_level
    ')->fetchAll(PDO::FETCH_ASSOC);

    $priorityMap = [];
    foreach ($priorityBreakdown as $row) {
        $priorityMap[$row['priority_level']] = $row['count'];
    }

    // Get assistance type breakdown
    $assistanceTypes = $db->query('
        SELECT 
            assistance_type, 
            COUNT(*) as count,
            SUM(assistance_value) as total_value
        FROM assistance_distributions 
        GROUP BY assistance_type
    ')->fetchAll(PDO::FETCH_ASSOC);

    $response = [
        'success' => true,
        'summary' => [
            'total_households' => $householdTotal,
            'avg_poverty_score' => round($skrAvg['avg_skr'] ?? 0, 2),
            'households_scored' => $skrAvg['scored_count'] ?? 0,
            'households_assisted' => $assistedCount,
            'percentage_assisted' => $householdTotal > 0 ? round(($assistedCount / $householdTotal) * 100, 1) : 0
        ],
        'status_breakdown' => $statusMap,
        'priority_breakdown' => $priorityMap,
        'assistance_by_type' => $assistanceTypes
    ];

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

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