<?php
if (!function_exists("const_or_default")) {
  /**
   * Gets the constant value or default if constant is not defined
   * @param string $constant_name
   * @param mixed $default
   * @package inobydoc
   */
  function const_or_default($constant_name, $default = null) {
    return defined($constant_name) ? constant($constant_name) : $default;
  }
}

function vardampíček($data) {
  if (const_or_default("WP_DEBUG")) {
    $msg = json_encode($data, JSON_PRETTY_PRINT);
    echo "<pre>$msg</pre>";
  }
}

function adjustBrightness($hexCode, $adjustPercent) {
  $hexCode = ltrim($hexCode, "#");

  if (strlen($hexCode) == 3) {
    $hexCode =
      $hexCode[0] .
      $hexCode[0] .
      $hexCode[1] .
      $hexCode[1] .
      $hexCode[2] .
      $hexCode[2];
  }

  $hexCode = array_map("hexdec", str_split($hexCode, 2));

  foreach ($hexCode as &$color) {
    $adjustableLimit = $adjustPercent < 0 ? $color : 255 - $color;
    $adjustAmount = ceil($adjustableLimit * $adjustPercent);

    $color = str_pad(dechex($color + $adjustAmount), 2, "0", STR_PAD_LEFT);
  }

  return "#" . implode($hexCode);
}

function rwmb_meta_before_init_theme_setting($id, $default = null) {
  $options = get_option("options", []);
  return $options[$id] ?? $default;
}

function phone_intl_format($phone, $default_prefix = "+421") {
  // remove all spaces
  $phone = preg_replace("/\s+/", "", $phone);
  if (str_starts_with($phone, "00")) {
    return "+" . substr($phone, 2);
  } elseif (!str_starts_with($phone, "+")) {
    return $default_prefix . ltrim($phone, "0");
  }
  return $phone;
}

function rwmb_sanitize_number($value, $field, $old_value, $object_id) {
  return floatval($value);
}
