<?php
/// file: app/Core/Response.php

declare(strict_types=1);

namespace App\Core;

final class Response
{
    public function __construct(
        private string $body = '',
        private int $status = 200,
        /** @var array<string, string> */
        private array $headers = []
    ) {
    }

    public function header(string $name, string $value): self
    {
        $this->headers[$name] = $value;
        return $this;
    }

    public function status(int $code): self
    {
        $this->status = $code;
        return $this;
    }

    public function send(): void
    {
        http_response_code($this->status);
        foreach ($this->headers as $n => $v) {
            header("{$n}: {$v}");
        }
        echo $this->body;
    }

    public static function html(string $html, int $status = 200): self
    {
        $r = new self($html, $status);
        return $r->header('Content-Type', 'text/html; charset=UTF-8');
    }

    /** @param array<string, mixed> $data */
    public static function json(array $data, int $status = 200): self
    {
        $r = new self(json_encode($data, JSON_THROW_ON_ERROR), $status);
        return $r->header('Content-Type', 'application/json; charset=UTF-8');
    }
}
