<?php

declare(strict_types=1);

/**
 * Shared sanitization functions for the _meetups click pipeline.
 * Used by both _meetups/index.php and _meetups/r.php.
 *
 * All functions accept mixed input — callers may pass raw $_GET values.
 * Return null when validation fails; callers must check before use.
 */

function meetup_sanitize_token(mixed $value, int $maxLength): ?string
{
    if (!is_scalar($value)) {
        return null;
    }

    $value = trim((string) $value);
    if ($value === '' || strlen($value) > $maxLength) {
        return null;
    }

    return preg_match('/^[A-Za-z0-9_-]+$/', $value) === 1 ? $value : null;
}

function meetup_sanitize_country_code(mixed $value): ?string
{
    if (!is_scalar($value)) {
        return null;
    }

    $value = strtolower(trim((string) $value));
    if ($value === '') {
        return null;
    }

    return preg_match('/^[a-z]{2}$/', $value) === 1 ? $value : null;
}

function meetup_sanitize_ip(mixed $value): string
{
    if (!is_scalar($value)) {
        return '';
    }

    $value = trim((string) $value);
    if ($value === '') {
        return '';
    }

    return filter_var($value, FILTER_VALIDATE_IP) !== false ? $value : '';
}
