<?php

/**
 * This is the model class for table "clientes_dispositivos_moveis".
 *
 * The followings are the available columns in table 'clientes_dispositivos_moveis':
 * @property integer $CDM_IDDISPOSITIVOSMOVEIS
 * @property string $CDM_DESCRICAO
 * @property string $CDM_MAC
 * @property string $CDM_DTLOGIN
 * @property integer $CDM_STATUS
 * @property integer $CDM_IDCLIENTE
 *
 * The followings are the available model relations:
 * @property Clientes $cDMIDCLIENTE
 */
class ClientesDispositivosMoveis extends GxActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'clientes_dispositivos_moveis';
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return ClientesDispositivosMoveis the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public static function label($n = 1) {
        return Yii::t('app', 'Dispositivo Móvel|Dispositivos Móveis', $n);
    }

    public static function representingColumn() {
        return 'CDM_MAC';
    }

    public function behaviors() {
        return array('datetimeI18NBehavior' => array('class' => 'ext.DateTimeI18NBehavior'));
    }

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('CDM_DESCRICAO, CDM_MAC', 'required'),
			array('CDM_STATUS, CDM_IDCLIENTE', 'numerical', 'integerOnly'=>true),
			array('CDM_DESCRICAO', 'length', 'max'=>200),
			array('CDM_MAC', 'length', 'max'=>17),
			array('CDM_MAC', 'validateMac'),
			array('CDM_DTLOGIN', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('CDM_IDDISPOSITIVOSMOVEIS, CDM_DESCRICAO, CDM_MAC, CDM_DTLOGIN, CDM_STATUS, CDM_IDCLIENTE', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		return array(
			'Cliente' => array(self::BELONGS_TO, 'Clientes', 'CDM_IDCLIENTE'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'CDM_IDDISPOSITIVOSMOVEIS' => 'ID',
			'CDM_DESCRICAO' => 'Nome',
			'CDM_MAC' => 'MAC',
			'CDM_DTLOGIN' => 'Último Login',
			'CDM_STATUS' => 'Status',
			'CDM_IDCLIENTE' => 'Cliente',
		);
	}

	public function validateMac($attribute, $params)
  	{
    	if(filter_var($this->{$attribute}, FILTER_VALIDATE_MAC) === false) {
      		$this->addError($attribute, 'O endereço MAC informado é inválido');
      		return false;
    	}
  	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('CDM_IDDISPOSITIVOSMOVEIS',$this->CDM_IDDISPOSITIVOSMOVEIS);
		$criteria->compare('CDM_DESCRICAO',$this->CDM_DESCRICAO,true);
		$criteria->compare('CDM_MAC',$this->CDM_MAC,true);
		$criteria->compare('CDM_DTLOGIN',$this->CDM_DTLOGIN,true);
		$criteria->compare('CDM_STATUS',$this->CDM_STATUS);
		$criteria->compare('CDM_IDCLIENTE',$this->CDM_IDCLIENTE);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	public function beforeSave()
    {
    	parent::beforeSave();
        $this->CDM_MAC = preg_replace('/[\W]/', '', $this->CDM_MAC);
        $this->CDM_MAC = strtolower($this->CDM_MAC);
        return true;
    }

	public function afterSave()
    {
    	parent::afterSave();
        $this->updateLicencasUsadas();
    }

    public function afterDelete()
    {
    	parent::afterDelete();
        $this->updateLicencasUsadas();
    }

    private function updateLicencasUsadas()
    {
    	$cliente = Clientes::model()->findByPk($this->CDM_IDCLIENTE);
    	$cliente->CLI_LICENCAS_USO_MOBILE = $this->countActive($this->CDM_IDCLIENTE);
        $cliente->save(false,  array('CLI_LICENCAS_USO_MOBILE'));
    }

    public function countActive($cliente, $not = false)
    {
    	$criteria=new CDbCriteria;
        $criteria->compare('CDM_IDCLIENTE', $cliente);
        $criteria->compare('CDM_STATUS', 1);

        if($not) {
            $criteria->compare('CDM_IDDISPOSITIVOSMOVEIS', '<>'.$not);
        }
        return ClientesDispositivosMoveis::model()->count($criteria);
    }
}
