<?php

declare(strict_types=1);

function myronFormHoneypotCheck(array $form, array $payload): bool
{
    $name = trim((string) ($form['honeypot_field_name'] ?? ''));
    return $name !== '' && trim((string) ($payload[$name] ?? '')) !== '';
}

/**
 * @return array<string, string>
 */
function myronFormValidateSubmission(array $form, array $payload): array
{
    $errors = [];
    $normalizedTotal = 0;
    foreach (is_array($form['fields'] ?? null) ? $form['fields'] : [] as $field) {
        if (!is_array($field)) {
            continue;
        }
        $key = (string) ($field['key'] ?? '');
        if ($key === '') {
            continue;
        }
        $type = (string) ($field['type'] ?? 'text');
        $value = $payload[$key] ?? '';
        $text = is_array($value) ? implode(', ', array_map('strval', $value)) : (string) $value;
        $text = trim($text);
        if (!empty($field['required']) && $text === '') {
            $errors[$key] = 'This field is required.';
            continue;
        }
        if ($text === '') {
            continue;
        }
        if (strlen($text) > 5000) {
            $errors[$key] = 'This field is too long.';
            continue;
        }
        $normalizedTotal += strlen($text);
        if ($normalizedTotal > 50000) {
            $errors[$key] = 'This submission is too large.';
            continue;
        }
        if ($type === 'email' && filter_var($text, FILTER_VALIDATE_EMAIL) === false) {
            $errors[$key] = 'Enter a valid email address.';
        } elseif ($type === 'url') {
            $scheme = strtolower((string) parse_url($text, PHP_URL_SCHEME));
            if (filter_var($text, FILTER_VALIDATE_URL) === false || !in_array($scheme, ['http', 'https'], true)) {
                $errors[$key] = 'Enter a valid http or https URL.';
            }
        } elseif ($type === 'tel' && preg_match('/^[0-9+().\\-\\s]{7,40}$/', $text) !== 1) {
            $errors[$key] = 'Enter a valid phone number.';
        } elseif ($type === 'number') {
            if (!is_numeric($text)) {
                $errors[$key] = 'Enter a number.';
            } else {
                $validation = is_array($field['validation'] ?? null) ? $field['validation'] : [];
                if (isset($validation['min']) && (float) $text < (float) $validation['min']) {
                    $errors[$key] = 'Enter a number above the minimum.';
                }
                if (isset($validation['max']) && (float) $text > (float) $validation['max']) {
                    $errors[$key] = 'Enter a number below the maximum.';
                }
            }
        } elseif (in_array($type, ['select', 'radio'], true)) {
            $allowed = [];
            foreach (is_array($field['options'] ?? null) ? $field['options'] : [] as $option) {
                if (is_array($option)) {
                    $allowed[] = (string) ($option['value'] ?? '');
                }
            }
            if (!in_array($text, $allowed, true)) {
                $errors[$key] = 'Select a valid option.';
            }
        }
    }
    return $errors;
}

/**
 * @return array<string, string>
 */
function myronFormNormalizeSubmission(array $form, array $payload): array
{
    $values = [];
    foreach (is_array($form['fields'] ?? null) ? $form['fields'] : [] as $field) {
        if (!is_array($field)) {
            continue;
        }
        $key = (string) ($field['key'] ?? '');
        if ($key === '') {
            continue;
        }
        $value = $payload[$key] ?? '';
        if (($field['type'] ?? '') === 'checkbox') {
            $values[$key] = !empty($value) && $value !== '0' ? '1' : '0';
            continue;
        }
        $values[$key] = trim(strip_tags(is_array($value) ? implode(', ', array_map('strval', $value)) : (string) $value));
    }
    return $values;
}

function myronFormIpHash(string $ip): string
{
    return hash('sha256', $ip . '|' . gmdate('Y-m-d') . '|' . (string) (getenv('MYRON_APP_KEY') ?: 'myron'));
}
