<?php
/**
 * Maho
 *
 * @category    design
 * @package     default_default
 * @copyright   Copyright (c) 2006-2020 Magento, Inc. (https://magento.com)
 * @copyright   Copyright (c) 2021-2024 The OpenMage Contributors (https://openmage.org)
 * @copyright   Copyright (c) 2024 Maho (https://mahocommerce.com)
 * @license     https://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

/** @var Mage_Adminhtml_Block_Catalog_Product_Attribute_Set_Main $this */
?>
<div class="content-header">
    <table cellspacing="0">
        <tr>
            <td style="width:50%;"><h3><?= $this->escapeHtml($this->_getHeader()) ?></h3></td>
            <td class="form-buttons">
                <?= $this->getBackButtonHtml() ?>
                <?= $this->getResetButtonHtml() ?>
                <?= $this->getDeleteButtonHtml() ?>
                <?= $this->getSaveButtonHtml() ?>
            </td>
        </tr>
    </table>
</div>
<table cellspacing="0" width="100%">
    <tr>
        <td width="360" style="border-right:1px solid #ddd; padding:0 23px 23px 0;" class="edit-attribute-set">
            <?= $this->getSetFormHtml() ?>
        </td>
        <td width="320" style="border-right:1px solid #ddd; padding:0 23px 23px 23px;">
            <div class="content-header skip-header">
            <table cellspacing="0">
                    <tbody>
                        <tr>
                            <td><h3><?= Mage::helper('catalog')->__('Groups') ?></h3></td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <?php if (!$this->getIsReadOnly()): ?>
                <p><?= $this->getAddGroupButton() ?>&nbsp;<?= $this->getDeleteGroupButton() ?></p>
                <p class="note-block"><?= Mage::helper('catalog')->__('Double click on a group to rename it') ?></p>
            <?php endif ?>

            <?= $this->getSetsFilterHtml() ?>
            <?= $this->getGroupTreeHtml() ?>
        </td>
        <td style="padding:0 0 23px 23px;">
            <div class="content-header skip-header">
                <table cellspacing="0">
                    <tbody>
                        <tr>
                            <td><h3><?= Mage::helper('catalog')->__('Unassigned Attributes') ?></h3></td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div id="tree-div2" style="height:550px;margin-top:5px;overflow:auto"></div>
            <script type="text/javascript">
            //<![CDATA[
            var allowDragAndDrop = <?= ($this->getIsReadOnly() ? 'false' : 'true') ?>;
            var canEditGroups = <?= ($this->getIsReadOnly() ? 'false' : 'true') ?>;

            var TreePanels = function() {
                // shorthand
                var Tree = Ext.tree;

                return {
                    init : function(){
                        // yui-ext tree

                        var tree = new Ext.tree.TreePanel('tree-div1', {
                            animate:false,
                            loader: false,
                            enableDD:allowDragAndDrop,
                            containerScroll: true,
                            rootVisible: false
                        });

                        // set the root node
                        this.root = new Ext.tree.TreeNode({
                            text: 'ROOT',
                            allowDrug:false,
                            allowDrop:true,
                            id:'1'
                        });

                        tree.setRootNode(this.root);
                        buildCategoryTree(this.root, <?= $this->getGroupTreeJson() ?>);
                        // render the tree
                        tree.render();
                        this.root.expand(false, false);
                        tree.expandAll();

                        this.ge = new Ext.tree.TreeEditor(tree, {
                            allowBlank:false,
                            blankText:'<?= Mage::helper('core')->jsQuoteEscape(Mage::helper('catalog')->__('A name is required')) ?>',
                            selectOnFocus:true,
                            cls:'folder'
                        });

                        this.ge.completeEdit = function(remainVisible) {
                            if (!this.editing) {
                                return;
                            }
                            this.editNode.attributes.input = this.getValue();
                            this.setValue(this.getValue().escapeHTML());
                            return Ext.tree.TreeEditor.prototype.completeEdit.call(this, remainVisible);
                        };

                        this.ge.triggerEdit = function(node) {
                            this.completeEdit();
                            node.text = node.attributes.input;
                            node.attributes.text = node.attributes.input;
                            this.editNode = node;
                            this.startEdit(node.ui.textNode, node.text);
                        };

                        this.root.addListener('beforeinsert', editSet.leftBeforeInsert);
                        this.root.addListener('beforeappend', editSet.leftBeforeInsert);

                        //this.ge.addListener('beforerender', editSet.editGroup);
                        this.ge.addListener('beforeshow', editSet.editGroup);
                        this.ge.addListener('beforecomplete', editSet.beforeRenameGroup);
                        //this.ge.addListener('startedit', editSet.editGroup);

                        //-------------------------------------------------------------

                        var tree2 = new Ext.tree.TreePanel('tree-div2', {
                            animate:false,
                            loader: false,
                            enableDD:allowDragAndDrop,
                            containerScroll: true,
                            rootVisible: false,
                            lines:false
                        });

                        // set the root node
                        this.root2 = new Ext.tree.TreeNode({
                            text: 'ROOT',
                            draggable:false,
                            id:'free'
                        });
                        tree2.setRootNode(this.root2);
                        buildCategoryTree(this.root2, <?= $this->getAttributeTreeJson() ?>);

                        this.root2.addListener('beforeinsert', editSet.rightBeforeInsert);
                        this.root2.addListener('beforeappend', editSet.rightBeforeAppend);

                        this.root2.addListener('append', editSet.rightAppend);
                        this.root2.addListener('remove', editSet.rightRemove);
                        // render the tree
                        tree2.render();
                        this.root2.expand(false, false);
                        tree2.expandAll();
                    },

                    rebuildTrees : function(){
                        editSet.req.attributes = new Array();
                        rootNode = TreePanels.root;
                        var gIterator = 0;
                        for( i in rootNode.childNodes ) {
                            if(rootNode.childNodes[i].id) {
                                var group = rootNode.childNodes[i];
                                editSet.req.groups[gIterator] = new Array(group.id, group.attributes.input.strip(), (gIterator+1));
                                var iterator = 0
                                for( j in group.childNodes ) {
                                    iterator ++;
                                    if( group.childNodes[j].id > 0 ) {
                                        editSet.req.attributes[group.childNodes[j].id] = new Array(group.childNodes[j].id, group.id, iterator, group.childNodes[j].attributes.entity_id);
                                    }
                                }
                                iterator = 0;
                            }
                            gIterator ++;
                        }

                        editSet.req.not_attributes = new Array();
                        rootNode = TreePanels.root2;

                        var iterator = 0;
                        for( i in rootNode.childNodes ) {
                            if(rootNode.childNodes[i].id) {
                                if( rootNode.childNodes[i].id > 0 ) {
                                    editSet.req.not_attributes[iterator] = rootNode.childNodes[i].attributes.entity_id;
                                }
                                iterator ++;
                            }
                        }
                    }
                };
            }();

            function buildCategoryTree(parent, config){
                if (!config) return null;
                if (parent && config && config.length){
                    for (var i = 0; i < config.length; i++) {
                        config[i].input = config[i].text;
                        config[i].text = config[i].text.escapeHTML();
                        var node = new Ext.tree.TreeNode(config[i]);
                        parent.appendChild(node);
                        node.addListener('click', editSet.register);
                        node.addListener('beforemove', editSet.groupBeforeMove);
                        node.addListener('beforeinsert', editSet.groupBeforeInsert);
                        node.addListener('beforeappend', editSet.groupBeforeInsert);
                        if( config[i].children ) {
                            for( j in config[i].children ) {
                                if(config[i].children[j].id) {
                                    newNode = new Ext.tree.TreeNode(config[i].children[j]);
                                    node.appendChild(newNode);
                                    newNode.addListener('click', editSet.unregister);
                                }
                            }
                        }
                    }
                }
            }

            var editSet = function() {
                return {
                    register : function(node) {
                        editSet.currentNode = node;
                    },

                    unregister : function() {
                        editSet.currentNode = false;
                    },

                    submit : function() {
                        if( TreePanels.root.firstChild == TreePanels.root.lastChild ) {
                            return;
                        }

                        if( editSet.SystemNodesExists(editSet.currentNode) ) {
                            alert('<?= Mage::helper('core')->jsQuoteEscape(Mage::helper('catalog')->__('This group contains system attributes. Please move system attributes to another group and try again.')) ?>');
                            return;
                        }

                        if (editSet.ConfigurableNodeExists(editSet.currentNode)) {
                            alert('<?= Mage::helper('core')->jsQuoteEscape(Mage::helper('catalog')->__('This group contains attributes, used in configurable products. Please move these attributes to another group and try again.')) ?>');
                            return;
                        }

                        if( editSet.currentNode && editSet.currentNode.attributes.cls == 'folder' ) {
                            TreePanels.root.removeChild(editSet.currentNode);
                            for( i in editSet.currentNode.childNodes ) {
                                if( editSet.currentNode.childNodes[i].id ) {
                                    child = editSet.currentNode.childNodes[i];
                                    newNode = new Ext.tree.TreeNode(child.attributes);

                                    if( child.attributes.is_user_defined == 1 ) {
                                        TreePanels.root2.appendChild(newNode);
                                    }
                                }
                            }
                            editSet.req.removeGroups[editSet.currentNode.id] = editSet.currentNode.id;
                            editSet.currentNode = false;
                        }
                    },

                    SystemNodesExists : function(currentNode) {
                        for( i in currentNode.childNodes ) {
                            if( currentNode.childNodes[i].id ) {
                                child = editSet.currentNode.childNodes[i];
                                if( child.attributes.is_user_defined != 1 ) {
                                    return true;
                                }
                            }
                        }
                    },

                    ConfigurableNodeExists : function(currentNode) {
                        for (var i in currentNode.childNodes ) {
                            if (currentNode.childNodes[i].id) {
                                child = editSet.currentNode.childNodes[i];
                                if (child.attributes.is_configurable) {
                                    return true;
                                }
                            }
                        }
                        return false;
                    },

                    rightAppend : function(node) {
                        return;
                    },

                    addGroup : function() {
                        var group_name = prompt("<?= Mage::helper('core')->jsQuoteEscape(Mage::helper('catalog')->__('Please enter a new group name')) ?>","");
                        group_name = group_name.strip();
                        if( group_name == '' ) {
                            this.addGroup();
                        } else if( group_name != false && group_name != null && group_name != '' ) {

                            if (!editSet.validateGroupName(group_name, 0)) {
                                return;
                            }

                            var newNode = new Ext.tree.TreeNode({
                                    text : group_name.escapeHTML(),
                                    input: group_name,
                                    cls : 'folder',
                                    allowDrop : true,
                                    allowDrag : true
                                });
                            TreePanels.root.appendChild(newNode);
                            newNode.addListener('beforemove', editSet.groupBeforeMove);
                            newNode.addListener('beforeinsert', editSet.groupBeforeInsert);
                            newNode.addListener('beforeappend', editSet.groupBeforeInsert);
                            newNode.addListener('click', editSet.register);
                        }
                    },

                    editGroup : function(obj) {
                        if( obj.editNode.attributes.cls != 'folder' || !canEditGroups) {
                             TreePanels.ge.cancelEdit();
                             return false;
                        }
                    },

                    beforeRenameGroup : function(obj, after, before) {
                        if (editSet.validateGroupName(after, obj.editNode.id)) {
                            return true;
                        }
                        obj.field.el.dom.value = before;
                        return false;
                    },

                    validateGroupName : function(name, exceptNodeId) {
                        name = name.strip();
                        if (name === '') {
                            return false;
                        }
                        for (var i=0; i < TreePanels.root.childNodes.length; i++) {
                            if (TreePanels.root.childNodes[i].text.toLowerCase() == name.toLowerCase() && TreePanels.root.childNodes[i].id != exceptNodeId) {
                                errorText = "<?= Mage::helper('core')->jsQuoteEscape(Mage::helper('catalog')->__('Attribute group with the \"/name/\" name already exists')) ?>";
                                alert(errorText.replace("/name/",name));
                                return false;
                            }
                        }
                        return true;
                    },

                    save : function() {
                        $('messages').update();
                        TreePanels.rebuildTrees();
                        var _validator = new Validation('set_prop_form', {onSubmit:false});
                        if( !_validator.validate() ) {
                            return;
                        }
                        editSet.req.attribute_set_name = $('attribute_set_name').value;
                        if (!editSet.req.form_key) {
                            editSet.req.form_key = FORM_KEY;
                        }
                        var req = {data : Ext.util.JSON.encode(editSet.req)};
                        var con = new Ext.lib.Ajax.request('POST', '<?= $this->getMoveUrl() ?>', {success:editSet.success,failure:editSet.failure}, req);
                    },

                    success : function(o) {
                        var response = Ext.util.JSON.decode(o.responseText);
                        if( response.error ) {
                            $('messages').update(response.message);
                        } else if( response.ajaxExpired && response.ajaxRedirect ){
                            setLocation(response.ajaxRedirect);
                        } else if( response.url ){
                            setLocation(response.url);
                        } else if( response.message ) {
                            $('messages').update(response.message);
                        }
                    },

                    failure : function(o) {
                        alert('<?= Mage::helper('core')->jsQuoteEscape(Mage::helper('catalog')->__('Unable to complete this request.')) ?>');
                    },

                    groupBeforeMove : function(tree, nodeThis, oldParent, newParent) {
                        if( newParent.attributes.cls == 'folder' && nodeThis.attributes.cls == 'folder' ) {
                            return false;
                        }

                        if( newParent == TreePanels.root && nodeThis.attributes.cls != 'folder' ) {
                            return false;
                        }
                    },

                    rightBeforeAppend : function(tree, nodeThis, node, newParent) {
                        if (node.attributes.is_user_defined == 0) {
                            alert('<?= Mage::helper('core')->jsQuoteEscape(Mage::helper('catalog')->__('You cannot remove system attribute from this set.')) ?>');
                            return false;
                        }
                        else if (node.attributes.is_configurable == 1) {
                            alert('<?= Mage::helper('core')->jsQuoteEscape(Mage::helper('catalog')->__('This attribute is used in configurable products. You cannot remove it from the attribute set.')) ?>');
                            return false;
                        }
                        else {
                            return true;
                        }
                    },

                    rightBeforeInsert : function(tree, nodeThis, node, newParent) {
                        var empty = TreePanels.root2.findChild('id', 'empty');
                        if( empty ) {
                            return false;
                        }

                        if (node.attributes.is_user_defined == 0) {
                            alert('<?= Mage::helper('core')->jsQuoteEscape(Mage::helper('catalog')->__('You cannot remove system attribute from this set.')) ?>');
                            return false;
                        }
                        else if (node.attributes.is_configurable == 1) {
                            alert('<?= Mage::helper('core')->jsQuoteEscape(Mage::helper('catalog')->__('This attribute is used in configurable products. You cannot remove it from the attribute set.')) ?>');
                            return false;
                        }
                        else {
                            return true;
                        }
                    },

                    groupBeforeInsert : function(tree, nodeThis, node, newParent) {
                        if( node.allowChildren ) {
                            return false;
                        }
                    },

                    rightAppend : function(tree, nodeThis, node) {
                        var empty = TreePanels.root2.findChild('id', 'empty');
                        if( empty && node.id != 'empty' ) {
                            TreePanels.root2.removeChild(empty);
                        }
                    },

                    rightRemove : function(tree, nodeThis, node) {
                        if( nodeThis.firstChild == null && node.id != 'empty' ) {
                            var newNode = new Ext.tree.TreeNode({
                                    text : '<?= Mage::helper('core')->jsQuoteEscape(Mage::helper('catalog')->__('Empty')) ?>',
                                    id : 'empty',
                                    cls : 'folder',
                                    is_user_defined : 1,
                                    allowDrop : false,
                                    allowDrag : false
                                });
                            TreePanels.root2.appendChild(newNode);
                        }
                    },

                    leftBeforeInsert : function(tree, nodeThis, node, newParent) {
                        if( node.allowChildren == false ) {
                            return false;
                        }
                    }
                }
            }();

            function initVars() {
                editSet.req = {};
                editSet.req.attributes = false;
                editSet.req.groups = new Array();
                editSet.req.not_attributes = false;
                editSet.req.attribute_set_name = false;
                editSet.req.removeGroups = new Array();
            }

            initVars();
            Ext.EventManager.onDocumentReady(TreePanels.init, TreePanels, true);
            //]]>
            </script>
        </td>
    </tr>
</table>
