<?php

App::uses('AppModel', 'Model');

/**
 * WikiGroup Model
 */
class WikiGroup extends AppModel {

    /**
     * Campos usado nos combos como campo label
     */
    public $displayField = 'name';

     /**
     * belongsTo associations
     *
     * @var array
     */
    public $hasMany = array(
        'Wiki' => array(
            'className' => 'Wiki',
            'foreignKey' => 'wiki_group_id',
            'fields' => array(
                'id',
                'title',
                'slug'
            ),
            'limit' => 5
        )
    );

    /**
     * Retorna um json de itens para popular um combo
     */
    public function list_all($current_item_id = null) {
        $jsonItems = '';
        $where = array();

        if ($current_item_id != null) {
            $current_item = $this->read(array(
                'id',
                'name'
            ), $current_item_id);

            $jsonItems .= "{id: '{$current_item['WikiGroup']['id']}', 'text': '{$current_item['WikiGroup']['name']}'},";
            $where = array(
                'id !=' => $current_item['WikiGroup']['id']
            );
        }

        $items = $this->find('all', array(
            'fields' => array(
                'id',
                'name'
            ),
            'order' => array(
                'default_selected DESC',
                'name'
            ),
            'recursive' => -1,
            'conditions' => $where
        ));
        foreach ($items as $item) {
            $jsonItems .= "{id: '{$item['WikiGroup']['id']}', 'text': '{$item['WikiGroup']['name']}'},";
        }
        return "[{$jsonItems}]";
    }
}