<?php
/**
 * TechStackBase – Standard API Response Helper
 */

if (headers_sent()) {
    // Prevent malformed responses
    exit;
}

/**
 * Send a JSON response and exit
 *
 * @param int    $statusCode
 * @param string $message
 * @param mixed  $data
 */
function response(int $statusCode, string $message, $data = null): void
{
    http_response_code($statusCode);

    $payload = [
        'status'  => $statusCode < 400 ? 'success' : 'error',
        'message' => $message,
    ];

    if ($data !== null) {
        $payload['data'] = $data;
    }

    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

/**
 * Shortcut helpers
 */
function success(string $message, $data = null): void
{
    response(200, $message, $data);
}

function created(string $message, $data = null): void
{
    response(201, $message, $data);
}

function error_bad_request(string $message = 'Bad request'): void
{
    response(400, $message);
}

function error_unauthorized(string $message = 'Unauthorized'): void
{
    response(401, $message);
}

function error_forbidden(string $message = 'Forbidden'): void
{
    response(403, $message);
}

function error_not_found(string $message = 'Not found'): void
{
    response(404, $message);
}

function error_server(string $message = 'Server error'): void
{
    response(500, $message);
}
