<?php
if (!defined('WPINC')) {
    die();
}

$type = $type ?? 'text';
$value = $value ?? '';
$variable_name = $variable_name ?? ($name ?? '');
$id = $id ?? '';
$default_class = $extra_class ?? '';
$class = $default_class;
$attributes = [];
$kses_ruleset = [
    'input' => [
        'type' => true,
        'name' => true,
        'id' => true,
        'value' => true,
        'class' => true,
        'placeholder' => true,
        'required' => true,
        'readonly' => true,
        'checked' => true,
        'style' => true,
        'autocomplete' => true,
        'data-lpignore' => true,
        'data-form-type' => true,
    ]
];

if (isset($class_override) && !empty($class_override)) {
    $class = $class_override;
} elseif (in_array($type, ['text', 'email'])) {
    $attributes[] = 'autocomplete="off" data-lpignore="true" data-form-type="other"';
    $class = 'estatebud-text-field';
    if (isset($extra_class) && !empty($extra_class)) {
        $class .= ' ' . $extra_class;
    }
}

$attributes[] = 'type="' . esc_attr($type) . '"';

if (!empty($variable_name)) {
    $attributes[] = 'name="' . esc_attr($variable_name) . '"';
} elseif (!empty($name)) {
    $attributes[] = 'name="' . esc_attr($name) . '"';
}

if (!empty($id)) {
    $attributes[] = 'id="' . esc_attr($id) . '"';
}

$attributes[] = 'value="' . esc_attr($value) . '"';

if (!empty($class)) {
    $attributes[] = 'class="' . esc_attr(trim($class)) . '"';
}

if (isset($placeholder) && !empty($placeholder)) {
    $attributes[] = 'placeholder="' . esc_attr($placeholder) . '"';
}

if (isset($required) && $required) {
    $attributes[] = 'required';
}

$is_readonly = filter_var($readonly ?? false, FILTER_VALIDATE_BOOLEAN);
if ($is_readonly) {
    $attributes[] = 'readonly';
}

if (in_array($type, ['checkbox', 'radio'])) {
    $is_checked = filter_var($checked ?? false, FILTER_VALIDATE_BOOLEAN);
    if ($is_checked) {
        $attributes[] = 'checked';
    }
}

if (isset($style) && !empty($style)) {
    $attributes[] = 'style="' . esc_attr($style) . '"';
}

if (isset($additional_attributes) && is_array($additional_attributes)) {
    foreach ($additional_attributes as $attr_name => $attr_value) {
        if (is_bool($attr_value) && $attr_value) {
            $attributes[] = esc_attr($attr_name);
        } elseif (!is_bool($attr_value)) {
            $attributes[] = esc_attr($attr_name) . '="' . esc_attr($attr_value) . '"';
        }
    }
}

echo wp_kses('<input ' . implode(' ', $attributes) . ' />', $kses_ruleset);