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

require_once 'config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $data = json_decode(file_get_contents('php://input'), true);

        if (!is_array($data)) {
            http_response_code(400);
            echo json_encode(['error' => 'Invalid JSON body']);
            exit;
        }

        if (!isset($data['household_id']) || !is_numeric($data['household_id'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing or invalid household_id']);
            exit;
        }

        $householdId = (int)$data['household_id'];

        $error = null;
        $assistanceType = normalizeAssistanceType($data['assistance_type'] ?? null, $error);
        if ($assistanceType === null) {
            http_response_code(400);
            echo json_encode(['error' => $error]);
            exit;
        }

        $assistanceValue = normalizeAssistanceValue($data['assistance_value'] ?? null, $error);
        if ($assistanceValue === null) {
            http_response_code(400);
            echo json_encode(['error' => $error]);
            exit;
        }

        $assistanceFrequency = normalizeAssistanceFrequency($data['assistance_frequency'] ?? null, $error);
        if ($assistanceFrequency === null) {
            http_response_code(400);
            echo json_encode(['error' => $error]);
            exit;
        }

        $deliveryStatus = normalizeDeliveryStatus($data['delivery_status'] ?? null, $error);
        if ($deliveryStatus === null) {
            http_response_code(400);
            echo json_encode(['error' => $error]);
            exit;
        }

        $distributionDate = isset($data['distribution_date']) && trim((string)$data['distribution_date']) !== ''
            ? trim((string)$data['distribution_date'])
            : date('Y-m-d');

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

        $deliveredBy = isset($data['delivered_by']) ? trim((string)$data['delivered_by']) : null;
        if ($deliveredBy === '') {
            $deliveredBy = null;
        }

        $notes = isset($data['notes']) ? trim((string)$data['notes']) : null;
        if ($notes === '') {
            $notes = null;
        }

        $db = getDB();
        if (!householdExists($db, $householdId)) {
            http_response_code(404);
            echo json_encode(['error' => 'Household not found']);
            exit;
        }

        $insertStmt = $db->prepare('
            INSERT INTO assistance_distributions (
                household_id,
                assistance_type,
                assistance_value,
                assistance_frequency,
                distribution_date,
                delivery_status,
                delivered_by,
                notes,
                updated_at
            )
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
        ');

        $insertStmt->execute([
            $householdId,
            $assistanceType,
            $assistanceValue,
            $assistanceFrequency,
            $distributionDate,
            $deliveryStatus,
            $deliveredBy,
            $notes
        ]);

        $id = (int)$db->lastInsertId();
        $resultStmt = $db->prepare('
            SELECT
                ad.*,
                h.household_code,
                h.head_name
            FROM assistance_distributions ad
            JOIN households h ON h.id = ad.household_id
            WHERE ad.id = ?
        ');
        $resultStmt->execute([$id]);
        $distribution = $resultStmt->fetch(PDO::FETCH_ASSOC);

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