<?php
defined('_JEXEC') or die('Restricted access');

/**
* @package OS CCK
* @copyright 2020 OrdaSoft.
* @author Andrey Kvasnevskiy(akbet@mail.ru),Roman Akoev (akoevroman@gmail.com)
* @link http://ordasoft.com/cck-content-construction-kit-for-joomla.html
* @description OrdaSoft Content Construction Kit
*/

class AdminViewEntity
{


    static function showEntities($option, $rows, $pageNav)
    {

        global $doc, $app;
        $html = "<div class='os_cck_caption' ><img src='./components/com_os_cck/images/os_cck_logo.png' alt ='Config' />" . cck_lang_text("COM_OS_CCK_ADMIN_ENTITIES") . "</div>";
        $app = JFactory::getApplication();
        $app->JComponentTitle = $html;

        $form_name = 'adminForm';
        $form_id = 'adminForm' ;
        $table = new os_cckViewTable($form_name, $form_id, 'cck-orders-main cck-instanceis-main', 'index.php?option=com_os_cck&task=manage_entities', 'manage_entities');

        $what_check = 'instance' ;
        $table->create_button('Edit', 'edit_entity', 
            JURI::root() . 'components/com_os_cck/images/btn_edit.png', 'fa-pencil-square-o','',$what_check);
        $table->create_button('Add', 'add_entity', 
            JURI::root() . 'components/com_os_cck/images/btn_add.png', 'fa-plus');
        $table->create_button(cck_lang_text("COM_OS_CCK_LABEL_DELETE"), 'delete_entity', 
            JURI::root() . 'components/com_os_cck/images/btn_d.png', 'fa-close','',$what_check);
        
        $table->limitbox = '<div class="btn-group pull-right hidden-phone">
        <label for="limit" class="element-invisible">'. cck_lang_text('OS_LIB_SEARCH_SEARCHLIMIT_DESC') .'</label>'. $pageNav->getLimitBox() .'</div>';

        $table->create_first_row_collumn(JHtml::_('grid.checkall'), 'width:3%;', '');
        $table->create_first_row_collumn(cck_lang_text("COM_OS_CCK_LABEL_ID"), 'width:5%;', '');
        $table->create_first_row_collumn(cck_lang_text("COM_OS_CCK_ENTITIES_NAME"), 'width:25%;', '');
        $table->create_first_row_collumn(cck_lang_text("COM_OS_CCK_ENTITIES_TYPE"), 'width:25%;', '');
        $table->create_first_row_collumn(cck_lang_text("COM_OS_CCK_ENTITIES_PUBLISHED"), 'width:10%;', '');

        $i = 0;
        foreach ($rows AS $row) {
            $entity_data = array();
            $onclick = (version_compare(JVERSION, "1.6.0", "lt")) ? "isChecked(this.checked);" : "Joomla.isChecked(this.checked);";
            

            $entity_data[] = '<input type="checkbox" id="cb'. $i .'" name="eid[]" value="'.$row->eid.'" onClick="'.$onclick.'"/>';
            $entity_data[] = $row->eid;
            $entity_data[] = '<a href="#edit_entety" onClick="return cckSendForm(\'cb'.$i.'\',\'edit_entity\',\''.$form_name.'\')">'.$row->name.'</a>';
            $entity_data[] = $row->type;

            $task = $row->published ? 'unpublish_entities' : 'publish_entities';
            $alt = $row->published ? 'Unpublish' : 'Publish';
            $img = $row->published ? 'tick.png' : 'publish_x.png';
            $img = "components/com_os_cck/images/{$img}";

            $entity_data[] = '<a href="javascript: void(0);" onClick="return cckSendForm(\'cb'.$i.'\',\''.$task.'\',\''.$form_name.'\')"> <img src="'.$img.'" width="12" height="12" border="0" alt="'.$alt.'"/> </a>';
            $first_row_data_class = 'row' . ($i % 2) . ' '; 
            $i++;
            $table->create_first_row_data($entity_data, $first_row_data_class);
        }

//        $table->paginator = $pageNav->getListFooter();
        $table->pageNav = $pageNav;
        echo $table->viewTable();

    }


