<?php

namespace lib\Core\Http;

class Url extends Http
{
  protected string $baseUrl;
  protected string $uri;

  public function __construct()
  {
    parent::__construct();
    $this->baseUrl = $this->detectBaseUrl();
    $this->uri = $this->detectUri();
  }

  // 현재 전체 URL 반환
  public function current(): string
  {
    return $this->baseUrl . '/' . ltrim($this->uri, '/');
  }

  // base URL만 반환
  public function base(): string
  {
    return $this->baseUrl;
  }

  // 세그먼트 배열 반환
  public function segments(): array
  {
    return explode('/', trim($this->uri, '/'));
  }

  // N번째 세그먼트 반환 (1부터 시작)
  public function segment(int $n): ?string
  {
    $segments = $this->segments();
    return $segments[$n - 1] ?? null;
  }

  // 특정 경로에 대한 URL 생성
  public function to(string $path): string
  {
    return rtrim($this->baseUrl, '/') . '/' . ltrim($path, '/');
  }

  // URI 추출 (도메인 제외)
  protected function detectUri(): string
  {
    $uri = $_SERVER['REQUEST_URI'] ?? '/';
    $scriptName = dirname($_SERVER['SCRIPT_NAME'] ?? '');
    $uri = str_replace($scriptName, '', $uri);
    $uri = strtok($uri, '?'); // 쿼리 스트링 제거
    return $uri;
  }

  // base URL 추출
  protected function detectBaseUrl(): string
  {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $scriptDir = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/');
    return $scheme . '://' . $host . $scriptDir;
  }

  public static function baseUrl(): string
  {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $script = str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);

    return rtrim($protocol . $host . $script, '/');
  }

  public static function currentUrl(): string
  {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $uri = $_SERVER['REQUEST_URI'] ?? '';

    return $protocol . $host . $uri;
  }

  public static function previousUrl(): ?string
  {
    return $_SERVER['HTTP_REFERER'] ?? null;
  }

  public static function urlIs(string $pattern): bool
  {
    $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    $pattern = str_replace('*', '.*', preg_quote($pattern, '/'));
    return preg_match("/^{$pattern}$/", $uri) === 1;
  }

  public static function getSegment(int $index): ?string
  {
    $uri = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
    $segments = explode('/', $uri);
    return $segments[$index - 1] ?? null;
  }
}
