<?php

/**
 * Class Response
 *
 * @package Mtc\Core
 * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 * @version 2017-03-11
 */

namespace Mtc\Core;

use Exception;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * Class Response
 *
 * Request handling class.
 *
 * @package Mtc\Core
 * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 * @version 2017-02-11
 */
class Response
{
    /**
     * @var string[] Allowed response types for json
     */
    public static $allowed_json_responses = [
        'ok',
        'failed',
    ];

    /**
     * Return a JSON response for this page request.
     * Stops further script execution
     *
     * @param string $status ok|failed to signify request success
     * @param array $data array of data to pass back
     * @param string $messages message for successful request
     * @return JsonResponse
     */
    public static function jsonResponse($status = 'ok', $data = [], $messages = [])
    {
        // Make sure response status is uniform
        $status = strtolower($status);

        // Check if this status is allowed
        if (! in_array($status, self::$allowed_json_responses)) {
            throw new Exception('Invalid status for response');
        }

        // encode response using Symfony JsonResponse
        return new JsonResponse([
            'status' => $status,
            'data' => $data,
            'messages' => $messages,
        ]);
    }

    /**
     * Output JSON string and finalize script
     *
     * @param string $status response type
     * @param array $data array of data to pass back
     * @param string $messages message for successful request
     */
    public static function outputJson($status = 'ok', $data = [], $messages = [])
    {
        self::jsonResponse($status, $data, $messages)->send();
    }
}
