<?php

namespace GriffinForms\Admin\Html\FormControls\Field\FieldOptionsTraits;

trait SelectField
{
    private function selectFieldHtml()
    {
        echo '<div class=\'griffinforms-selectfield-options-container griffinforms-field-options-container row pe-2\'>';

        if (is_array($this->value)) {
            foreach ($this->value as $group => $pairs) {
                $this->selectFieldOptionsGroup($group, $pairs);
            }
        }

        echo '<div class="griffinforms-selectfield-options-addoptionsgroup col-md-12 text-center">';
        echo '<button type="button" class="griffinforms-add-optionsgroup-btn button-primary">' . esc_html($this->lang->getText('add_options_group')) . '</button>';
        echo '</div>';
        echo '</div>';

        echo '<template class="griffinforms-selectfield-option-template">';
        $this->selectFieldOption();
        echo '</template>';

        echo '<template class="griffinforms-selectfield-optionsgroup-template">';
        $this->selectFieldOptionsGroup();
        echo '</template>';
    }

    private function selectFieldOptionsGroup($group = '', $pairs = array('' => ''))
    {
        echo '<div class=\'griffinforms-selectfield-optionsgroup griffinforms-field-optionsgroup col-md-12 mb-3 rounded p-3 bg-white\'>';

        echo '<div class=\'griffinforms-selectfield-optionsgroup-wrap row g-2\'>';

        echo '<div class=\'griffinforms-selectfield-options-groupname-wrap col-md-12 d-flex align-items-center mb-3\'>';
        echo '<div class=\'griffinforms-selectfield-options-group-handle d-inline-flex me-2\'>' . wp_kses_post($this->mIcon('drag_indicator', 'rounded', 'return')) . '</div>';
        echo '<input class=\'griffinforms-selectfield-options-groupname form-control\' type=\'text\' class=\'w-25\' placeholder=\'' . esc_attr($this->lang->getText('Options Group Name')) . '\' value=\'' . esc_attr($group) . '\'>';
        echo '</div>';

        echo '<div class=\'griffinforms-selectfield-options-pairs col-md-12 py-1\'>';

        foreach ($pairs as $text => $value) {
            $this->selectFieldOption($text, $value);
        }

        echo  '</div>';

        $this->addSelectFieldOption();
        $this->deleteSelectFieldOptionsGroup();

        echo '</div>';
        echo '</div>';
    }

    private function selectFieldOption($text = '', $value = '')
    {
        echo '<div class=\'griffinforms-selectfield-options-pair griffinforms-field-options-pair row g-2 mb-1\'>';
        echo '<div class=\'col-md-1 d-flex align-items-center justify-content-end\'><div class=\'griffinforms-selectfield-options-pair-dragbtn me-2\'>' . wp_kses_post($this->mIcon('drag_indicator', 'rounded', 'return')) . '</div></div>';
        echo '<div class=\'col-md-5\'><input class=\'griffinforms-selectfield-optionname griffinforms-field-optionname form-control\' type=\'text\' placeholder=\'' . wp_kses_post($this->lang->getText('Options Text')) . '\' value=\'' . esc_attr($text) . '\'></div>';
        echo '<div class=\'col-md-5\'><input class=\'griffinforms-selectfield-optionvalue griffinforms-field-optionvalue form-control\' type=\'text\' placeholder=\'' . esc_html($this->lang->getText('Options Value')) . '\' value=\'' . esc_html($value) . '\'></div>';
        echo '<div class=\'col-md-1\'><button type=\'button\' class=\'griffinforms-selectfield-options-pair-deletebtn ms-2 button button-small\'>' . wp_kses_post($this->mIcon('delete', 'rounded', 'return')) . '</button></div>';
        echo '</div>';
    }

    private function addSelectFieldOption()
    {
        echo '<div class=\'griffinforms-selectfield-addoption-button-wrap col-md-12 text-center pt-2\'>';
        echo '<button type=\'button\' class=\'griffinforms-add-option-btn button\'><small>' . esc_html($this->lang->getText('add_option_btn_label')) . '</small></button>';
        echo '</div>';
    }

    private function deleteSelectFieldOptionsGroup()
    {
        echo '<div class=\'griffinforms-selectfield-deleteoptionsgroup-button-wrap col-md-12 text-end pt-2\'>';
        echo '<button type=\'button\' class=\'griffinforms-delete-optionsgroup-btn button-primary\'><small>' . esc_html($this->lang->getText('delete_optionsgroup')) . '</small></button>';
        echo '</div>';
    }

