<?php
// app/http/Response.php

declare(strict_types=1);

namespace ScMedia\Http;

final class Response {
  public static function json(array $payload, int $code = 200): void {
    http_response_code($code);
    header('Content-Type: application/json; charset=utf-8');
    $out = function_exists('normalize_dates_in_array')
      ? normalize_dates_in_array($payload)
      : $payload;
    echo json_encode($out, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  }

  public static function html(string $html, int $code = 200): void {
    http_response_code($code);
    header('Content-Type: text/html; charset=utf-8');
    echo $html;
  }

  /**
   * Serve static HTML from public/assets safely (no traversal).
   * Example: Response::assetHtml('settings.html');
   */
  public static function assetHtml(string $assetFile, int $code = 200): void {
    $assetFile = ltrim($assetFile, '/');

    if (str_contains($assetFile, '..') || str_contains($assetFile, "\0")) {
      http_response_code(400);
      header('Content-Type: text/plain; charset=utf-8');
      echo "Bad request";
      return;
    }

    $baseDir = realpath(__DIR__ . '/../../public/assets');
    if ($baseDir === false) {
      http_response_code(500);
      header('Content-Type: text/plain; charset=utf-8');
      echo "Assets directory not found";
      return;
    }

    $fullPath = realpath($baseDir . '/' . $assetFile);
    if ($fullPath === false || !str_starts_with($fullPath, $baseDir) || !is_file($fullPath)) {
      http_response_code(404);
      header('Content-Type: text/plain; charset=utf-8');
      echo "Not found";
      return;
    }

    http_response_code($code);
    header('Content-Type: text/html; charset=utf-8');
    readfile($fullPath);
  }
}
