<?php

namespace App\Core;

/**
 * ITSWEBER CMS – Response Helper
 */
class Response
{
    /**
     * Send HTML response.
     */
    public static function html(string $content, int $statusCode = 200): void
    {
        http_response_code($statusCode);
        header('Content-Type: text/html; charset=utf-8');
        echo $content;
    }

    /**
     * Send JSON response.
     */
    public static function json(array $data, int $statusCode = 200): void
    {
        // Clean any stray output buffers to prevent HTML leaking into JSON
        while (ob_get_level() > 0) {
            ob_end_clean();
        }

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

        $json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
        if ($json === false) {
            $json = json_encode([
                'success' => false,
                'message' => 'JSON encode error: ' . json_last_error_msg(),
            ]);
        }
        echo $json;
    }

    /**
     * Redirect to a URL.
     */
    public static function redirect(string $url, int $statusCode = 302): void
    {
        http_response_code($statusCode);
        header('Location: ' . $url);
        exit;
    }

    /**
     * Send a 404 response.
     */
    public static function notFound(string $message = 'Page Not Found'): void
    {
        http_response_code(404);
        echo $message;
    }

    /**
     * Send a 403 response.
     */
    public static function forbidden(string $message = 'Forbidden'): void
    {
        http_response_code(403);
        echo $message;
    }
}
