<?php

namespace Khofmann\Response;

use Pecee\SimpleRouter\SimpleRouter;
use Pecee\Http\Response as PResponse;

/**
 * Facade for Response creation (wraps SimpleRouter)
 */
class Response
{
  /**
   * Private since facade.
   */
  private function __construct()
  {
  }

  /**
   * Get current response
   */
  public static function response(): PResponse
  {
    return SimpleRouter::response();
  }

  /**
   * Create JSON response
   *
   * @param mixed $value Body of response
   * @param int $options Options passed to `json_encode`
   * @param int $dept Depth passed to `json_encode`
   */
  public static function json($value, int $options = 0, int $dept = 512): void
  {
    if (is_bool($value)) {
      Response::response()->header('Content-Type: application/json; charset=utf-8');
      echo json_encode($value, $options, $dept);
      exit(0);
    }
    SimpleRouter::response()->json($value, $options, $dept);
  }

  /**
   * Create API error response
   *
   * @param string $value Body of error
   * @param int $code HTTP code of error
   */
  public static function apiError(string $value, int $code): void
  {
    Response::response()->header('Content-Type: application/json; charset=utf-8')->httpCode($code);
    echo $value;
    exit(0);
  }

  /**
   * Create redirect response
   * 
   * @param string $url New target
   * @param ?int $code HTTP code
   */
  public static function redirect(string $url, ?int $code = null): void
  {
    if ($code !== null) {
      Response::response()->httpCode($code);
    }

    Response::response()->redirect($url);
  }
}
