<?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();

        $totalsStmt = $db->query('
            SELECT
                COUNT(*) AS total_households,
                SUM(CASE WHEN verification_status = \'unverified\' THEN 1 ELSE 0 END) AS unverified_count,
                SUM(CASE WHEN verification_status = \'field_verified\' THEN 1 ELSE 0 END) AS field_verified_count,
                SUM(CASE WHEN verification_status = \'admin_approved\' THEN 1 ELSE 0 END) AS admin_approved_count,
                SUM(CASE WHEN verification_status = \'rejected\' THEN 1 ELSE 0 END) AS rejected_count,
                SUM(CASE WHEN verification_status = \'needs_review\' THEN 1 ELSE 0 END) AS needs_review_count,
                COALESCE(AVG(monthly_income), 0) AS avg_monthly_income
            FROM households
        ');
        $totals = $totalsStmt->fetch(PDO::FETCH_ASSOC);

        $assistanceStmt = $db->query('
            SELECT
                COUNT(*) AS total_distributions,
                COUNT(DISTINCT household_id) AS assisted_households,
                COALESCE(SUM(assistance_value), 0) AS total_assistance_value,
                COALESCE(SUM(CASE WHEN delivery_status = \'delivered\' THEN assistance_value ELSE 0 END), 0) AS delivered_assistance_value
            FROM assistance_distributions
        ');
        $assistance = $assistanceStmt->fetch(PDO::FETCH_ASSOC);

        $verificationStmt = $db->query('
            SELECT
                COUNT(*) AS total_verifications,
                SUM(CASE WHEN DATE(verified_at) >= DATE(\'now\', \'-7 day\') THEN 1 ELSE 0 END) AS verifications_last_7_days,
                COALESCE(AVG(data_confidence_score), 0) AS avg_confidence_score
            FROM verification_logs
        ');
        $verification = $verificationStmt->fetch(PDO::FETCH_ASSOC);

        $topMasjidStmt = $db->query('
            SELECT
                m.id,
                m.name,
                COUNT(h.id) AS household_count
            FROM masjids m
            LEFT JOIN households h ON h.masjid_id = m.id
            GROUP BY m.id, m.name
            ORDER BY household_count DESC, m.name ASC
            LIMIT 5
        ');
        $topMasjidCoverage = $topMasjidStmt->fetchAll(PDO::FETCH_ASSOC);

        echo json_encode([
            'success' => true,
            'summary' => [
                'totals' => $totals,
                'assistance' => $assistance,
                'verification' => $verification,
                'top_masjid_coverage' => $topMasjidCoverage
            ]
        ]);
    } 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']);
}
?>