<?php

App::uses('AppModel', 'Model');
App::uses('AuthComponent', 'Controller/Component');

/**
 * User
 *
 * PHP version 5
 *
 * @category Model
 * @package  Bemmelhor
 * @version  1.0
 * @author   Fabricio S Costa <fabriciojf@gmail.com>
 *
 * @link     http://www.bemmelhor.org
 */
class User extends AppModel {

    public $displayField = 'name';

    /**
     * Model name
     *
     * @var string
     * @access public
     */
    public $name = 'User';

    /**
     * Order
     *
     * @var string
     * @access public
     */
    public $order = 'name ASC';

    /**
     * Behaviors used by the Model
     *
     * @var array
     * @access public
     */
    public $actsAs = array(
        'Acl' => array(
            'className' => 'BemmelhorAcl',
            'type' => 'requester',
        ),
    );

    /**
     * Model associations: belongsTo
     *
     * @var array
     * @access public
     */
    public $belongsTo = array('Role');

    /**
     * Validation
     *
     * @var array
     * @access public
     */
    public $validate = array(
        'username' => array(
            'isUnique' => array(
                'rule' => 'isUnique',
                'message' => 'The username has already been taken.',
                'last' => true,
            ),
            'notEmpty' => array(
                'rule' => 'notEmpty',
                'message' => 'This field cannot be left blank.',
                'last' => true,
            ),
            'validAlias' => array(
                'rule' => 'validAlias',
                'message' => 'This field must be alphanumeric',
                'last' => true,
            ),
        ),
        'email' => array(
            'email' => array(
                'rule' => 'email',
                'message' => 'Please provide a valid email address.',
                'last' => true,
            ),
            'isUnique' => array(
                'rule' => 'isUnique',
                'message' => 'Email address already in use.',
                'last' => true,
            ),
        ),
        'password' => array(
            'rule' => array('minLength', 6),
            'message' => 'Passwords must be at least 6 characters long.',
        ),
        'verify_password' => array(
            'rule' => 'validIdentical',
        ),
        'name' => array(
            'notEmpty' => array(
                'rule' => 'notEmpty',
                'message' => 'This field cannot be left blank.',
                'last' => true,
            ),
        ),
        'website' => array(
            'url' => array(
                'rule' => 'url',
                'message' => 'This field must be a valid URL',
                'allowEmpty' => true,
            ),
        ),
    );

    /**
     * Display fields for this model
     *
     * @var array
     */
    protected $_displayFields = array(
        'id',
        'Role.title' => 'Role',
        'username',
        'status' => array('type' => 'boolean'),
        'email',
        'locale',
        'image',
    );

    /**
     * Edit fields for this model
     *
     * @var array
     */
    protected $_editFields = array(
        'role_id',
        'username',
        'name',
        'email',
        'website',
        'locale',
        'status',
        'image',
        'twitter',
        'facebook',
        'linkedin',
        'youtube',
        'gplus',
        'description',
    );

    /**
     * beforeDelete
     *
     * @param boolean $cascade
     * @return boolean
     */
    public function beforeDelete($cascade = true) {
        $this->Role->Behaviors->attach('Aliasable');
        $adminRoleId = $this->Role->byAlias('admin');

        $current = AuthComponent::user();
        if (!empty($current['id']) && $current['id'] == $this->id) {
            return false;
        }
        if ($this->field('role_id') == $adminRoleId) {
            $count = $this->find('count', array(
                'conditions' => array(
                    'User.id <>' => $this->id,
                    'User.role_id' => $adminRoleId,
                    'User.status' => true,
                )
            ));
            return ($count > 0);
        }
        return true;
    }

    /**
     * beforeSave
     *
     * @param array $options
     * @return boolean
     */
    public function beforeSave($options = array()) {
        if (!empty($this->data['User']['password'])) {
            $this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
        }
        return true;
    }

    /**
     * _identical
     *
     * @param string $check
     * @return boolean
     * @deprecated Protected validation methods are no longer supported
     */
    protected function _identical($check) {
        return $this->validIdentical($check);
    }

    /**
     * validIdentical
     *
     * @param string $check
     * @return boolean
     */
    public function validIdentical($check) {
        if (isset($this->data['User']['password'])) {
            if ($this->data['User']['password'] != $check['verify_password']) {
                return __('Passwords do not match. Please, try again.');
            }
        }
        return true;
    }

    /**
     * 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['User']['id']}', 'text': '{$current_item['User']['name']}'},";
            $where = array(
                'id !=' => $current_item['User']['id']
            );
        }

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

    /**
     * Retorna o profile do usuario corrente
     */
    public function my_profile($myid) {
        $myprofile = $this->read(array(
            'User.id',
            'User.name',
            'User.email',
            'User.gravatar',
                ), $myid);

        if (($myprofile['User']['gravatar'] == '') ||
                ($myprofile['User']['gravatar'] == null)) {
            $myprofile['User']['gravatar'] = 'profile.png';
        }

        return $myprofile;
    }

}
