<?php

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

/**
 * Link Model
 */
class Link extends AppModel {

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

    /**
     * Validation rules
     *
     * @var array
     */
    public $validate = array(
        'status' => array(
            'boolean' => array(
                'rule' => array('boolean'),
                'message' => 'Your custom message here',
                'allowEmpty' => false,
                'required' => false,
                'last' => false, // Stop validation after this rule
                'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
    );

    /**
     * belongsTo associations
     *
     * @var array
     */
    public $belongsTo = array(
        'ParentLink' => array(
            'className' => 'Link',
            'foreignKey' => 'parent_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'Menu' => array(
            'className' => 'Menu',
            'foreignKey' => 'menu_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );

    /**
     * hasMany associations
     *
     * @var array
     */
    public $hasMany = array(
        'ChildLink' => array(
            'className' => 'Link',
            'foreignKey' => 'parent_id',
            'dependent' => false,
        )
    );

    /**
     * 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',
                'title'
                    ), $current_item_id);

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

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

}
