<?php

namespace Bricks;

use \Bricksforge\ProForms\Helper as Helper;

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

class Brf_Pro_Forms_Textarea extends \Bricks\Element
{

    public $category = 'bricksforge forms';
    public $name = 'brf-pro-forms-field-textarea';
    public $icon = 'fa-solid fa-text-height';
    public $css_selector = '';
    public $scripts = [];
    public $nestable = false;

    public function get_label()
    {
        return esc_html__("Textarea", 'bricksforge');
    }

    public function enqueue_scripts()
    {
        wp_enqueue_script('bricksforge-elements');
    }

    public function set_control_groups()
    {
        $this->control_groups['general'] = [
            'title'    => esc_html__('General', 'bricksforge'),
            'tab'      => 'content',
        ];
        $this->control_groups['maxLengthCounter'] = [
            'title'    => esc_html__('Max Length Counter', 'bricksforge'),
            'tab'      => 'content',
            'required' => ['showMaxLengthCounter', '=', true],
        ];
        $this->control_groups['conditions'] = [
            'title'    => esc_html__('Conditions', 'bricksforge'),
            'tab'      => 'content',
        ];
        $this->control_groups['validation'] = [
            'title'    => esc_html__('Validation', 'bricksforge'),
            'tab'      => 'content',
        ];
        $this->control_groups['style'] = [
            'title'    => esc_html__('Style', 'bricksforge'),
            'tab'      => 'content',
        ];
    }

