<?php
// powered by knuepower.de
function hexToRgb($hex) {
  $hex = ltrim($hex, '#');
  if (strlen($hex) === 3) {
    $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
  }
  if (strlen($hex) !== 6) return null;
  return [hexdec(substr($hex, 0, 2)), hexdec(substr($hex, 2, 2)), hexdec(substr($hex, 4, 2))];
}

function rgbToHsl($r, $g, $b) {
  $r /= 255; $g /= 255; $b /= 255;
  $max = max($r, $g, $b); $min = min($r, $g, $b);
  $h = $s = $l = ($max + $min) / 2;

  if ($max === $min) {
    $h = $s = 0;
  } else {
    $d = $max - $min;
    $s = $l > 0.5 ? $d / (2.0 - $max - $min) : $d / ($max + $min);
    switch ($max) {
      case $r: $h = ($g - $b) / $d + ($g < $b ? 6 : 0); break;
      case $g: $h = ($b - $r) / $d + 2; break;
      case $b: $h = ($r - $g) / $d + 4; break;
    }
    $h /= 6;
  }
  return [round($h * 360), round($s * 100), round($l * 100)];
}

$result = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $hex_input = trim($_POST['hex_input'] ?? '');
  $rgb = hexToRgb($hex_input);
  if ($rgb) {
    [$r, $g, $b] = $rgb;
    [$h, $s, $l] = rgbToHsl($r, $g, $b);
    $hex_clean = sprintf("#%02x%02x%02x", $r, $g, $b);
    $result = "HEX: $hex_clean\nRGB: $r, $g, $b\nHSL: $h°, $s%, $l%";
  } else {
    $result = "Ungültiger HEX-Wert.";
  }
}
?>
<form method="post">
  <input type="text" name="hex_input" value="<?= htmlspecialchars($_POST['hex_input'] ?? '') ?>" required placeholder="#ff6600 oder ff6600">
  <button type="submit">Umrechnen</button>
</form>
<?php if (!empty($result)): ?>
<pre><?= htmlspecialchars($result) ?></pre>
<?php endif; ?>
