<?php
/**
 * Lightweight validators / sanitizers used across the app.
 */

function v_clean_string($v, int $maxLen = 255): string
{
    $v = is_string($v) ? trim($v) : '';
    if ($maxLen > 0 && mb_strlen($v) > $maxLen) {
        $v = mb_substr($v, 0, $maxLen);
    }
    return $v;
}

function v_int($v, int $min = PHP_INT_MIN, int $max = PHP_INT_MAX, int $default = 0): int
{
    if ($v === null || $v === '') return $default;
    $n = (int) $v;
    if ($n < $min) return $min;
    if ($n > $max) return $max;
    return $n;
}

function v_password_strong(string $pwd, int $min = 0): array
{
    if ($min <= 0) $min = max(8, (int) osce_env('PASSWORD_MIN_LENGTH', 10));
    $issues = [];
    if (strlen($pwd) < $min)            $issues[] = "must be at least {$min} characters";
    if (!preg_match('/[A-Z]/', $pwd))   $issues[] = "must contain an uppercase letter";
    if (!preg_match('/[a-z]/', $pwd))   $issues[] = "must contain a lowercase letter";
    if (!preg_match('/\d/', $pwd))      $issues[] = "must contain a digit";
    return $issues;
}

function v_username(string $u): bool
{
    return (bool) preg_match('/^[A-Za-z0-9._-]{3,50}$/', $u);
}

function v_barcode(string $b): bool
{
    return (bool) preg_match('/^[A-Za-z0-9_-]{3,50}$/', $b);
}

function h($s): string
{
    return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
}
