<?php
/**
 * whp-async.php — server helpers for progressive-enhancement async forms
 * (see js/whp-async-forms.js). A page's existing POST handler can opt in:
 * after it computes its $message / outcome, call whp_async_json() so an
 * X-WHP-Async request gets JSON instead of a full re-render.
 */
if (!function_exists('whp_is_async_request')) {
    /** True when the request came from whp-async-forms.js (X-WHP-Async: 1). */
    function whp_is_async_request(): bool {
        return strcasecmp($_SERVER['HTTP_X_WHP_ASYNC'] ?? '', '1') === 0;
    }
    /** Emit the {success,message} envelope and stop (only for async requests). */
    function whp_async_json(string $message, bool $success): void {
        if (ob_get_length() !== false) { @ob_clean(); }
        header('Content-Type: application/json');
        echo json_encode(['success' => $success, 'message' => $message]);
        exit;
    }
}