    public function set_controls()
    {

        $this->controls = array_merge($this->controls, Helper::get_default_controls('textarea'));

        // Placeholder
        $this->controls['placeholder'] = [
            'group' => 'general',
            'label'          => esc_html__('Placeholder', 'bricksforge'),
            'type'           => 'text',
            'inline'         => true,
            'spellcheck'     => false,
            'hasDynamicData' => true,
        ];

        // Autocomplete
        $this->controls['autocomplete'] = [
            'group' => 'general',
            'label' => esc_html__('Autocomplete', 'bricksforge'),
            'type'  => 'select',
            'default' => 'off',
            'options' => Helper::get_autocomplete_options(),
            'description' => esc_html__('If checked, you allow the browser to autocomplete the value.', 'bricksforge'),
        ];

        // Strip HTML
        $this->controls['stripHTML'] = [
            'group' => 'general',
            'label' => esc_html__('Strip HTML', 'bricksforge'),
            'type'  => 'checkbox',
            'default' => false,
            'description' => esc_html__('If checked, all HTML tags will be stripped from the output. By default, not dangerous tags are allowed.', 'bricksforge'),
        ];

        // Max Length (Characters)
        $this->controls['maxlength'] = [
            'group' => 'general',
            'label'          => esc_html__('Max Length (Characters)', 'bricksforge'),
            'type'           => 'number',
            'inline'         => true,
            'spellcheck'     => false,
            'hasDynamicData' => true,
            'default'        => '',
        ];

        // Show Max Length Counter
        $this->controls['showMaxLengthCounter'] = [
            'group' => 'general',
            'label' => esc_html__('Show Max Length Counter', 'bricksforge'),
            'type'  => 'checkbox',
            'default' => false,
        ];

        // Max Length Counter Position (Below, Inside)
        $this->controls['maxLengthCounterPosition'] = [
            'group' => 'maxLengthCounter',
            'label' => esc_html__('Max Length Counter Position', 'bricksforge'),
            'type'  => 'select',
            'options' => [
                'below' => esc_html__('Below', 'bricksforge'),
                'inside' => esc_html__('Inside', 'bricksforge'),
            ],
            'default' => 'below',
        ];

        // Counter Text ($current and $remaining as variables)
        $this->controls['maxLengthCounterText'] = [
            'group' => 'maxLengthCounter',
            'label' => esc_html__('Max Length Counter Text', 'bricksforge'),
            'type'  => 'textarea',
            'default' => 'You have {{remaining}} characters remaining. Maximum length is {{maxlength}}. Current length is {{current}}.',
            'description' => esc_html__('You can use the variables {{current}}, {{remaining}} and {{maxlength}} to display the current and maximum length of the textarea.', 'bricksforge'),
        ];

        // If "Inside", we need top, right, bottom and left
        $this->controls['maxLengthCounterInsidePositionTop'] = [
            'group' => 'maxLengthCounter',
            'label' => esc_html__('Inside Position Top', 'bricksforge'),
            'type'  => 'number',
            'units' => true,
            'css' => [
                [
                    'selector' => '.max-length-counter--inside',
                    'property' => 'top',

                ],
            ],
            'required' => ['maxLengthCounterPosition', '=', 'inside'],
        ];

        $this->controls['maxLengthCounterInsidePositionRight'] = [
            'group' => 'maxLengthCounter',
            'label' => esc_html__('Inside Position Right', 'bricksforge'),
            'type'  => 'number',
            'units' => true,
            'css' => [
                [
                    'selector' => '.max-length-counter--inside',
                    'property' => 'right',
                ],
            ],
            'required' => ['maxLengthCounterPosition', '=', 'inside'],
        ];

        $this->controls['maxLengthCounterInsidePositionBottom'] = [
            'group' => 'maxLengthCounter',
            'label' => esc_html__('Inside Position Bottom', 'bricksforge'),
            'type'  => 'number',
            'units' => true,
            'css' => [
                [
                    'selector' => '.max-length-counter--inside',
                    'property' => 'bottom',
                ],
            ],
            'required' => ['maxLengthCounterPosition', '=', 'inside'],
        ];

        $this->controls['maxLengthCounterInsidePositionLeft'] = [
            'group' => 'maxLengthCounter',
            'label' => esc_html__('Inside Position Left', 'bricksforge'),
            'type'  => 'number',
            'units' => true,
            'css' => [
                [
                    'selector' => '.max-length-counter--inside',
                    'property' => 'left',
                ],
            ],
            'required' => ['maxLengthCounterPosition', '=', 'inside'],
        ];


        // Counter Style (Typography)
        $this->controls['maxLengthCounterTypography'] = [
            'group' => 'maxLengthCounter',
            'label' => esc_html__('Max Length Counter Typography', 'bricksforge'),
            'type'  => 'typography',
            'css' => [
                [
                    'selector' => '.max-length-counter',
                    'property' => 'typography',
                ],

            ],
        ];

        // Counter Style (Margin)
        $this->controls['maxLengthCounterMargin'] = [
            'group' => 'maxLengthCounter',
            'label' => esc_html__('Max Length Counter Margin', 'bricksforge'),
            'type'  => 'spacing',
            'css' => [
                [
                    'selector' => '.max-length-counter',
                    'property' => 'margin',
                ],
            ],
        ];

        // Counter Style (Padding)
        $this->controls['maxLengthCounterPadding'] = [
            'group' => 'maxLengthCounter',
            'label' => esc_html__('Max Length Counter Padding', 'bricksforge'),
            'type'  => 'spacing',
            'css' => [
                [
                    'selector' => '.max-length-counter',
                    'property' => 'padding',
                ],
            ],
        ];

        // Counter Style (Background)
        $this->controls['maxLengthCounterBackground'] = [
            'group' => 'maxLengthCounter',
            'label' => esc_html__('Max Length Counter Background', 'bricksforge'),
            'type'  => 'color',
            'css' => [
                [
                    'selector' => '.max-length-counter',
                    'property' => 'background',
                ],
            ],
        ];

        // Counter Style (Border)
        $this->controls['maxLengthCounterBorder'] = [
            'group' => 'maxLengthCounter',
            'label' => esc_html__('Max Length Counter Border', 'bricksforge'),
            'type'  => 'border',
            'css' => [
                [
                    'selector' => '.max-length-counter',
                    'property' => 'border',
                ],
            ],
        ];

        // Counter Style (Box Shadow)
        $this->controls['maxLengthCounterBoxShadow'] = [
            'group' => 'maxLengthCounter',
            'label' => esc_html__('Max Length Counter Box Shadow', 'bricksforge'),
            'type'  => 'box-shadow',
            'css' => [
                [
                    'selector' => '.max-length-counter',
                    'property' => 'box-shadow',
                ],
            ],
        ];

        // Counter Style (Justify Content)
        $this->controls['maxLengthCounterJustifyContent'] = [
            'group' => 'maxLengthCounter',
            'label' => esc_html__('Max Length Counter Justify Content', 'bricksforge'),
            'type'  => 'justify-content',
            'css' => [
                [
                    'selector' => '.max-length-counter',
                    'property' => 'justify-content',
                ],
            ],
        ];

        // Remaining Count Typography
        $this->controls['maxLengthCounterRemainingTypography'] = [
            'group' => 'maxLengthCounter',
            'label' => esc_html__('Remaining Count Typography', 'bricksforge'),
            'type'  => 'typography',
            'css' => [
                [
                    'selector' => '.counter-remaining',
                    'property' => 'typography',
                ],
            ],
        ];

        // Current Count Typography
        $this->controls['maxLengthCounterCurrentTypography'] = [
            'group' => 'maxLengthCounter',
            'label' => esc_html__('Current Count Typography', 'bricksforge'),
            'type'  => 'typography',
            'css' => [
                [
                    'selector' => '.counter-current',
                    'property' => 'typography',
                ],
            ],
        ];

        // Max Length Count Typography
        $this->controls['maxLengthCounterMaxLengthTypography'] = [
            'group' => 'maxLengthCounter',
            'label' => esc_html__('Max Length Count Typography', 'bricksforge'),
            'type'  => 'typography',
            'css' => [
                [
                    'selector' => '.counter-max',
                    'property' => 'typography',
                ],
            ],
        ];



        $this->controls = array_merge($this->controls, Helper::get_condition_controls());
        $this->controls = array_merge($this->controls, Helper::get_advanced_controls());
        $this->controls = array_merge($this->controls, Helper::get_validation_controls());
    }

