<?php

namespace Sitecake\Http;

/**
 * HTTP response — replaces Symfony\Component\HttpFoundation\Response.
 */
class Response
{
    protected string $content;
    protected int $statusCode;
    public HeaderBag $headers;

    public function __construct(string $content = '', int $statusCode = 200, array $headers = [])
    {
        $this->content    = $content;
        $this->statusCode = $statusCode;
        $this->headers    = new HeaderBag($headers);
    }

    public function setContent(string $content): void
    {
        $this->content = $content;
    }

    public function getContent(): string
    {
        return $this->content;
    }

    public function setStatusCode(int $code): void
    {
        $this->statusCode = $code;
    }

    public function getStatusCode(): int
    {
        return $this->statusCode;
    }

    /** Send HTTP headers + body to the client. */
    public function send(): void
    {
        http_response_code($this->statusCode);
        foreach ($this->headers->all() as $name => $value) {
            // LOW-4: Strip CRLF to prevent header injection
            $name  = preg_replace('/[\r\n]/', '', $name);
            $value = preg_replace('/[\r\n]/', '', (string)$value);
            if ($name !== '') {
                header($name . ': ' . $value, true);
            }
        }
        echo $this->content;
    }
}
