<?php

namespace lib\Core\Http;

//사용법 
//1. 일반 HTML 반환
//return new Response('<h1>Hello World</h1>');
//2. JSON API 응답
//return (new Response())->json(['status' => 'success','message' => 'OK']);
//3. redirect
//return (new Response())->redirect('/login');
//4. 파일 다운로드
//return (new Response())->download('/path/to/manual.pdf', '사용자_매뉴얼.pdf');
class Response
{
  private string $content = '';
  private int $statusCode = 200;
  private array $headers = [];

  public function __construct(string $content = '', int $statusCode = 200, array $headers = [])
  {
    $this->content = $content;
    $this->statusCode = $statusCode;
    $this->headers = $headers;
  }

  public function setContent(string $content): self
  {
    $this->content = $content;
    return $this;
  }

  public function setStatusCode(int $code): self
  {
    $this->statusCode = $code;
    return $this;
  }

  public function header(string $key, string $value): self
  {
    $this->headers[$key] = $value;
    return $this;
  }

  public function json(array $data): self
  {
    $this->header('Content-Type', 'application/json');
    $this->content = json_encode($data, JSON_UNESCAPED_UNICODE);
    return $this;
  }

  public function redirect(string $url): self
  {
    $this->statusCode = 302;
    $this->header('Location', $url);
    return $this;
  }

  public function download(string $filePath, ?string $downloadName = null): self
  {
    if (!file_exists($filePath)) {
      return $this->setStatusCode(404)->setContent("File not found.");
    }

    $downloadName = $downloadName ?? basename($filePath);
    $this->header('Content-Description', 'File Transfer')
      ->header('Content-Type', mime_content_type($filePath))
      ->header('Content-Disposition', 'attachment; filename="' . $downloadName . '"')
      ->header('Content-Length', (string)filesize($filePath))
      ->header('Pragma', 'public')
      ->header('Cache-Control', 'must-revalidate');

    $this->content = file_get_contents($filePath);
    return $this;
  }

  public function send(): void
  {
    http_response_code($this->statusCode);
    foreach ($this->headers as $key => $value) {
      header("$key: $value");
    }
    echo $this->content;
  }
}
