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

        $sql = '
            SELECT
                ad.*,
                h.household_code,
                h.head_name,
                h.verification_status AS household_verification_status
            FROM assistance_distributions ad
            JOIN households h ON h.id = ad.household_id
            WHERE 1 = 1
        ';
        $params = [];

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

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

        if (isset($_GET['assistance_type']) && $_GET['assistance_type'] !== '') {
            $error = null;
            $assistanceType = normalizeAssistanceType($_GET['assistance_type'], $error);
            if ($assistanceType === null) {
                http_response_code(400);
                echo json_encode(['error' => $error]);
                exit;
            }

            $sql .= ' AND ad.assistance_type = ?';
            $params[] = $assistanceType;
        }

        if (isset($_GET['delivery_status']) && $_GET['delivery_status'] !== '') {
            $error = null;
            $deliveryStatus = normalizeDeliveryStatus($_GET['delivery_status'], $error);
            if ($deliveryStatus === null) {
                http_response_code(400);
                echo json_encode(['error' => $error]);
                exit;
            }

            $sql .= ' AND ad.delivery_status = ?';
            $params[] = $deliveryStatus;
        }

        if (isset($_GET['date_from']) && $_GET['date_from'] !== '') {
            $dateFrom = trim((string)$_GET['date_from']);
            $dateObj = DateTime::createFromFormat('Y-m-d', $dateFrom);
            if (!$dateObj || $dateObj->format('Y-m-d') !== $dateFrom) {
                http_response_code(400);
                echo json_encode(['error' => 'date_from must be in YYYY-MM-DD format']);
                exit;
            }

            $sql .= ' AND ad.distribution_date >= ?';
            $params[] = $dateFrom;
        }

        if (isset($_GET['date_to']) && $_GET['date_to'] !== '') {
            $dateTo = trim((string)$_GET['date_to']);
            $dateObj = DateTime::createFromFormat('Y-m-d', $dateTo);
            if (!$dateObj || $dateObj->format('Y-m-d') !== $dateTo) {
                http_response_code(400);
                echo json_encode(['error' => 'date_to must be in YYYY-MM-DD format']);
                exit;
            }

            $sql .= ' AND ad.distribution_date <= ?';
            $params[] = $dateTo;
        }

        $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 ad.distribution_date DESC, ad.created_at DESC LIMIT ' . $limit;

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

        $summarySql = '
            SELECT
                COUNT(*) AS total_records,
                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
        ';
        $summaryStmt = $db->query($summarySql);
        $summary = $summaryStmt->fetch(PDO::FETCH_ASSOC);

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