<?php

namespace GriffinForms\Admin\Html\FormControls\FormTheme;

class BorderStyle extends \GriffinForms\Admin\Html\FormControls\FormTheme\Format
{
    protected $field_type;
    protected $state;

    public function __construct($name = '', $value = '', $data = '')
    {
        parent::__construct($name, $value, $data);

        if (isset($data['field_type'])) {
            $this->field_type = $data['field_type'];
        }

        if (isset($data['state'])) {
            $this->state = $data['state'];
        }

    }

    public function html()
    {
        $current_value = $this->getBorderStyleValue();
        if ($this->field_type) {
            $field_name = $this->buildFieldStyleName($this->field_type, $this->state, 'style');
        } else {
            $field_name = $this->buildSimpleStyleName($this->state, 'style');
        }
        $border_styles = $this->choices->getBorderStyle();

        echo '<select class="form-select griffinforms-border-style" ';
        echo 'name="' . esc_attr($field_name) . '" ';
        echo 'data-field-name="' . esc_attr($field_name) . '">';

        foreach ($border_styles as $style) {
            $selected = ($style === $current_value) ? ' selected' : '';
            echo '<option value="' . esc_attr($style) . '"' . esc_attr($selected) . '>';
            echo esc_html(ucfirst($style));
            echo '</option>';
        }

        echo '</select>';
    }

    /**
     * Gets the border style value from nested array
     */
    protected function getBorderStyleValue()
    {
        if (!is_array($this->value)) {
            return 'solid';
        }

        $value = $this->value;

        // Handle field-type specific structure (e.g., field_style[text_input][default][style])
        if ($this->field_type && isset($value[$this->field_type][$this->state]['style'])) {
            return $value[$this->field_type][$this->state]['style'];
        }

        // Handle direct structure without field_type (e.g., form_style[default][style])
        if (isset($value[$this->state]['style'])) {
            return $value[$this->state]['style'];
        }

        return 'solid';
    }
}
