<?php
/**
 * Response Helper - Compatível com PHP 7.x
 */

namespace Core;

class Response
{
    /**
     * Enviar resposta JSON
     */
    public static function json(array $data, int $code = 200): void
    {
        http_response_code($code);
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;
    }

    /**
     * Resposta de sucesso
     * @param mixed $data
     */
    public static function success($data = null, string $message = '', int $code = 200): void
    {
        $response = ['status' => 'success'];
        
        if ($message) {
            $response['message'] = $message;
        }
        
        if ($data !== null) {
            $response['data'] = $data;
        }
        
        self::json($response, $code);
    }

    /**
     * Resposta de erro
     */
    public static function error(string $message, int $code = 400, $details = null): void
    {
        $response = [
            'status' => 'error',
            'message' => $message
        ];
        
        if ($details !== null) {
            $response['details'] = $details;
        }
        
        self::json($response, $code);
    }

    /**
     * Resposta de warning
     * @param mixed $data
     */
    public static function warning(string $message, $data = null, int $code = 200): void
    {
        $response = [
            'status' => 'warning',
            'message' => $message
        ];
        
        if ($data !== null) {
            $response['data'] = $data;
        }
        
        self::json($response, $code);
    }

    /**
     * Resposta paginada
     */
    public static function paginated(array $data, int $total, int $page, int $limit): void
    {
        self::json([
            'status' => 'success',
            'data' => $data,
            'pagination' => [
                'total' => $total,
                'page' => $page,
                'limit' => $limit,
                'pages' => ceil($total / $limit)
            ]
        ]);
    }

    /**
     * Erro 401 - Não autorizado
     */
    public static function unauthorized(string $message = 'Authentication required'): void
    {
        self::error($message, 401);
    }

    /**
     * Erro 403 - Acesso negado
     */
    public static function forbidden(string $message = 'Access denied'): void
    {
        self::error($message, 403);
    }

    /**
     * Erro 404 - Não encontrado
     */
    public static function notFound(string $message = 'Not found'): void
    {
        self::error($message, 404);
    }

    /**
     * Erro 500 - Erro interno
     */
    public static function serverError(string $message = 'Internal server error'): void
    {
        self::error($message, 500);
    }
}