    static function editEntity($option, &$row, $entity_type, $entity_list)
    {
        global $doc, $cck_entity_configuration;
        
//        $doc->addStyleSheet(JURI::root() . "components/com_os_cck/assets/bootstrap/css/bootstrap.css");
        
//        if (version_compare(JVERSION, "4.0.0", "ge")) {
//            $doc->addStyleSheet(JURI::root() . "/media/vendor/codemirror/lib/codemirror.css");
//            addCodeMirrorsScriptJ4();
//        } else {
//            
//            $doc->addStyleSheet(JURI::root() . "/media/editors/codemirror/lib/codemirror.css");
//            addCodeMirrorsScript();
//        }
//        echo '11111111111111113'; return;
//        if (version_compare(JVERSION, "4.0.0-alpha10", "ge")) {
//            $doc->addStyleSheet(JURI::root() . "components/com_os_cck/assets/css/editLayout-j4.css");
//        }
        
        includeJavaScriptCCK("components/com_os_cck/assets/bootstrap/js/bootstrapCCK.js");
        $app = JFactory::getApplication();
        $html = "<div class='os_cck_caption' ><img src='./components/com_os_cck/images/os_cck_logo.png' alt ='Config' />" . cck_lang_text("COM_OS_CCK_ADMIN_ENTITIES") . "</div>";
        $app->JComponentTitle = $html;
        
        $access_option = array();
        $access_option[] = JHTML::_('select.option','0','Off');
        $access_option[] = JHTML::_('select.option','1','On');
        
        $meta_title_option = array();
        $meta_title_option[] = JHTML::_('select.option','0','Do not use');
        $meta_title_option[] = JHTML::_('select.option','1','From system (Do not change)');
        $meta_title_option[] = JHTML::_('select.option','2','From Instance/Category (From the title field if empty)');
        $meta_title_option[] = JHTML::_('select.option','3','From Instance/Category (From System -  if the field is empty)');

        $meta_description_option = array();
        $meta_description_option[] = JHTML::_('select.option','0','Do not use');
        $meta_description_option[] = JHTML::_('select.option','1','From system (Do not change)');
        $meta_description_option[] = JHTML::_('select.option','2','From Instance/Category (None if the field is empty)');
        $meta_description_option[] = JHTML::_('select.option','3','From Instance/Category (From System -  if the field is empty)');
        
        $meta_keywords_option = array();
        $meta_keywords_option[] = JHTML::_('select.option','0','Do not use');
        $meta_keywords_option[] = JHTML::_('select.option','1','From system (Do not change)');
        $meta_keywords_option[] = JHTML::_('select.option','2','From Instance/Category (None if the field is empty)');
        $meta_keywords_option[] = JHTML::_('select.option','3','From Instance/Category (From System -  if the field is empty)');
        
        $gtree = get_group_children_tree_cck_without_options();
        
        if($row->eid != null){
            
            $check_access_instances_selected = (isset($cck_entity_configuration[$row->eid]['check_access_instances'])) ? $cck_entity_configuration[$row->eid]['check_access_instances'] : '1';
            $check_access_fields_selected = (isset($cck_entity_configuration[$row->eid]['check_access_fields'])) ? $cck_entity_configuration[$row->eid]['check_access_fields'] : '1';
            $check_access_categories_selected = (isset($cck_entity_configuration[$row->eid]['check_access_categories'])) ? $cck_entity_configuration[$row->eid]['check_access_categories'] : '1';
            $max_product_download = (isset($cck_entity_configuration[$row->eid]['max_product_download'])) ? $cck_entity_configuration[$row->eid]['max_product_download'] : '0';
            $days_for_product_download = (isset($cck_entity_configuration[$row->eid]['days_for_product_download'])) ? $cck_entity_configuration[$row->eid]['days_for_product_download'] : '0';
            $redirect_missing_instance = (isset($cck_entity_configuration[$row->eid]['redirect_missing_instance'])) ? $cck_entity_configuration[$row->eid]['redirect_missing_instance'] : '';
            $redirect_missing_category = (isset($cck_entity_configuration[$row->eid]['redirect_missing_category'])) ? $cck_entity_configuration[$row->eid]['redirect_missing_category'] : '';
            $files_eid = $row->eid;
            $meta_title_source_selected = (isset($cck_entity_configuration[$row->eid]['meta_title_source'])) ? $cck_entity_configuration[$row->eid]['meta_title_source'] : 1;
            $meta_description_source_selected = (isset($cck_entity_configuration[$row->eid]['meta_description_source'])) ? $cck_entity_configuration[$row->eid]['meta_description_source'] : 1;
            $meta_keywords_source_selected = (isset($cck_entity_configuration[$row->eid]['meta_keywords_source'])) ? $cck_entity_configuration[$row->eid]['meta_keywords_source'] : 1;
        }else{
            $check_access_instances_selected = '1';
            $check_access_fields_selected = '1';
            $check_access_categories_selected = '1';
            $max_product_download = '0';
            $days_for_product_download = '0';
            $redirect_missing_instance = '';
            $redirect_missing_category = '';
            $files_eid = '(The entity id will appear after saving)';
            $meta_title_source_selected = 1;
            $meta_description_source_selected = 1;
            $meta_keywords_source_selected = 1;
        }
        $disable = '';
        //var_dump($entity_type);
        
        if($entity_type == 'joomla_user'){
            if (version_compare(JVERSION, "4.0.0-alpha10", "ge")) {
                $joom_user = JFactory::getUser();

                JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
                JPluginHelper::importPlugin('user');
                JForm::addFormPath(JPATH_SITE . '/components/com_users/forms');

                $user_profile_form = JForm::getInstance('com_users.user', 'profile');

                $offset = 0;
                $plug_params = 1;
                 //run mambot onPrepareContent on plug_row object
                // Trigger the onContentPrepare event.
                $results2 = JFactory::getApplication()->triggerEvent('onContentPrepareData', array("com_users.user", $joom_user));
                $results = JFactory::getApplication()->triggerEvent('onContentPrepareForm', array($user_profile_form, $joom_user));

                $user_profile_form->bind($joom_user);
                
                $user_profile = JUserHelper::getProfile($joom_user->id);
                $fieldsets = $user_profile_form->getFieldsets();

            }else{
                $user = JFactory::getUser();
                // Load the fields helper
                JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
                // Gets the fields associated with the 'com_users.user' instance
                // Since we give an actual object instance (and not, for example, just the id), in returned $customFields there will be a 'value' property for every additional fields
                $customFields = FieldsHelper::getFields('com_users.user');

                $dispatcher = JDispatcher::getInstance();
                JPluginHelper::importPlugin('user');
                JForm::addFormPath(JPATH_SITE . '/plugins/user/profile');
    
                $user_profile_form = JForm::getInstance('com_users.user', 'profile');
                $results2 = $dispatcher->trigger('onContentPrepareData', array('com_users.user', $user));
                $results = $dispatcher->trigger('onContentPrepareForm', array($user_profile_form, $user));
                $user_profile_form->bind($user);

                $user_profile = JUserHelper::getProfile($user->id);
                $fieldsets = $user_profile_form->getFieldsets();
            }
            if($row->eid == null){
                $row->name = 'Joomla User';
            }
            //$disable = 'disabled="disabled"';
            
            //$user_test = new JUser();
            
            //$fields = $user_profile_form->getFieldset($fieldsets['fields-0']->name);
//            var_dump($fields['com_fields_subject']->label);
//            var_dump($customFields);
//            var_dump($fieldsets);
            
            //$form = JForm::getInstance('myform', __DIR__ ."/test.xml");
        }
        ?>
        <script language="javascript" type="text/javascript">
            Joomla.submitbutton = function (pressbutton) {
                
                var form = document.adminForm;
                var isset_id = false
                var isset_title = false
                jQuerOs('select').each(function(){
                    if(jQuerOs(this).val() == 'id'){
                        isset_id = true
                    }else if(jQuerOs(this).val() == 'title'){
                        isset_title = true
                    }

                })

                var selects = jQuerOs('select')

                if (pressbutton == "cancel_edit_entity") {
                    Joomla.submitform(pressbutton);
                    return true;
                }
                if (form.name.value == '') {
                    alert("<?php echo "Entity name cant be empty"; ?>");
                    return;
                }else if(jQuerOs('[name=type]').val() == 'custom_sql' && (isset_id == false || isset_title == false)){
                    alert("<?php echo "The ID and Title values must be selected"; ?>");
                    return;
                } else {
                    Joomla.submitform(pressbutton);
                }
            }
            
            function checkQuery(){
//                var query = JSON.stringify(jQuerOs('[name=sql_select]').val());
                var query = jQuerOs('[name=sql_select]').val();
                
                jQuerOs.ajax({
                    dataType: "json",
                    type: 'POST',
                    url: '<?php echo JURI::base(); ?>/index.php?option=com_os_cck&format=raw',
                    data: {
                        task: 'check_custom_query',
                        query: query,
                    },
                    success: function(data){
                        if(data.success){
                            alert('Ok')
                        }else{
                            alert(data.errorMsg)
                        }
                        
                    },
                    error: function(data){
                        
                    }
                })
                
            }
            
            function loadFields(){
                var query = jQuerOs('[name=sql_select]').val();
                
                jQuerOs.ajax({
                    dataType: "json",
                    type: 'POST',
                    url: '<?php echo JURI::base(); ?>/index.php?option=com_os_cck&format=raw',
                    data: {
                        task: 'load_fields_form_custom_sql',
                        query: query,
                    },
                    success: function(data){
                        if(data.success){
//                            console.log('111111111111', data.fields);
                            for(var key in data.fields){
                                if(jQuerOs('#custom_fields_'+key).length > 0) continue;
                                
                                var text = '<div class="user_group_wrap" id="custom_fields_'+key+'">'
                                    + '<div class="user_groups">'+key+'</div>'
                                    + '<div class="group_setting">\n\
                                        <select name="custom_fields['+key+']" class="inputbox">'
                                    +'<option value="0"><?php echo cck_lang_text("COM_OS_CCK_OPTIONS_NOT_USE"); ?></option>'
                                    +'<option value="id"><?php echo cck_lang_text("COM_OS_CCK_OPTIONS_ID"); ?></option>'
                                    +'<option value="title"><?php echo cck_lang_text("COM_OS_CCK_OPTIONS_TITLE"); ?></option>'
                                    //+'<option value="child_id"><?php //echo cck_lang_text("COM_OS_CCK_OPTIONS_CHILD_ID"); ?></option>'
                                    +'<option value="date"><?php echo cck_lang_text("COM_OS_CCK_OPTIONS_DATE"); ?></option>'
                                    +'<option value="img"><?php echo cck_lang_text("COM_OS_CCK_OPTIONS_IMG"); ?></option>'
                                    +'<option value="number"><?php echo cck_lang_text("COM_OS_CCK_OPTIONS_NUMBER"); ?></option>'
                                    +'<option value="pricefield_number"><?php echo cck_lang_text("COM_OS_CCK_OPTIONS_PRICEFIELD"); ?></option>'
                                    +'<option value="text"><?php echo cck_lang_text("COM_OS_CCK_OPTIONS_TEXT"); ?></option>'
                                    +'<option value="textarea"><?php echo cck_lang_text("COM_OS_CCK_OPTIONS_TEXTAREA"); ?></option>'
                                    +'<option value="url"><?php echo cck_lang_text("COM_OS_CCK_OPTIONS_URL"); ?></option>'
                                    + '</select></div></div>'
                                    
                                    if(jQuerOs('.user_group_wrap').length > 0){
                                        jQuerOs('.user_group_wrap:last').after(text);
                                    }else{
                                        jQuerOs('.select_query_wrap').after(text);
                                    }
                            }
                            disableIdTitle()
                            disableTitleUser()
                        }else{
                            alert(data.errorMsg)
                        }
                        
                    },
                    error: function(data){
                        
                    }
                })
            }
            
            function make_editor(){
              
              jQuerOs(".editor-button, .save-editor-button").unbind('click');
              
            }
            jQuerOs(window).on('load', function(){
                jQuerOs(".editor-button").on('click',function(event) {
                      
                    jQuerOs(".joomla-editor").hide();
                    //jQuerOs("#editor-area").attr("style","");
                    jQuerOs(".CodeMirror").remove();
                    //tinyMCE.remove();
                    
                    jQuerOs('#editor-modal').css('z-index', '1500');
                    if(typeof bootstrap !== "undefined"){
                        var myModal = new bootstrap.Modal(document.getElementById("editor-modal"), {});
                        myModal.show()
                    }else{
                        jQuerOs('#editor-modal').modal();
                    }
                    
                    mode = 'php';
                    textValue = jQuerOs(this).parent().find("textarea").val();
//                    console.log('2222222222222222', textValue)
                    var editable_field = jQuerOs(this).parent().find("textarea");
                    

                      CodeMirror.commands.autocomplete = function(cm) {
                        cm.showHint({hint: CodeMirror.hint.anyword});
                      }

                      var editor = CodeMirror.fromTextArea(document.getElementById('editor-area'), {
                        lineNumbers: true,
                        mode: mode,
                        keyMap: "sublime",
                        autoCloseBrackets: true,
                        matchBrackets: true,
                        showCursorWhenSelecting: true,
                        theme: "monokai",
                        styleActiveLine: true,
                        tabSize: 2,
                        extraKeys: {
                          "F11": function(cm) {
                            cm.setOption("fullScreen", !cm.getOption("fullScreen"));
                          },
                          "Esc": function(cm) {
                            if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
                          },
                          "Ctrl-Space": "autocomplete"
                        }
                      });

                      editor.setValue(textValue);
                      setTimeout(function() {
                          editor.refresh();
                      },1000);
                      editor.on("change", function(cm, change) {
                        if(jQuerOs(".custom-code-editor:visible").val() != undefined){
                          jQuerOs(".custom-code-editor:visible").val(editor.getValue());
                        }else{
                            jQuerOs(editable_field).val(editor.getValue());
                        }
                      })
                      jQuerOs(".save-editor-button, [data-dismiss=modal]").on('click',function(event) {
                          if(typeof bootstrap !== "undefined"){
                              myModal.hide()
                          }else{
                            jQuerOs('#editor-modal').modal("hide");
                          }
                      });
                

              });
            })
            
            make_editor()
            
            function disableIdTitle(){
                var id = false;
                var title = false
                jQuerOs('[name^=custom_fields]').each(function(){
//                    console.log('333333333333333', jQuerOs(this).val())
                    if(jQuerOs(this).val() == 'id'){
                        id = true;
                    }
                    if(jQuerOs(this).val() == 'title'){
                        title = true;
                    }
                })
//                console.log('4444444444444', {id}, {title})
                if(id){
                    jQuerOs('[name^=custom_fields]').each(function(){
                        if(jQuerOs(this).val() != 'id'){
                            jQuerOs(this).find('[value=id]').attr('disabled', 'disabled')
                        }
                    })
//                    jQuerOs('[name^=custom_fields] [value=id]').attr('disabled', 'disabled')
                }else{
                    jQuerOs('[name^=custom_fields] [value=id]').removeAttr('disabled')
                }
                
                if(title){
                    jQuerOs('[name^=custom_fields]').each(function(){
                        if(jQuerOs(this).val() != 'title'){
                            jQuerOs(this).find('[value=title]').attr('disabled', 'disabled')
                        }
                    })
                }else{
                    jQuerOs('[name^=custom_fields] [value=title]').removeAttr('disabled')
                }
//                console.log('3333333333333', values)
            }
            
            function disableTitleUser(){
                var title = false
                jQuerOs('[name^=user_fields]').each(function(){

                    if(jQuerOs(this).val() == 'title'){
                        title = true;
                    }
                })
                
                if(title){
                    jQuerOs('[name^=user_fields]').each(function(){
                        if(jQuerOs(this).val() != 'title'){
                            jQuerOs(this).find('[value=title]').attr('disabled', 'disabled')
                        }
                    })
                }else{
                    jQuerOs('[name^=user_fields] [value=title]').removeAttr('disabled')
                }
            }
            
            jQuerOs(window).on('load', function(){
                disableIdTitle()
                disableTitleUser()
                jQuerOs('[name^=custom_fields]').on('change', function(){
                    disableIdTitle()
                    if(jQuerOs(this).val() == 'child_id'){
                        var name = jQuerOs(this).attr('name')
                        var replace_name = name.replace('custom_fields', 'child_id')
                        var clone_field = jQuerOs('form .child_id_setting:first').clone();
                        jQuerOs(clone_field).find('select').attr('name', replace_name)
                        jQuerOs(this).parents('.user_group_wrap').append(clone_field[0]);
                        jQuerOs(this).parents('.user_group_wrap').find('.child_id_setting').show()
                    }else{
//                        jQuerOs()
                        if(jQuerOs(this).parents('.user_group_wrap').find('.child_id_setting').length > 0){
                            var old_child_id = jQuerOs(this).parents('.user_group_wrap').find('[name=old_child_id]').val()
                            var input = '<input type="hidden" name="delete_child_ids[]" value="'+old_child_id+'"/>'
                            jQuerOs('form').append(input)
                            jQuerOs(this).parents('.user_group_wrap').find('.child_id_setting').remove();
                        }
                        
                    }
                })
                jQuerOs('[name^=user_fields]').on('change', function(){
                    disableTitleUser()
                })
            })
        </script>
        <?php
        $form_name = 'adminForm';
        $form_id = 'adminForm' ;
        $table = new os_cckViewTable($form_name, $form_id, 'add_entity_form wrapper_add_entity', 'index.php', '');

        $what_check = 'fields' ;
        $table->create_button('Save & Close', 'save_entity', '', 'fa-save','',$what_check);
        $table->create_button('Cancel', 'cancel_edit_entity', '', 'fa-close');
      
        $layout_html = '';
        ob_start();      
//        var_dump($row);
        ?>
<!--        <form action="index.php" method="post" name="adminForm" id="adminForm" class="add_entity_form wrapper_add_entity">-->
            <div class="cck-add-entity-block">
                <div>
                    <label style="display: block;"><?php echo cck_lang_text("COM_OS_CCK_ENTITIES_NAME"); ?>*</label>
                    <span class="cck-col-2">
                        <input class="text-input required" type="text" name="name" maxlength="250" value="<?php echo $row->name; ?>" <?php echo $disable; ?>/>
                    </span>
                </div>
            </div>
            <div>
            <div>
            <div class="entity-settings">
                <div>
                    <label style="display: block;"><?php echo cck_lang_text("COM_OS_CCK_ENTITIES_FILES_LABEL"); ?></label>
                    <span class="cck-col-2">
                        components/com_os_cck/files/entity_files_<?php echo $files_eid; ?> <i title="<?php echo cck_lang_text("COM_OS_CCK_ENTITIES_FILES_DESC")?>" class="glyphicon glyphicon-info-sign date_tooltip"></i> {|this_entity_filesfolder|}
                    </span>
                </div>
            </div>
            <div class="entity-settings">
                <div>
                    <label style="display: block;"><?php echo cck_lang_text("COM_OS_CCK_CCK_IMAGES_LABEL"); ?></label>
                    <span class="cck-col-2">
                        images/os-cck/ <i title="<?php echo cck_lang_text("COM_OS_CCK_CCK_IMAGES_LABEL_DESC")?>" class="glyphicon glyphicon-info-sign date_tooltip"></i> {|cck_images_folder|}
                    </span>
                </div>
            </div>
                
            </div>
            <?php if($entity_type == 'os_cck_entity'){ ?>
                <div class="entity-settings">
                <?php if( checkOsCckVersionProFree() == "pro" ){ ?>
                    <div>
                        <label><?php echo cck_lang_text("COM_OS_CCK_LABEL_ACCESS_CHECK_INSTASNCES"); ?></label>
                        <span class="cck-col-2">
                                <?php echo JHTML::_('select.genericlist',$access_option, 'check_access_instances',
                                    'size="1" class="inputbox" ', 'value', 'text', $check_access_instances_selected);?>
                        </span>
                    </div>
                    <div>
                        <label><?php echo cck_lang_text("COM_OS_CCK_LABEL_ACCESS_CHECK_FIELDS"); ?></label>
                        <span class="cck-col-2">
                                <?php echo JHTML::_('select.genericlist',$access_option, 'check_access_fields',
                                    'size="1" class="inputbox" ', 'value', 'text', $check_access_fields_selected);?>
                        </span>
                    </div>
                    <div>
                        <label><?php echo cck_lang_text("COM_OS_CCK_LABEL_ACCESS_CHECK_CATEGORIES"); ?></label>
                        <span class="cck-col-2">
                                <?php echo JHTML::_('select.genericlist',$access_option, 'check_access_categories',
                                    'size="1" class="inputbox" ', 'value', 'text', $check_access_categories_selected);?>
                        </span>
                    </div>
                <?php } ?>    
                    <div>
                        <label><?php echo cck_lang_text("COM_OS_CCK_LABEL_MAX_PRODUCT_DOWNLOADS"); ?> 
                            <i title="<?php echo cck_lang_text("COM_OS_CCK_LABEL_MAX_PRODUCT_DOWNLOADS_DESC")?>" class="glyphicon glyphicon-info-sign date_tooltip"></i>
                        </label>
                        <span class="cck-col-2">
                            <input type="number" class="inputbox" name="max_product_download" value="<?php echo $max_product_download; ?>">
                        </span>
                    </div>
                    <div>
                        <label><?php echo cck_lang_text("COM_OS_CCK_LABEL_DAYS_PRODUCT_DOWNLOADS"); ?> 
                            <i title="<?php echo cck_lang_text("COM_OS_CCK_LABEL_DAYS_PRODUCT_DOWNLOADS_DESC")?>" class="glyphicon glyphicon-info-sign date_tooltip"></i>
                        </label>
                        <span class="cck-col-2">
                            <input type="number" class="inputbox" name="days_for_product_download" value="<?php echo $days_for_product_download; ?>">
                        </span>
                    </div>
                    <div>
                        <label><?php echo cck_lang_text("COM_OS_CCK_LABEL_REDIRECT_MISSING_INSTANCE"); ?> 
                            <i title="<?php echo cck_lang_text("COM_OS_CCK_LABEL_REDIRECT_MISSING_INSTANCE_DESC")?>" class="glyphicon glyphicon-info-sign date_tooltip"></i>
                        </label>
                        <span class="cck-col-2">
                            <input type="text" class="inputbox" name="redirect_missing_instance" value="<?php echo $redirect_missing_instance; ?>">
                        </span>
                    </div>
                    <div>
                        <label><?php echo cck_lang_text("COM_OS_CCK_LABEL_REDIRECT_MISSING_CATEGORY"); ?> 
                            <i title="<?php echo cck_lang_text("COM_OS_CCK_LABEL_REDIRECT_MISSING_CATEGORY_DESC")?>" class="glyphicon glyphicon-info-sign date_tooltip"></i>
                        </label>
                        <span class="cck-col-2">
                            <input type="text" class="inputbox" name="redirect_missing_category" value="<?php echo $redirect_missing_category; ?>">
                        </span>
                    </div>
                    <div>
                        <label><?php echo cck_lang_text("COM_OS_CCK_LABEL_META_TITLE_SOURCE"); ?></label>
                        <span class="cck-col-2">
                                <?php echo JHTML::_('select.genericlist',$meta_title_option, 'meta_title_source',
                                    'size="1" class="inputbox" ', 'value', 'text', $meta_title_source_selected);?>
                        </span>
                    </div>
                    <div>
                        <label><?php echo cck_lang_text("COM_OS_CCK_LABEL_META_DESCRIPTION_SOURCE"); ?></label>
                        <span class="cck-col-2">
                                <?php echo JHTML::_('select.genericlist',$meta_description_option, 'meta_description_source',
                                    'size="1" class="inputbox" ', 'value', 'text', $meta_description_source_selected);?>
                        </span>
                    </div>
                    <div>
                        <label><?php echo cck_lang_text("COM_OS_CCK_LABEL_META_KEYWORDS_SOURCE"); ?></label>
                        <span class="cck-col-2">
                                <?php echo JHTML::_('select.genericlist',$meta_keywords_option, 'meta_keywords_source',
                                    'size="1" class="inputbox" ', 'value', 'text', $meta_keywords_source_selected);?>
                        </span>
                    </div>
                </div>
                <?php if( checkOsCckVersionProFree() == "pro" ){ ?> 
                    <div class="user_groups_settings">
                        <h3><?php echo cck_lang_text("COM_OS_CCK_LABEL_GROUPS_OPTIONS"); ?></h3>
                        <div class="user_group_wrap">
                            <div class="user_groups"><?php echo cck_lang_text("COM_OS_CCK_LABEL_GROUP"); ?></div>
                            <div class="group_setting"><?php echo cck_lang_text("COM_OS_CCK_LABEL_NUMBER_ITEMS"); ?> <i title="<?php echo cck_lang_text("COM_OS_CCK_LABEL_NUMBER_ITEMS_DESC")?>" class="glyphicon glyphicon-info-sign date_tooltip"></i></div>
                        </div>
                        <?php foreach ($gtree as $key => $group){ ?>
                            <div class="user_group_wrap">
                                <div class="user_groups"><?php echo $group; ?></div>
                                <div class="group_setting"><input type="number" name="max_items[<?php echo $key; ?>]" value="<?php echo (isset($cck_entity_configuration[$row->eid]['max_items'][$key])) ? $cck_entity_configuration[$row->eid]['max_items'][$key] : 10; ?>"></div>
                            </div>
                        <?php }?>
                    </div>
                <?php } ?> 
                
            <?php }elseif ($entity_type == 'joomla_user') { 
                $type_options = array();
                $type_options[] = JHTML::_('select.option','0',cck_lang_text("COM_OS_CCK_OPTIONS_NOT_USE"));
                $type_options[] = JHTML::_('select.option','title',cck_lang_text("COM_OS_CCK_OPTIONS_TITLE"));
                $type_options[] = JHTML::_('select.option','text',cck_lang_text("COM_OS_CCK_OPTIONS_TEXT"));
                $type_options[] = JHTML::_('select.option','textarea',cck_lang_text("COM_OS_CCK_OPTIONS_TEXTAREA"));
                $type_options[] = JHTML::_('select.option','img',cck_lang_text("COM_OS_CCK_OPTIONS_IMG"));
                $type_options[] = JHTML::_('select.option','date',cck_lang_text("COM_OS_CCK_OPTIONS_DATE"));
                $type_options[] = JHTML::_('select.option','number',cck_lang_text("COM_OS_CCK_OPTIONS_NUMBER"));
                $type_options[] = JHTML::_('select.option','url',cck_lang_text("COM_OS_CCK_OPTIONS_URL"));
                
                
                if($row->eid){
                    $custom_fields = unserialize($row->custom_fields);
                }
                
                $user_fields_standart_id = (isset($custom_fields['standart']['id'])) ? $custom_fields['standart']['id'] : '';
                $user_fields_standart_name = (isset($custom_fields['standart']['name'])) ? $custom_fields['standart']['name'] : '';
                $user_fields_standart_username = (isset($custom_fields['standart']['username'])) ? $custom_fields['standart']['username'] : '';
                $user_fields_standart_email = (isset($custom_fields['standart']['email'])) ? $custom_fields['standart']['email'] : '';
                $user_fields_standart_last_visit = (isset($custom_fields['standart']['last_visit'])) ? $custom_fields['standart']['last_visit'] : '';
                $user_fields_standart_register = (isset($custom_fields['standart']['register'])) ? $custom_fields['standart']['register'] : '';
                
                ?>
            <div class="profile_label">
                <h3><?php echo cck_lang_text("COM_OS_CCK_LABEL_STANDART_USER_FIELDS"); ?></h3>
                <div class="user_group_wrap">
                    <div class="user_groups"><?php echo cck_lang_text("COM_OS_CCK_LABEL_ID"); ?></div>
                    <div class="group_setting"><?php echo JHTML::_('select.genericlist',$type_options, 'user_fields[standart][id]',
                                    'size="1" class="inputbox" ', 'value', 'text', $user_fields_standart_id);?></div>
                </div>
                <div class="user_group_wrap">
                    <div class="user_groups"><?php echo cck_lang_text("COM_OS_CCK_LABEL_NAME"); ?></div>
                    <div class="group_setting"><?php echo JHTML::_('select.genericlist',$type_options, 'user_fields[standart][name]',
                                    'size="1" class="inputbox" ', 'value', 'text', $user_fields_standart_name);?></div>
                </div>
                <div class="user_group_wrap">
                    <div class="user_groups"><?php echo cck_lang_text("COM_OS_CCK_LABEL_USERNAME"); ?></div>
                    <div class="group_setting"><?php echo JHTML::_('select.genericlist',$type_options, 'user_fields[standart][username]',
                                    'size="1" class="inputbox" ', 'value', 'text', $user_fields_standart_username);?></div>
                </div>
                <div class="user_group_wrap">
                    <div class="user_groups"><?php echo cck_lang_text("COM_OS_CCK_LABEL_EMAIL"); ?></div>
                    <div class="group_setting"><?php echo JHTML::_('select.genericlist',$type_options, 'user_fields[standart][email]',
                                    'size="1" class="inputbox" ', 'value', 'text', $user_fields_standart_email);?></div>
                </div>
                <div class="user_group_wrap">
                    <div class="user_groups"><?php echo cck_lang_text("COM_OS_CCK_LABEL_LAST_VISIT"); ?></div>
                    <div class="group_setting"><?php echo JHTML::_('select.genericlist',$type_options, 'user_fields[standart][last_visit]',
                                    'size="1" class="inputbox" ', 'value', 'text', $user_fields_standart_last_visit);?></div>
                </div>
                <div class="user_group_wrap">
                    <div class="user_groups"><?php echo cck_lang_text("COM_OS_CCK_LABEL_REGISTER"); ?></div>
                    <div class="group_setting"><?php echo JHTML::_('select.genericlist',$type_options, 'user_fields[standart][register]',
                                    'size="1" class="inputbox" ', 'value', 'text', $user_fields_standart_register);?></div>
                </div>
                
                
                <?php 
                if(isset($fieldsets['profile'])){ 
                    ?>
                    <h3><?php echo cck_lang_text("COM_OS_CCK_LABEL_PROFILE_USER_FIELDS"); ?></h3>
                    <?php
                    $fields = $user_profile_form->getFieldset($fieldsets['profile']->name);
                    
                    foreach ($fields as $field){ 
                        $value = (isset($custom_fields['profile'][$field->fieldname])) ? $custom_fields['profile'][$field->fieldname] : '';
                        ?>
                        <div class="user_group_profile_wrap">
                            <div class="user_groups"><?php echo strip_tags($field->label); ?></div>
                            <div class="group_setting"><?php echo JHTML::_('select.genericlist',$type_options, 'user_fields[profile]['.$field->fieldname.']',
                                        'size="1" class="inputbox" ', 'value', 'text', $value);?></div>
                        </div>
                        
                    <?php }
                } ?>
                        
                <?php foreach($fieldsets as $fieldset){ 
                    if($fieldset->name == 'profile' || $fieldset->name == 'actionlogs' || $fieldset->name == 'core'){continue;}
                    ?>
                    <h3><?php echo cck_lang_text(strip_tags($fieldset->label)); ?></h3>
                    <?php
                    $fields = $user_profile_form->getFieldset($fieldset->name);
                    foreach ($fields as $field){ 
                        $value = (isset($custom_fields[$fieldset->name][$field->fieldname])) ? $custom_fields[$fieldset->name][$field->fieldname] : '';
                        ?>
                    <div class="user_group_profile_wrap">
                        <div class="user_groups"><?php echo strip_tags($field->label); ?></div>
                        <div class="group_setting"><?php echo JHTML::_('select.genericlist',$type_options, 'user_fields['.$fieldset->name.']['.$field->fieldname.']',
                                    'size="1" class="inputbox" ', 'value', 'text', $value);?></div>
                    </div>
                        
                    <?php }
                } ?>
            </div>      
            <?php }elseif ($entity_type == 'custom_sql') { 
                $type_options = array();
                $type_options[] = JHTML::_('select.option','0',cck_lang_text("COM_OS_CCK_OPTIONS_NOT_USE"));
                $type_options[] = JHTML::_('select.option','id',cck_lang_text("COM_OS_CCK_OPTIONS_ID"));
                $type_options[] = JHTML::_('select.option','title',cck_lang_text("COM_OS_CCK_OPTIONS_TITLE"));
//                $type_options[] = JHTML::_('select.option','child_id',cck_lang_text("COM_OS_CCK_OPTIONS_CHILD_ID"));
                $type_options[] = JHTML::_('select.option','date',cck_lang_text("COM_OS_CCK_OPTIONS_DATE"));
                $type_options[] = JHTML::_('select.option','img',cck_lang_text("COM_OS_CCK_OPTIONS_IMG"));
                $type_options[] = JHTML::_('select.option','number',cck_lang_text("COM_OS_CCK_OPTIONS_NUMBER"));
                $type_options[] = JHTML::_('select.option','pricefield_number',cck_lang_text("COM_OS_CCK_OPTIONS_PRICEFIELD"));
                $type_options[] = JHTML::_('select.option','text',cck_lang_text("COM_OS_CCK_OPTIONS_TEXT"));
                $type_options[] = JHTML::_('select.option','textarea',cck_lang_text("COM_OS_CCK_OPTIONS_TEXTAREA"));
                $type_options[] = JHTML::_('select.option','url',cck_lang_text("COM_OS_CCK_OPTIONS_URL"));
                
                
                $entity_options = array();
                foreach($entity_list as $ent){
                    $entity_options[] = JHTML::_('select.option',$ent->eid,$ent->name);
                }
                $custom_fields = array();
                if($row->eid && $row->custom_fields != ''){
                    $custom_fields = unserialize($row->custom_fields);
                }
                $custom_child_ids = array();
                if(isset($custom_fields['custom_child_ids'])){
                    $custom_child_ids = unserialize($custom_fields['custom_child_ids']);
//                    var_dump($custom_child_ids);
                }
                
                ?>
                <div class="child_id_setting" style="display:none;">
                    <?php echo JHTML::_('select.genericlist',$entity_options, '',
                        'size="1" class="inputbox" ', 'value', 'text', '');?>
                </div>
                <div class="select_query_wrap" style="width: 100%;">
                    <div style="width: 100%;">
                        <label><?php echo cck_lang_text("COM_OS_CCK_ENTITY_SETTINGS_LABEL_SQL_QUERY"); ?></label>
                        <span class="cck-col-2" style="display: block;width: 70%;">
                            
                            <textarea class="text-input" style="width: 70%;resize:auto;" name="sql_select" value="" <?php echo $disable; ?>><?php echo $row->sql_select; ?></textarea>
                        </span>
                    </div>
                    <div class="select_query_buttons_wrap">
                        <div>
                            <button class="btn btn-primary" type="button" onclick="checkQuery()" value=""><?php echo cck_lang_text("COM_OS_CCK_ENTITY_SETTINGS_LABEL_CHECK_QUERY"); ?></button>
                        </div>
                        <div>
                            <button class="btn btn-primary" type="button" onclick="loadFields()" value=""><?php echo cck_lang_text("COM_OS_CCK_ENTITY_SETTINGS_LABEL_LOAD_FIELDS"); ?></button>
                        </div>
                    </div>
                </div>
                <?php 
                if(property_exists($row, 'fields')){    
                foreach($row->fields as $field){ ?>
                    <div class="user_group_wrap" id="custom_fields_<?php echo $field; ?>">
                        <div class="user_groups"><?php echo cck_lang_text($field); ?></div>
                        <div class="group_setting"><?php echo JHTML::_('select.genericlist',$type_options, 'custom_fields['.$field.']',
                                        'size="1" class="inputbox" ', 'value', 'text', (isset($custom_fields[$field])) ? $custom_fields[$field] : '0');?></div>
                        <?php if(isset($custom_child_ids[$field])){ ?>
                            <div class="child_id_setting">
                                <?php echo JHTML::_('select.genericlist',$entity_options, 'child_id['.$field.']',
                                    'size="1" class="inputbox" ', 'value', 'text', $custom_child_ids[$field]);?>
                            </div>
                        <input type="hidden" name="old_child_id" value="<?php echo $custom_child_ids[$field]; ?>">
                        <?php } ?>
                    </div>
                    
                <?php }
                }
                require getLayoutPathCCK::getAdminLayoutViewPath('com_os_cck', 'modal_snippets', 'editor-modal');
             } ?>
            <input type="hidden" name="option" value="com_os_cck"/>
            <input type="hidden" name="task" value=""/>
            <input type="hidden" name="eid" value="<?php echo $row->eid; ?>"/>
            <input type="hidden" name="type" value="<?php echo $entity_type; ?>"/>
            <input type="hidden" name="delete_child_ids[]" value=""/>
<!--        </form>-->
        
    <?php
        $layout_html = ob_get_contents();
        ob_end_clean();
        $table->set_custom_html($layout_html);
        echo $table->viewTable();
    }
    
    static function addEntity($option, $type_list){
        $app = JFactory::getApplication();
        $html = "<div class='os_cck_caption' ><img src='./components/com_os_cck/images/os_cck_logo.png' alt ='Config' />" . cck_lang_text("COM_OS_CCK_ADMIN_ENTITIES") . "</div>";
        $app->JComponentTitle = $html;
        ?>
        <form action="index.php" method="post" name="adminForm" id="adminForm" enctype="multipart/form-data">
            <?php echo $type_list; ?>
            
            <input type="hidden" name="option" value="<?php echo $option; ?>"/>
            <input type="hidden" name="task" value="edit_entity"/>
        </form>
        <?php
    }
}
