<?php


namespace CCDN\Helpers\Http;

use CCDN\Helpers\Exception\CCDNRuntimeException;

class Response
{


    /**
     * @param  string  $to
     * @param  bool  $replace
     * @param  int  $code
     */
    public function redirect($to, $replace = true, $code = 301)
    {
        $this->addHeader('Location', $to, $replace, $code);
        exit();
    }

    /**
     * @param  string  $key
     * @param  string  $value
     * @param  bool  $replace
     * @param  int|null  $http_response_code
     * @return Response
     */
    public function addHeader($key, $value, $replace = true, $http_response_code = null)
    {
        if (!empty($value)) {
            $value = ': '.$value;
        }
        header($key.$value, $replace, $http_response_code);
        return $this;
    }

    /**
     * @param  string  $date
     * @param  int  $code
     * @return string
     */
    public function make($date, $code = 200)
    {
        global $config;
        $this->addHeader('Content-Type', "text/html; charset={$config['charset']}", true, $code);
        return $date;
    }

    /**
     * @param  string|array  $date
     * @param  int  $code
     * @return string
     */
    public function json($date, $code = 200)
    {
        global $config;
        http_response_code($code);

        $this->addHeaders([
            'Cache-Control' => 'no-cache',
            'Content-Type' => "application/json; charset={$config['charset']}",
        ]);

        if (!is_string($date)) {
            $date = json_encode($date, JSON_UNESCAPED_UNICODE);
        }


        if (!$this->_isJson($date)) {
            throw new CCDNRuntimeException('Invalid json response');
        }

        return mb_convert_encoding($date, $config['charset']);

    }

    /**
     * @param  array  $headers
     * @return Response
     */
    public function addHeaders($headers)
    {
        foreach ($headers as $key => $value) {
            $this->addHeader($key, $value);
        }

        return $this;
    }

    /**
     * @param  string  $string
     * @param  bool  $assoc
     * @return bool
     */
    private function _isJson($string, $assoc = true)
    {
        json_decode($string, $assoc);
        return json_last_error() === JSON_ERROR_NONE;
    }
}
