<?php

class attr_userlist extends attr {

    public $linked_obj;
    public $sql_where;
    public $lobj_name;

    public function __construct($attr_name, $obj) {
        $this->attr_name = $attr_name;
        $this->obj       = $obj;
        $full_type       = $obj->attrs[$attr_name]['type'];
        $this->lobj_name = '_sys_users';
    }

    public function getDBType() {
        return "varchar(255)";
    }

    public function getLinkedObj() {
        if (!$this->linked_obj) {
            $this->linked_obj = new cobject($this->lobj_name, $this->obj->recursion_depth);
        }
        return $this->linked_obj;
    }

    public function lPost() {
        if (is_array($_POST[$this->attr_name])) {
            $this->obj->set($this->attr_name, implode(",", $_POST[$this->attr_name]));
        } else {
            $this->obj->set($this->attr_name, $_POST[$this->attr_name]);
        }
    }


    public function render_text($crop) {
        $id = $this->getCurVal();
        if ($id) {
            $ids = explode(",", $id);
        }
        $outa = [];
        if ($ids) {
            foreach($ids as $id) {
                $this->getLinkedObj()->byId($id); // Показывать удаленные
                $outa[] = $this->getLinkedObj()->assign('{name}');
            }
            if ($outa) {
                sort($outa);
            }
        }
        return implode("; ", $outa);
    }


    public function render_input() {
        global $core;

        $db = $this->getLinkedObj()->getDB();

        $addsql = $this->obj->attrs[$this->attr_name]['templ'];

        $db2 = $db->q($this->getLinkedObj()->getSelect($this->sql_where . $addsql . ' ORDER BY `name`'));
        $out = '';
        $id  = $this->getCurVal();
        if ($id) {
            $ids = explode(",", $id);
        }
        while ($db2->r()) {
            $this->getLinkedObj()->lRow($db2);
            $tt = $this->getLinkedObj()->assign(' {name}');
            if ($ids && in_array($db2->f('id'), $ids)) {
                $checked = 'checked';
            } else {
                $checked = '';
            }
            $out .= '<label><input type="checkbox" name="'.$this->attr_name.'[]" class="checkbox" ' . $checked . ' value="'.$db2->f('id').'">' . $tt . '</label><br>';
        }
        return $out;
    }


}

?>