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

        $sql = '
            SELECT
                h.*,
                np.name AS need_point_name,
                m.name AS masjid_name,
                pa.name AS area_name,
                (
                    SELECT COUNT(*)
                    FROM assistance_distributions ad
                    WHERE ad.household_id = h.id
                ) AS assistance_count,
                (
                    SELECT MAX(vl.verified_at)
                    FROM verification_logs vl
                    WHERE vl.household_id = h.id
                ) AS last_verified_at
            FROM households h
            LEFT JOIN need_points np ON np.id = h.need_point_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['verification_status']) && $_GET['verification_status'] !== '') {
            $error = null;
            $status = normalizeVerificationStatus($_GET['verification_status'], $error, true);
            if ($status === null) {
                http_response_code(400);
                echo json_encode(['error' => $error]);
                exit;
            }

            $sql .= ' AND h.verification_status = ?';
            $params[] = $status;
        }

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

            $sql .= ' AND h.masjid_id = ?';
            $params[] = (int)$_GET['masjid_id'];
        }

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

            $sql .= ' AND h.pontianak_area_id = ?';
            $params[] = (int)$_GET['pontianak_area_id'];
        }

        if (isset($_GET['q']) && trim((string)$_GET['q']) !== '') {
            $q = '%' . trim((string)$_GET['q']) . '%';
            $sql .= ' AND (h.household_code LIKE ? OR h.head_name LIKE ?)';
            $params[] = $q;
            $params[] = $q;
        }

        $limit = 200;
        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 h.created_at DESC LIMIT ' . $limit;

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

        echo json_encode([
            'success' => true,
            'count' => count($households),
            'households' => $households
        ]);
    } 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']);
}
?>