<?php

namespace KaliForms\Inc\Frontend\FormFields;

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Class Product
 *
 * @package Inc\Frontend\FormFields;
 */
class Choices extends Form_Field
{
    /**
     * Class constructor
     */
    public function __construct()
    {
        $this->id = 'choices';
    }

    /**
     * Render function
     *
     * @return void
     */
    public function render($item, $form_info)
    {
        $item['multipleSeparator'] = $form_info['multiple_selections_separator'];
        $item['multiple']          = !empty($item['maxItemCount']) && absint($item['maxItemCount'] > 1);

        if ($item['multiple'] && $item['required']) {
            $item['required']          = false;
            $item['data-was-required'] = true;
        }

        $attributes = $this->generate_attribute_string($item);
        $offset     = isset($item['offset']) && $item['offset'] > 0 ? 'offset-md-' . absint($item['offset']) : '';
        $div        = '<div class="col-12 col-md-' . absint($item['col']) . ' ' . $offset . '">';
        $div .= $this->generate_label($item, $form_info);
        $div .= '<select ' . $attributes . ' class="kaliforms-choices">';
        if (!$item['multiple'] && !empty($item['placeholder'])) {
            $div .= '<option placeholder>' . esc_html($item['placeholder']) . '</option>';
        }
        foreach ($item['choices'] as $choice) {
            $defaultValue = $this->default_value($item, $item['default']);
            $selected     = $choice->value === $defaultValue ? 'selected' : '';

            $div .= '<option value="' . esc_attr($choice->value) . '" ' . $selected . '>' . esc_html($choice->label) . '</option>';
        }
        $div .= '</select>';

        $div .= !empty($item['description']) ? '<small>' . esc_html($item['description']) . '</small>' : '';

        $div .= '</div>';
        return $div;
    }
}
