<?php
declare(strict_types=1);

function op_post_string(array $post, string $key, int $min=1, int $max=5000): string {
  $v = trim((string)($post[$key] ?? ''));
  if (strlen($v) < $min) {
    throw new InvalidArgumentException("Missing or invalid: {$key}");
  }
  if (strlen($v) > $max) {
    throw new InvalidArgumentException("Too long: {$key}");
  }
  return $v;
}

function op_post_int(array $post, string $key, int $min=0, ?int $max=null): int {
  if (!isset($post[$key])) throw new InvalidArgumentException("Missing: {$key}");
  $v = filter_var($post[$key], FILTER_VALIDATE_INT);
  if ($v === false) throw new InvalidArgumentException("Invalid integer: {$key}");
  if ($v < $min) throw new InvalidArgumentException("Out of range: {$key}");
  if ($max !== null && $v > $max) throw new InvalidArgumentException("Out of range: {$key}");
  return (int)$v;
}

function op_post_bool_checkbox(array $post, string $key): bool {
  $v = $post[$key] ?? null;
  return ($v === 'on' || $v === '1' || $v === 1 || $v === true || $v === 'true');
}

function op_post_url(array $post, string $key, int $max=2048): string {
  $v = op_post_string($post, $key, 1, $max);
  if (!filter_var($v, FILTER_VALIDATE_URL)) {
    throw new InvalidArgumentException("Invalid URL: {$key}");
  }
  return $v;
}
