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

$default_class = 'estatebud-field-select';
$id = $id ?? '';
$multiple = (bool) ($multiple ?? false);
$add_empty_option = $add_empty_option ?? true;
$placeholder = $placeholder ?? '';
$kses_ruleset = [
    'select' => [
        'class' => true,
        'id' => true,
        'name' => true,
        'placeholder' => true,
        'multiple' => true,
        'required' => true,
    ],
    'option' => [
        'value' => true,
        'disabled' => true,
        'selected' => true,
    ],
];

if (!isset($options) || !is_array($options)) {
    $options = [];
}

if (isset($extra_class) && !empty($extra_class)) {
    $default_class .= ' ' . $extra_class;
}

if (!empty($id) && isset($extra_id) && !empty($extra_id)) {
    $id .= ' ' . $extra_id;
} elseif (empty($id) && isset($extra_id) && !empty($extra_id)) {
    $id = $extra_id;
}

if (!$multiple && $add_empty_option === true) {
    array_unshift($options, [
        'value' => '',
        'label' => empty($placeholder) ? '-' : $placeholder,
    ]);
}

$attributes = [];

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

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

$attributes[] = 'name="' . esc_attr($variable_name ?? '') . '"';

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

if ($multiple) {
    $attributes[] = 'multiple';
}

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

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) . '"';
        }
    }
}

$options_parsed = [];

foreach ($options as $option) {
    $option_value = $option['value'] ?? '';

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

    if (isset($option['disabled']) && $option['disabled']) {
        $option_attributes[] = 'disabled="disabled"';
    }

    if (isset($option['selected']) && $option['selected']) {
        $option_attributes[] = 'selected="selected"';
    }

    $options_parsed[] = '<option ' . implode(' ', $option_attributes) . '>' . esc_html($option['label'] ?? '') . '</option>';
}

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