    private function selectFieldJs()
    {
        echo '

        optionGroupsSortable();
        optionPairsSortable();

        function optionGroupsSortable() {
            $(".griffinforms-selectfield-options-container").sortable({
            cursor: "grabbing",
            axis: "y",
            handle: ".griffinforms-selectfield-options-group-handle",
            opacity: 0.75,
            start: function (event, ui) {
                    ui.helper.addClass("shadow-sm");
                },
            stop: function (event, ui) {
                    ui.item.removeClass("shadow-sm");
                }
            });
        }

        function optionPairsSortable() {
            $(".griffinforms-selectfield-options-pairs").sortable({
            cursor: "grabbing",
            handle: ".griffinforms-selectfield-options-pair-dragbtn",
            axis: "y",
            connectWith: ".griffinforms-selectfield-options-pairs",
            opacity: 0.75,
            start: function (event, ui) {
                },
            stop: function (event, ui) {
                }
            });
        }

        $(".griffinforms-selectfield-options-container").on("click", ".griffinforms-selectfield-options-pair-deletebtn", function() {
            var groups = $(".griffinforms-selectfield-optionsgroup");
            var group = $(this).closest(".griffinforms-selectfield-optionsgroup");
            var pairs = group.find(".griffinforms-selectfield-options-pair");

            if (groups.length === 1 && pairs.length === 1) {
                alert("' . esc_js($this->lang->getText('min_options_pairs_limit')) . '");
                return;
            }

            $(this).parents(".griffinforms-selectfield-options-pair").remove();
        });

        $(".griffinforms-selectfield-options-container").on("click",".griffinforms-add-option-btn", function(){
            var optionHtml = document.querySelector(".griffinforms-selectfield-option-template").innerHTML;
            $(this).parent().siblings(".griffinforms-selectfield-options-pairs").append(optionHtml);
        });

        $(".griffinforms-selectfield-options-container").on("click",".griffinforms-delete-optionsgroup-btn", function(){
            var groups = $(".griffinforms-selectfield-optionsgroup");
            if (groups.length > 1) {
                $(this).parents(".griffinforms-selectfield-optionsgroup").remove();
            } else {
                alert("' . esc_js($this->lang->getText('min_options_groups_limit')) . '");
            }
        });

        $(".griffinforms-selectfield-options-container").on("blur", ".griffinforms-selectfield-optionname", function(){
            var optionValue = $(this).closest(".griffinforms-selectfield-options-pair").find(".griffinforms-selectfield-optionvalue");
            if (optionValue.val().trim() === "") {
                var cleanValue = $(this).val().trim().replace(/\s+/g, \'\').toLowerCase();
                optionValue.val(cleanValue);
            }
        });

        $(".griffinforms-add-optionsgroup-btn").click(addOptionsGroup);


        function addOptionsGroup() {
            var groupCount = $(".griffinforms-selectfield-options-container .griffinforms-selectfield-optionsgroup").length;
            var maxGroups = 10;

            if (groupCount >= maxGroups) {
                alert("' . esc_js($this->lang->getText('max_optgroup_limit')) . '");
                return;
            }

            var optionsGroupHtml = document.querySelector(".griffinforms-selectfield-optionsgroup-template").innerHTML;
            $(optionsGroupHtml).insertBefore(".griffinforms-selectfield-options-addoptionsgroup");
            optionPairsSortable();
            scrollToBottom();
        }

        function scrollToBottom() {
            $(".griffinforms-selectfield-options-container").animate({ scrollTop: $(".griffinforms-selectfield-options-container")[0].scrollHeight}, 1000);
        }

        $(".griffinforms-selectfield-options-container").on("keydown", ".griffinforms-selectfield-optionname, .griffinforms-selectfield-optionvalue", function(e) {
            if (e.keyCode === 13) {
                e.preventDefault();
                var group = $(this).closest(".griffinforms-selectfield-optionsgroup");
                var pairs = group.find(".griffinforms-selectfield-options-pair");
                var isLast = $(this).closest(".griffinforms-selectfield-options-pair").is(pairs.last());

                if (isLast) {
                    var optionHtml = document.querySelector(".griffinforms-selectfield-option-template").innerHTML;
                    group.find(".griffinforms-selectfield-options-pairs").append(optionHtml);
                }
            }
        });
        ';
    }
}
