<?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();
        syncNeedPointsToHouseholds($db);
        ensureHouseholdScoresForAllHouseholds($db);

        $scoreCountStmt = $db->query('SELECT COUNT(*) AS count FROM household_scores');
        $scoreCount = (int)$scoreCountStmt->fetch(PDO::FETCH_ASSOC)['count'];

        $sql = '
            SELECT
                hs.household_id,
                hs.skr,
                hs.sag,
                hs.spi,
                hs.priority_level,
                hs.score_version,
                hs.computed_at,
                h.household_code,
                h.head_name,
                h.economic_status,
                h.monthly_income,
                h.dependents_count,
                h.verification_status,
                CASE WHEN EXISTS (
                    SELECT 1
                    FROM assistance_distributions ad
                    WHERE ad.household_id = hs.household_id
                        AND ad.delivery_status = \'delivered\'
                ) THEN 1 ELSE 0 END AS assisted,
                m.name AS masjid_name,
                pa.name AS area_name
            FROM household_scores hs
            JOIN households h ON h.id = hs.household_id
            LEFT JOIN masjids m ON m.id = h.masjid_id
            LEFT JOIN pontianak_areas pa ON pa.id = h.pontianak_area_id
            WHERE 1 = 1
        ';

        $params = [];

        if (isset($_GET['priority_level']) && $_GET['priority_level'] !== '') {
            $allowed = ['very_high', 'high', 'medium', 'low'];
            $priority = strtolower(trim((string)$_GET['priority_level']));
            if (!in_array($priority, $allowed, true)) {
                http_response_code(400);
                echo json_encode(['error' => 'priority_level is invalid']);
                exit;
            }

            $sql .= ' AND hs.priority_level = ?';
            $params[] = $priority;
        }

        if (isset($_GET['min_spi']) && $_GET['min_spi'] !== '') {
            if (!is_numeric($_GET['min_spi'])) {
                http_response_code(400);
                echo json_encode(['error' => 'min_spi must be numeric']);
                exit;
            }
            $minSpi = (float)$_GET['min_spi'];
            $sql .= ' AND hs.spi >= ?';
            $params[] = $minSpi;
        }

        $includeAssisted = isset($_GET['include_assisted']) && $_GET['include_assisted'] !== '' && $_GET['include_assisted'] !== '0';
        if (!$includeAssisted) {
            $sql .= ' AND NOT EXISTS (SELECT 1 FROM assistance_distributions ad WHERE ad.household_id = hs.household_id AND ad.delivery_status = \'delivered\')';
        }

        $limit = 100;
        if (isset($_GET['limit']) && $_GET['limit'] !== '') {
            if (!is_numeric($_GET['limit'])) {
                http_response_code(400);
                echo json_encode(['error' => 'limit must be numeric']);
                exit;
            }

            $limit = max(1, min((int)$_GET['limit'], 1000));
        }

        $sql .= ' ORDER BY hs.spi DESC, hs.skr DESC, hs.computed_at DESC LIMIT ' . $limit;

        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $ranking = $stmt->fetchAll(PDO::FETCH_ASSOC);

        echo json_encode([
            'success' => true,
            'count' => count($ranking),
            'assisted_count' => (int)$db->query("SELECT COUNT(DISTINCT household_id) AS count FROM assistance_distributions WHERE delivery_status = 'delivered'")->fetch(PDO::FETCH_ASSOC)['count'],
            'ranking' => $ranking,
            'score_version' => 'v1'
        ]);
    } 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']);
}
?>