    public function render()
    {
        $settings = $this->settings;
        $parent_settings = Helper::get_nestable_parent_settings($this->element) ? Helper::get_nestable_parent_settings($this->element) : [];

        $id = $this->id ? $this->id : false;

        if (isset($settings['id']) && $settings['id']) {
            $id = $settings['id'];
        }

        $random_id = Helpers::generate_random_id(false);
        $label = isset($settings['label']) ? $settings['label'] : false;

        $show_labels = true;
        if (isset($parent_settings) && !empty($parent_settings) && !isset($parent_settings['showLabels'])) {
            $show_labels = false;
        }

        // Single Show Label
        if (isset($settings['showLabel']) && $settings['showLabel']) {
            $show_labels = true;
        }

        $placeholder = isset($settings['placeholder']) ? bricks_render_dynamic_data($settings['placeholder']) : false;
        $autocomplete = isset($settings['autocomplete']) ? $settings['autocomplete'] : 'off';
        $value = isset($settings['value']) ? bricks_render_dynamic_data($settings['value']) : '';
        $stripHTML = isset($settings['stripHTML']) ? $settings['stripHTML'] : false;
        $maxlength = isset($settings['maxlength']) ? $settings['maxlength'] : '';
        $required = isset($settings['required']) ? $settings['required'] : false;

        if (!$id && bricks_is_builder()) {
            return $this->render_element_placeholder(
                [
                    'title' => esc_html__('You have to set an ID for your element.', 'bricksforge'),
                ]
            );
        }

        /**
         * Wrapper
         */
        $this->set_attribute('_root', 'class', 'pro-forms-builder-field');
        $this->set_attribute('_root', 'class', 'form-group');
        $this->set_attribute('_root', 'data-element-id', $this->id);

        // Post Context
        if (isset($settings['postContext'])) {
            $this->set_attribute('_root', 'data-context', bricks_render_dynamic_data($settings['postContext']));
        }

        if ($id !== $this->id) {
            $this->set_attribute('_root', 'data-custom-id', $id);
        }

        // Custom Css Class
        if (isset($settings['cssClass']) && $settings['cssClass']) {
            $this->set_attribute('field', 'class', $settings['cssClass']);
        }

        /**
         * Field
         */
        $this->set_attribute('field', 'id', 'form-field-' . $random_id);
        $this->set_attribute('field', 'name', 'form-field-' . $id);
        $this->set_attribute('field', 'spellcheck', 'false');
        $this->set_attribute('field', 'data-label', $label);

        $disabled = isset($settings['disabled']) ? $settings['disabled'] : false;
        if ($disabled) {
            $this->set_attribute('field', 'disabled', 'disabled');
        }

        $readonly = isset($settings['readonly']) ? $settings['readonly'] : false;
        if ($readonly) {
            $this->set_attribute('field', 'readonly', 'readonly');
        }

        // Validation
        $validation = isset($settings['validation']) ? $settings['validation'] : false;
        if ($validation) {
            $this->set_attribute('field', 'data-validation', json_encode($validation));

            if (isset($settings['enableLiveValidation']) && $settings['enableLiveValidation'] == true) {
                $this->set_attribute('field', 'data-live-validation', 'true');
            }

            if (isset($settings['showValidationMessage']) && $settings['showValidationMessage'] == true) {
                $this->set_attribute('field', 'data-show-validation-message', 'true');
            }

            if (isset($settings['showMessageBelowField']) && $settings['showMessageBelowField'] == true) {
                $this->set_attribute('field', 'data-show-message-below-field', 'true');
            }
        }

        if ($placeholder) {
            $this->set_attribute('field', 'placeholder', $placeholder);
        }
        if ($autocomplete) {
            $this->set_attribute('field', 'autocomplete', $autocomplete);
        }
        if ($value) {
            $this->set_attribute('field', 'value', $value);
        }
        if ($maxlength) {
            $this->set_attribute('field', 'maxlength', $maxlength);
        }
        if ($required) {
            $this->set_attribute('field', 'required', $required);
        }

        // Conditions
        if (isset($settings['hasConditions']) && isset($settings['conditions']) && $settings['conditions']) {
            $this->set_attribute('_root', 'data-brf-conditions', json_encode($settings['conditions']));
        }
        if (isset($settings['conditionsRelation']) && $settings['conditionsRelation']) {
            $this->set_attribute('_root', 'data-brf-conditions-relation', $settings['conditionsRelation']);
        }

        // Required Asterisk
        if (isset($parent_settings['requiredAsterisk']) && $parent_settings['requiredAsterisk'] == true && $required) {
            $this->set_attribute("label", 'class', 'required');
        }

        // Icons
        if (isset($settings['icon'])) {
            $this->set_attribute("field-icons", 'class', 'input-icon-wrapper input-icon-wrapper--is-textarea');
            $this->set_attribute("field-icons", 'class', isset($parent_settings['iconPosition']) && $parent_settings['iconPosition'] == 'row' ? 'icon-left' : 'icon-right');

            if (isset($parent_settings['iconInset']) && $parent_settings['iconInset'] == true) {
                $this->set_attribute("field-icons", 'class', 'icon-inset');
            }

            if (isset($parent_settings['iconFocusInput']) && $parent_settings['iconFocusInput'] == true) {
                $this->set_attribute("field-icons", 'data-focus', 'true');
            }
        }

?>
        <div <?php echo $this->render_attributes('_root'); ?>>
            <?php if ($label && $show_labels) : ?>
                <label <?php echo $this->render_attributes('label'); ?> for="form-field-<?php echo $random_id; ?>"><?php echo wp_kses_post($label); ?></label>
            <?php endif; ?>
            <?php if (isset($settings['icon'])) { ?>
                <div <?php echo $this->render_attributes("field-icons"); ?>>
                    <span class="input-icon"><?php echo $this->render_icon($settings['icon']) ?></span>
                    <textarea <?php echo $this->render_attributes('field'); ?>><?php echo $value; ?></textarea>
                </div>
            <?php } else { ?>
                <textarea <?php echo $this->render_attributes('field'); ?>><?php echo $value; ?></textarea>
            <?php } ?>

            <?php if (isset($settings['showMaxLengthCounter']) && $settings['showMaxLengthCounter'] && $maxlength) {
                $counter_position = isset($settings['maxLengthCounterPosition']) ? $settings['maxLengthCounterPosition'] : 'below';
                $counter_class = 'max-length-counter';
                if ($counter_position === 'inside') {
                    $counter_class .= ' max-length-counter--inside';
                }

                // Get the counter text template
                $counter_text = isset($settings['maxLengthCounterText']) ? $settings['maxLengthCounterText'] : '{{current}}/{{maxlength}}';
            ?>
                <div class="<?php echo $counter_class; ?>" data-max-length="<?php echo $maxlength; ?>" data-counter-text="<?php echo esc_attr($counter_text); ?>">
                    <?php
                    // Set initial counter text
                    $initial_text = str_replace(
                        ['{{current}}', '{{maxlength}}', '{{remaining}}'],
                        [
                            '<span class="counter-current">0</span>',
                            '<span class="counter-max">' . $maxlength . '</span>',
                            '<span class="counter-remaining">' . $maxlength . '</span>'
                        ],
                        $counter_text
                    );
                    ?>
                    <span class="counter-text"><?php echo $initial_text; ?></span>
                </div>
            <?php } ?>
        </div>
<?php
    }
}
