<?php

namespace Snaju\Inception\Api\Returns;

class ApiReturn
{

    protected $code = 200;
    protected $success = false;
    protected $errorMessage = "";
    protected $return = [];

    /**
     * ApiReturn constructor.
     * @param bool $success
     * @param string $errorMessage
     * @param array $return
     * @param int $code
     */
    public function __construct(bool $success, string $errorMessage = "", array $return = [], int $code = 200)
    {
        $this->success = $success;
        $this->errorMessage = $errorMessage;
        $this->return = $return;
        $this->code = $code;
    }

    /**
     * @return bool
     */
    public function isSuccess(): bool
    {
        return $this->success;
    }

    /**
     * @param bool $success
     */
    public function setSuccess(bool $success): void
    {
        $this->success = $success;
    }

    /**
     * @return string
     */
    public function getErrorMessage(): string
    {
        return $this->errorMessage;
    }

    /**
     * @param string $errorMessage
     */
    public function setErrorMessage(string $errorMessage): void
    {
        $this->errorMessage = $errorMessage;
    }

    /**
     * @return array
     */
    public function getReturn(): array
    {
        return $this->return;
    }

    /**
     * @param array $return
     */
    public function setReturn(array $return): void
    {
        $this->return = $return;
    }

    /**
     * @return int
     */
    public function getCode(): int
    {
        return $this->code;
    }

    /**
     * @param int $code
     */
    public function setCode(int $code): void
    {
        $this->code = $code;
    }

    public function render(int $code)
    {
        $a = [
            "success" => true,
            "data" => $this->return
        ];

        if (!$this->success) {
            $a = [
                "success" => false,
                "data" => [
                    "error" => $this->errorMessage,
                    "code" => $code
                ]
            ];
        }

        header("Content-Type: application/json");
        echo json_encode($a);
        exit($code);
    }

    public static function call(ApiReturn $return)
    {
        $return->render($return->code);
    }


//    public static function SUCCESS(&$return, string $type = ApiReturn::class)
//    {
//        return new $type(true, "", $return);
//    }
//
//    public static function ERROR(string $msg, string $type = ApiReturn::class)
//    {
//        return new $type(false, $msg);
//    }

}