<?php

namespace Openguru\OpenCartFramework\Http;

class JsonResponse extends Response
{
    private array $data;
    private int $code;

    public function __construct(array $data, int $code = self::HTTP_OK)
    {
        $this->data = $data;
        $this->code = $code;
    }

    public function getData(): array
    {
        return $this->data;
    }

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

    public function send(): void
    {
        $this->sendHeaders();
        $this->sendContent();
    }

    private function sendContent(): void
    {
        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            http_response_code(204);
            exit;
        }

        echo json_encode($this->getData(), JSON_THROW_ON_ERROR);
    }

    private function sendHeaders(): void
    {
        http_response_code($this->getCode());
        header('Content-Type: application/json');
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST');
        header('Access-Control-Allow-Headers: Content-Type, Authorization');
        header('Access-Control-Allow-Credentials: true');
    }
}
