<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
header('Content-Type: application/json');

require_once 'config.php';

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    try {
        $db = getDB();

        $syncResult = syncNeedPointsToHouseholds($db);
        $computedMissing = ensureHouseholdScoresForAllHouseholds($db);

        $totalStmt = $db->query('SELECT COUNT(*) AS total_households FROM households');
        $totalHouseholds = (int)$totalStmt->fetch(PDO::FETCH_ASSOC)['total_households'];

        $scoreTotalStmt = $db->query('SELECT COUNT(*) AS scored_households FROM household_scores');
        $scoredHouseholds = (int)$scoreTotalStmt->fetch(PDO::FETCH_ASSOC)['scored_households'];

        $assistedStmt = $db->query("\n            SELECT COUNT(DISTINCT household_id) AS assisted_households\n            FROM assistance_distributions\n            WHERE delivery_status = 'delivered'\n        ");
        $assistedHouseholds = (int)$assistedStmt->fetch(PDO::FETCH_ASSOC)['assisted_households'];

        $priorityStmt = $db->query('
            SELECT
                priority_level,
                COUNT(*) AS count
            FROM household_scores hs
            JOIN households h ON h.id = hs.household_id
            WHERE NOT EXISTS (
                SELECT 1
                FROM assistance_distributions ad
                WHERE ad.household_id = hs.household_id
                  AND ad.delivery_status = \'delivered\'
            )
            GROUP BY priority_level
        ');
        $priorityRows = $priorityStmt->fetchAll(PDO::FETCH_ASSOC);

        $priorityCounts = [
            'very_high' => 0,
            'high' => 0,
            'medium' => 0,
            'low' => 0
        ];

        foreach ($priorityRows as $row) {
            $priority = $row['priority_level'];
            $priorityCounts[$priority] = (int)$row['count'];
        }

        $avgStmt = $db->query('
            SELECT
                COALESCE(AVG(skr), 0) AS avg_skr,
                COALESCE(AVG(sag), 0) AS avg_sag,
                COALESCE(AVG(spi), 0) AS avg_spi,
                MAX(computed_at) AS latest_computed_at
            FROM household_scores
        ');
        $averages = $avgStmt->fetch(PDO::FETCH_ASSOC);

        $topStmt = $db->query('
            SELECT
                hs.household_id,
                h.household_code,
                h.head_name,
                hs.spi,
                hs.priority_level
            FROM household_scores hs
            JOIN households h ON h.id = hs.household_id
            WHERE NOT EXISTS (
                SELECT 1
                FROM assistance_distributions ad
                WHERE ad.household_id = hs.household_id
                  AND ad.delivery_status = \'delivered\'
            )
            ORDER BY hs.spi DESC, hs.skr DESC
            LIMIT 5
        ');
        $topPriorities = $topStmt->fetchAll(PDO::FETCH_ASSOC);

        echo json_encode([
            'success' => true,
            'summary' => [
                'total_households' => $totalHouseholds,
                'scored_households' => $scoredHouseholds,
                'assisted_households' => $assistedHouseholds,
                'priority_counts' => $priorityCounts,
                'averages' => $averages,
                'top_priorities' => $topPriorities,
                'score_version' => 'v1',
                'sync_result' => $syncResult,
                'computed_missing_scores' => $computedMissing
            ]
        ]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}
?>