<?php
/**
 * Ragreen - API Response & Request Helpers
 */

header('Content-Type: application/json; charset=utf-8');

/**
 * Send a JSON response and stop execution.
 */
function send_json(bool $success, string $message, array $data = [], int $httpCode = 200): void
{
    http_response_code($httpCode);
    echo json_encode(array_merge([
        'success' => $success,
        'message' => $message,
    ], $data ? ['data' => $data] : []));
    exit;
}

function send_error(string $message, int $httpCode = 400, array $errors = []): void
{
    http_response_code($httpCode);
    echo json_encode([
        'success' => false,
        'message' => $message,
        'errors'  => $errors,
    ]);
    exit;
}

/**
 * Read JSON body from the request into an associative array.
 */
function get_json_input(): array
{
    $raw = file_get_contents('php://input');
    $data = json_decode($raw, true);
    return is_array($data) ? $data : [];
}

/**
 * Basic required-field validator.
 * Returns an array of missing field names (empty array = all present).
 */
function validate_required(array $input, array $required): array
{
    $missing = [];
    foreach ($required as $field) {
        if (!isset($input[$field]) || trim((string)$input[$field]) === '') {
            $missing[] = $field;
        }
    }
    return $missing;
}

function only_post_allowed(): void
{
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        send_error('Method not allowed. POST required.', 405);
    }
}
