<?php

namespace App\Core;

class Url
{
  public static function base(): string
  {
    static $base = null;

    if ($base !== null) {
      return $base;
    }

    $base = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'])), '/');

    return $base === '/' ? '' : $base;
  }

  public static function path(string $key, array $params = []): string
  {
    if (!isset(PATH_URL[$key])) {
      throw new \InvalidArgumentException("Path '{$key}' tidak ditemukan.");
    }

    $path = PATH_URL[$key];

    foreach ($params as $name => $value) {
      $path = str_replace('{' . $name . '}', $value, $path);
    }

    return self::base() . $path;
  }

  public static function asset(string $path): string
  {
    return self::base() . '/assets/' . ltrim($path, '/');
  }

  public static function redirect(
    string $key,
    array $params = [],
    ?string $hash = null
  ): never {
    $url = self::path($key, $params);

    if ($hash !== null) {
      $url .= '#' . ltrim($hash, '#');
    }

    header('Location: ' . $url);
    exit;
  }

  public static function uploads(string $path): string
  {
    return self::base() . '/public/uploads/' . ltrim($path, '/');
  }
}
