<?php
namespace IntellexApps\PHP\UploadFile\Network;

class Response
{

    var $content    = null;
    var $status     = 200;

    /**
     * Response constructor.
     * @param null $content
     * @param int $status
     */
    public function __construct($content = null, $status = 200)
    {
        $this->setContent($content);
        $this->setStatus($status);
    }

    /**
     * Output
     */
    public function output()
    {
        ob_start();

        $this->header("HTTP/1.1 " . $this->getStatus() . " " . $this->requestStatus($this->getStatus()));
        $this->header("Access-Control-Allow-Origin: *");
        $this->header("Access-Control-Allow-Methods: *");
        $this->header("Access-Control-Allow-Methods: GET, POST, PATCH, DELETE, OPTIONS");

        // Get body as string
        $body = $this->getBody();
        $size = strlen($body);

        // Content length
        $this->header("Content-length: $size");

        // Additional headers
        $this->additionalHeaders();

        echo $body;
        die;
    }

    /**
     * Output headers is necessarry
     */
    protected function additionalHeaders() {}

    /**
     * Output content
     */
    protected function getBody()
    {
        return $this->getContent();
    }

    /**
     * Output header
     *
     * @param $header
     */
    public function header($header)
    {
        header($header);
    }

    /**
     * Get message for code
     *
     * @param $code
     * @return mixed
     */
    private function requestStatus($code) {
        $status = array(
            200 => 'OK',
            404 => 'Not Found',
            405 => 'Method Not Allowed',
            500 => 'Internal Server Error',
        );
        return ($status[$code])?$status[$code]:$status[500];
    }

    /**
     * @return null
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * @param null $content
     */
    public function setContent($content)
    {
        $this->content = $content;
    }

    /**
     * @return int
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * @param int $status
     */
    public function setStatus($status)
    {
        $this->status = $status;
    }
}