<?php
    
class attr_tags extends attr  {

  	var $linked_obj;
	var $sql_where;
    var $lobj_name;
    var $hashCode = 'tags';

    var $presaveData = [];
    var $beenLPost = false;


    function __construct( $attr_name, $obj ) {
           $this->attr_name = $attr_name;
           $this->obj = $obj;
           $full_type = $obj->attrs[$attr_name]['type'];
           $this->lobj_name = 'global_tags';
           $this->lattr_name = 'entity_id';
           $this->linked_obj = new cobject($this->lobj_name);
           $this->hashCode = md5($this->lobj_name . $this->attr_name . $this->obj->id);
    }

    function getDBType() {
    	return "int(1)";
    }

    function lPost() {
        $this->beenLPost = true;
        $data = $_POST[$this->hashCode];
        $curattrs = [];
        // Заполняем данные из POST
        if (is_array($data) && !empty($data) ) {
            $sql = "SELECT id, title, tag_group_id FROM  `global_tags_titles` 
                    WHERE id in (".implode(",", $data).")
                    ";
            $db2 = $this->linked_obj->getDB()->q($sql); 

            while( $db2->nr() ) {
                $curattrs[$db2->f('tag_group_id')][] = array('id' => $db2->f('id'), 'title' => $db2->f('title'));
            }
        }
        $this->presaveData = $curattrs;
        $this->obj->diffed[] = $this->attr_name;
    }  

    
    function render_text( $crop = false ) {

        $data = $this->getCurVal();
        $html = '';
    	foreach($data as $group_id => $vals) {
            foreach( $vals as $val ) {
                $html .='<span class="badge badge-info mx-1">'.$val['title'].'</span>';
            }
        }
        return $html;
    }

    function getCurVal() {

        // Если была подгрузка из POST, то берём оттуда
        if ($this->beenLPost) {
            return $this->presaveData;
        }

        
        // Иначе из базы
        $curattrs = [];
        $sql = "SELECT global_tags_titles.id, global_tags_titles.title, `".$this->lobj_name."`.tag_group_id FROM  `".$this->lobj_name."` 
                    LEFT JOIN `global_tags_titles` ON (`global_tags_titles`.`id` = `".$this->lobj_name."`.`tag_id`)
                     WHERE  `".$this->lattr_name."` = '".$this->obj->id."' ";        
        $db2 = $this->linked_obj->getDB()->q( $sql );

        while( $db2->nr() ) {
            $curattrs[$db2->f('tag_group_id')][] = array('id' => $db2->f('id'), 'title' => $db2->f('title'));
        }
       

        return $curattrs;
    }

    function render_input() {
        $obj_id = $this->linked_obj->id;

        $groupObj = new cobject('global_tags_groups');
        $titleObj = new cobject('global_tags_titles');
        $out = '<table id="table'.$this->hashCode.'" class="table table-sm bg-white" style="table-layout: fixed; width: 100%;">
                <thead>
                    <tr><th style=" width: 200px;">Характеристика</th><th>Значение</th></tr>
                </thead>
                <tbody>
        ';

        $groupList = $groupObj->getList(' ORDER BY `title` ');

        // Получаем текущие значения из базы или POST
        $curattrs = $this->getCurVal();

        $addList = [];
        foreach ($groupList as $group_id => $group_title) {
            if (isset($curattrs[$group_id])) {
                $out .= '<tr><td class="align-middle">' . $group_title . "</td><td>
                    <select name='".$this->hashCode."[]' id='filter_".$this->hashCode."_".$group_id."' data-addLink='tags_loader.php?add=1&group_id=".$group_id."&str=' multiple style='width: 100%;'> ";
                foreach( $curattrs[$group_id] as $vals ) {
                        $out .= '<option selected value="'.$vals['id'].'">'.$vals['title'].'</option>';   
                }
                $out .= "</select></td></tr>
                    <script>
                        $(document).ready( function() {
                                addSelector_".$this->hashCode."('filter_".$this->hashCode."_".$group_id."', '".$group_id."');
                        });
                    </script>";

            } else {
                $addList[] = '<option value="'.$group_id.'">'.$group_title.'</option>';
            }
        }

        $out .= '</tbody>
                <tfoot>
                <tr><td>
                        <select id="addfilter_'.$this->hashCode.'" style="width:100%">';
        $out .= implode(" ", $addList);
        $out .=         '</select>
                    </td><td>
                        <a href="javascript:addLine_'.$this->hashCode.'(\'addfilter_'.$this->hashCode.'\');" class="btn btn-primary">Добавить</a>
                    </td></tr>
                </tfoot>
                </table>
                <input type="hidden" name="'.$this->attr_name.'" value="1">
                ';

    
  
        
        $out .= "<script>
                $(document).ready( function() { 
                        $('#addfilter_".$this->hashCode."').chosen();
                }); 

                function addSelector_".$this->hashCode."(selector, id ) {

                    $.getJSON('tags_loader.php?preload=1&group_id=' + id, function(data) {
                            var currentOptions = $('#' + selector + ' option').map(function() { return parseInt(this.value) }).get();
                            for(i in data ) {
                                if ($.inArray(parseInt(data[i].value), currentOptions) === -1 ) {
                                    console.log('addme');   
                                    $('#' + selector).append('<option value=\"' + data[i].value + '\">'+data[i].text+'</option>');        
                                }
                            }
                            $('#' + selector).trigger('liszt:updated');
                    } );
                    
                    $('#' + selector).ajaxChosen({
                            type: 'GET', url: 'tags_loader.php?group_id=' + id, 
                            dataType: 'json', 
                            minTermLength: 1
                        }, 
                        function (data) {
                            var results = []; 
                            $.each(data, function (i, val) {
                                results.push({ value: val.value, text: val.text });
                            });
                        return results;
                        }
                    );
                }
            
                function addLine_".$this->hashCode."(selector) {
                    var attr_id = $('#' + selector).val();
                    var text = $('#' +selector + ' option:selected').text();
                    $('#table".$this->hashCode." tbody').append('<tr><td class=\'align-middle\'>'+text+'</td><td><select name=\"".$this->hashCode."[]\" id=\"filter_".$this->hashCode."_'+attr_id+'\" data-addLink=\"tags_loader.php?add=1&group_id='+attr_id+'&str=\" multiple style=\"min-width: 100%;\"></select></td></tr>');
                    addSelector_".$this->hashCode."('filter_".$this->hashCode."_' + attr_id, attr_id );
                    $('#' +selector + ' option:selected').remove();
                    $('#' + selector).trigger('liszt:updated');
                }
              
          </script> ";

        return $out;
    }

    // Сохраняем после сохранения основного объекта
    function postsave() {
        
        if (!$this->obj->id ) return false;

        // Очищаем старые значения
        $this->linked_obj->getDB()->q('DELETE FROM `'.$this->lobj_name.'` WHERE `'.$this->lattr_name.'` = "'.$this->obj->id.'"');
        foreach($this->presaveData as $group_id => $vals) {
            foreach( $vals as $val ) {
                $this->linked_obj->byId(0);
                $this->linked_obj->set($this->lattr_name, $this->obj->id);
                $this->linked_obj->set('tag_id', $val['id']);
                $this->linked_obj->set('tag_group_id', $group_id);
                $this->linked_obj->save();
            }
        }
    }

}

?>