<?php
/**
 * lib/validation.php
 *
 * Input validation helper functions.
 */

/**
 * Sanitize string input
 */
function sanitizeString(?string $value, int $maxLength = 255): string
{
    if ($value === null) return '';
    $sanitized = trim($value);
    $sanitized = filter_var($sanitized, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);
    return substr($sanitized, 0, $maxLength);
}

/**
 * Validate numeric input
 */
function validateNumeric(?string $value, float $min = null, float $max = null): ?float
{
    if ($value === '' || $value === null) return null;

    $numeric = filter_var($value, FILTER_VALIDATE_FLOAT);
    if ($numeric === false) {
        throw new ValidationException('Invalid numeric value: ' . $value);
    }

    if ($min !== null && $numeric < $min) {
        throw new ValidationException('Value below minimum: ' . $numeric);
    }

    if ($max !== null && $numeric > $max) {
        throw new ValidationException('Value above maximum: ' . $numeric);
    }

    return $numeric;
}

/**
 * Custom exception for validation errors
 */
class ValidationException extends Exception {}
?>