<?php

class ForwardPresetPhoneKey extends PhonalisaRecord
{

    public $key;
    public $owner;
    public $forwardPreset;

    public static function myAttributes()
    {
        return array(
            'key' => 'key',
            'owner' => 'owner',
            'forwardPreset' => 'forwardPreset',
        );
    }

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Job the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @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('key', 'numerical', 'integerOnly' => true, 'min' => 0, 'max' => 9),
            array('forwardPreset, owner', 'required'),
            array('key, forwardPreset', 'safe'),
            array('key', 'uniqueKey', 'except' => array('createUser')),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
        );
    }

    public function uniqueKey($attribute, $params)
    {
        $keys = array();

        foreach ($_POST['ForwardPreset']['key'] as $id => $value) {
            if ($this->forwardPreset != $id && $value != '') {
                $keys[] = $value;
            }
        }

        if (in_array($this->$attribute, $keys)) {
            $this->addError(
                $attribute,
                __('FORWARD_PRESET_FEATURE_KEY_ISNOT_UNIQUE') . $this->$attribute,
                $this->$attribute
            );
        }
    }

    public static function modelForPresetId($presetId)
    {
        $model = ForwardPresetPhoneKey::model()->findByAttributes(array(
            'owner' => app()->user->sudoUserInstance,
            'preset' => $presetId
        ));

        if ($model != null) {
            return $model;
        }

        return null;
    }

    public function beforeSave()
    {
        if ($this->scenario != 'createUser') {
            $this->owner = app()->user->sudoUserInstance->id;
        }
        return parent::beforeSave();
    }
}
