<?php

namespace GriffinForms\Admin\Html\FormControls\Form;

class SelectItem extends \GriffinForms\Admin\Html\FormControls\Form\Format
{
    protected $sql;
    protected $item;
    protected $item_status;

    protected $name_id;
    protected $clear_id;

    /**
     * Sets the ID used for the item name display element.
     */
    public function setNameId()
    {
        $this->name_id = 'griffinforms-current-' . esc_attr($this->purgestring($this->name)) . '-name';
    }

    /**
     * Sets the ID used for the remove selection button element.
     */
    public function setClearId()
    {
        $this->clear_id = 'griffinforms-clear-' . esc_attr($this->purgestring($this->name)) . '-selection';
    }
    
    /**
     * Loads the item if the value is valid. Sets item status to 'default' if not found.
     */
    protected function setItem()
    {
        $item_class = '\GriffinForms\Items\\' . $this->data['item_type'];
        $this->item = new $item_class();
        
        if ($this->value == 0) {
            $this->item_status = 'default';
            return;
        }
                
        if (is_numeric($this->value) and $this->sql->itemExists($this->data['item_type'], $this->value)) {
            $this->item_status = true;
            $this->item->loadItem($this->value);
        } else {
            $this->item_status = 'default';
        }
    }
        
    /**
     * Outputs the main HTML for the item selector including modals, display box, and remove button.
     */
    public function html()
    {
        $this->createItemModal();
        $this->selectItemModal();
        echo '<div class="row"' . esc_attr($this->css_id) . '>';
        echo '<div class="col-md-12 mb-3" id="griffinforms-' . esc_attr($this->data['item_type']) . 'selection-wrap">';
        echo '<span id="griffinforms-' . esc_attr($this->data['item_type']) . 'selection-box" class="p-2 border bg-white rounded">';
        $this->selectItemOption();
        echo '</span>';
        $this->removeItemButton();
        echo '</div>';
        echo '</div>';
        
    }
    
    /**
     * Renders the currently selected item's label and attaches modal trigger attributes.
     */
    protected function selectItemOption()
    {
        if ($this->item_status === 'default') {
            $name = $this->lang->getText('default_' . $this->data['item_type'] . '_name');
            $value = 0;
        } elseif ($this->item_status == true) {
            $name = $this->item->getProp('name');
            $value = $this->value;
        } else {
            $name = $this->lang->getText('select_' . $this->data['item_type']);
            $value = 0;
        }
        
        $this->itemIcon();
        echo '<span class="me-2 align-middle small fw-bold" id="' . esc_attr($this->name_id) . '" data-bs-toggle="modal" data-bs-target="#griffinforms-select' . esc_attr($this->purgestring($this->name)) . '-modal" data-item-type="' . esc_attr($this->data['item_type']) . '" data-item-id="' . esc_attr($value) . '" role="button">';
        echo esc_html($name);
        echo '</span>';

        // Remove button logic moved to removeItemButton()
        
    }
    
    /**
     * Renders the icon image for the selected item type.
     */
    protected function itemIcon()
    {
        $icon = $this->item->getProp('icon');
        if (isset($icon)) {
            $location = $this->config->getRootUrl() . 'admin/images/' . $this->data['item_type'] . '/' . $icon . '.png';
        } else {
            $location = $this->config->getRootUrl() . 'admin/images/' . $this->data['item_type'] . '.png';
        }
        
       echo '<img id="griffinforms-current-' . esc_attr($this->purgestring($this->name)) . '-icon" class="me-2" height="16" src="' . esc_url($location) . '">';
    }

    /**
     * Outputs the remove button. Visibility is toggled based on item status.
     */
    protected function removeItemButton()
    {
        $label = $this->lang->getText('remove_item_label');
        $style = ($this->item_status === 'default' || $this->value == 0) ? ' style="visibility: hidden;"' : '';

        echo '<button type="button" class="button ms-2 align-baseline" id="' . esc_attr($this->clear_id) . '"' . $style . '>';
        echo esc_html($label);
        echo '</button>';
    }
    
    /**
     * Loads the modal for selecting an existing item.
     */
    protected function selectItemModal()
    {
        $data = array('name'=> $this->purgestring($this->name), 'item_type' => $this->data['item_type']);
        $this->newModal('selectItem', 'modal-lg', $data);
    }
    
    /**
     * Loads the modal for creating a new item.
     */
    protected function createItemModal()
    {
        $for = 'create' . $this->data['item_type'];
        $data = array('name'=> $this->purgestring($this->name), 'item_type' => $this->data['item_type']);
        $this->newModal($for, 'modal-lg', $data);
    }

    /**
     * Adds JavaScript for handling UI interactions:
     * - Hides remove button if no item selected on load.
     * - Updates icon and label on clear.
     * - Responds to custom item selection event to update UI.
     */
    public function fieldJs()
    {
        $name = $this->purgestring($this->name);
        $item_type = $this->data['item_type'];
        $default_icon_url = $this->config->getRootUrl() . 'admin/images/' . $item_type . '/default.png';
        $select_label = $this->lang->getText('select_' . $item_type);

        $js = '
            jQuery(document).ready(function($) {
                var removeButton = $("#griffinforms-clear-' . esc_js($name) . '-selection");
                var itemName = $("#griffinforms-current-' . esc_js($name) . '-name");

                // Hide or show remove button on initial load based on data-item-id
                removeButton.css("visibility", "hidden");

                if (parseInt(itemName.attr("data-item-id")) > 0) {
                    removeButton.css("visibility", "visible");
                }

                // Update icon, label, and button visibility when item is cleared
                removeButton.on("click", function() {
                    itemName.text("' . esc_js($select_label) . '").attr("data-item-id", "0");
                    $("#griffinforms-current-' . esc_js($name) . '-icon").attr("src", "' . esc_url($default_icon_url) . '");
                    removeButton.css("visibility", "hidden");
                });

                // Show remove button when a new item is selected via event
                $(document).on("griffinforms:itemSelectionChanged", function(event, data) {
                    if (data.itemType === "' . esc_js($name) . '" && parseInt(data.itemId) > 0) {
                        removeButton.css("visibility", "visible");
                    }
                });
            });
        ';
        wp_add_inline_script('griffinforms-global-js', $js);
    }
}