<?php

declare(strict_types=1);

namespace App\Helpers;

class Response
{
    public static function json(array $data, int $status = 200): void
    {
        http_response_code($status);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;
    }

    public static function success(mixed $data = null, string $message = 'OK', int $status = 200): void
    {
        $response = [
            'success' => true,
            'message' => $message,
        ];

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

        self::json($response, $status);
    }

    public static function paginated(array $items, int $total, int $page, int $perPage, string $message = 'OK'): void
    {
        self::json([
            'success' => true,
            'message' => $message,
            'data' => $items,
            'pagination' => [
                'page' => $page,
                'per_page' => $perPage,
                'total' => $total,
                'total_pages' => (int) ceil($total / $perPage),
            ],
        ]);
    }

    public static function error(string $message, int|string $status = 400): void
    {
        $status = (int) $status;
        if ($status < 100 || $status > 599) {
            $status = 400;
        }
        self::json([
            'success' => false,
            'message' => $message,
        ], $status);
    }

    public static function created(mixed $data = null, string $message = 'Creado correctamente'): void
    {
        self::success($data, $message, 201);
    }

    public static function noContent(string $message = 'Sin contenido'): void
    {
        self::json([
            'success' => true,
            'message' => $message,
        ], 204);
    }

    public static function download(string $filePath, string $fileName, string $contentType): void
    {
        if (!file_exists($filePath)) {
            self::error('Archivo no encontrado', 404);
        }

        header('Content-Type: ' . $contentType);
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        header('Content-Length: ' . filesize($filePath));
        readfile($filePath);
        exit;
    }
}
