<?php

class KeyType
{

    const noneSelected = 0;
    const hangUp = 1;
    const targetNumber = 2;
    const voiceMail = 3;
    const retryAnnounce = 4;

}

class IVR extends PhonalisaRecord
{

    public $id;
    public $extension;
    public $title;
    public $description;
    public $announce_file;
    public $answer_time;
    public $answer_retry;
    
    public $key_0_action;   //BehaviorType
    public $key_0_targetType;  //ExtensionType
    public $key_0_targetExtension; //Target Extension
    
    public $key_0_target;   //Target ID
    public $key_0_meta;    //for meta
    
    public $key_1_action;
    public $key_1_targetExtension;
    public $key_1_targetType;
    public $key_1_target;
    public $key_1_meta;
    
    public $key_2_action;
    public $key_2_targetExtension;
    public $key_2_targetType;
    public $key_2_target;
    public $key_2_meta;
    
    public $key_3_action;
    public $key_3_targetExtension;
    public $key_3_targetType;
    public $key_3_target;
    public $key_3_meta;
    
    public $key_4_action;
    public $key_4_targetExtension;
    public $key_4_targetType;
    public $key_4_target;
    public $key_4_meta;
    
    public $key_5_action;
    public $key_5_targetExtension;
    public $key_5_targetType;
    public $key_5_target;
    public $key_5_meta;
    
    public $key_6_action;
    public $key_6_targetExtension;
    public $key_6_targetType;
    public $key_6_target;
    public $key_6_meta;
    
    public $key_7_action;
    public $key_7_targetExtension;
    public $key_7_targetType;
    public $key_7_target;
    public $key_7_meta;
    
    public $key_8_action;
    public $key_8_targetExtension;
    public $key_8_targetType;
    public $key_8_target;
    public $key_8_meta;
    
    public $key_9_action;
    public $key_9_targetExtension;
    public $key_9_targetType;
    public $key_9_target;
    public $key_9_meta;
    
    public $key_asterisk_action;
    public $key_asterisk_targetExtension;
    public $key_asterisk_targetType;
    public $key_asterisk_target;
    public $key_asterisk_meta;
    
    public $key_pound_action;
    public $key_pound_targetExtension;
    public $key_pound_targetType;
    public $key_pound_target;
    public $key_pound_meta;
    
    public $key_invalid_action;
    public $key_invalid_targetExtension;
    public $key_invalid_targetType;
    public $key_invalid_target;
    public $key_invalid_meta;
    
    public $key_noInput_action;
    public $key_noInput_targetExtension;
    public $key_noInput_targetType;
    public $key_noInput_target;
    public $key_noInput_meta;
    
    public $scriptExtension;

    public static function myAttributes()
    {

        return array(
            'title' => 'title',
            'extension' => 'extension',
            'description' => 'description',
            'announce_file' => 'announce_file',
            'answer_time' => 'answer_time',
            'answer_retry' => 'answer_retry',
            'key_0_action' => 'key_0_action',
            'key_1_action' => 'key_1_action',
            'key_2_action' => 'key_2_action',
            'key_3_action' => 'key_3_action',
            'key_4_action' => 'key_4_action',
            'key_5_action' => 'key_5_action',
            'key_6_action' => 'key_6_action',
            'key_7_action' => 'key_7_action',
            'key_8_action' => 'key_8_action',
            'key_9_action' => 'key_9_action',
            'key_asterisk_action' => 'key_asterisk_action',
            'key_pound_action' => 'key_pound_action',
            'key_invalid_action' => 'key_invalid_action',
            'key_noInput_action' => 'key_noInput_action',
            'key_0_targetExtension' => 'key_0_targetExtension',
            'key_1_targetExtension' => 'key_1_targetExtension',
            'key_2_targetExtension' => 'key_2_targetExtension',
            'key_3_targetExtension' => 'key_3_targetExtension',
            'key_4_targetExtension' => 'key_4_targetExtension',
            'key_5_targetExtension' => 'key_5_targetExtension',
            'key_6_targetExtension' => 'key_6_targetExtension',
            'key_7_targetExtension' => 'key_7_targetExtension',
            'key_8_targetExtension' => 'key_8_targetExtension',
            'key_9_targetExtension' => 'key_9_targetExtension',
            'key_asterisk_targetExtension' => 'key_asterisk_targetExtension',
            'key_pound_targetExtension' => 'key_pound_targetExtension',
            'key_invalid_targetExtension' => 'key_invalid_targetExtension',
            'key_noInput_targetExtension' => 'key_noInput_targetExtension',
            'key_0_targetType' => 'key_0_targetType',
            'key_1_targetType' => 'key_1_targetType',
            'key_2_targetType' => 'key_2_targetType',
            'key_3_targetType' => 'key_3_targetType',
            'key_4_targetType' => 'key_4_targetType',
            'key_5_targetType' => 'key_5_targetType',
            'key_6_targetType' => 'key_6_targetType',
            'key_7_targetType' => 'key_7_targetType',
            'key_8_targetType' => 'key_8_targetType',
            'key_9_targetType' => 'key_9_targetType',
            'key_asterisk_targetType' => 'key_asterisk_targetType',
            'key_pound_targetType' => 'key_pound_targetType',
            'key_invalid_targetType' => 'key_invalid_targetType',
            'key_noInput_targetType' => 'key_noInput_targetType',
            'key_0_target' => 'key_0_target',
            'key_1_target' => 'key_1_target',
            'key_2_target' => 'key_2_target',
            'key_3_target' => 'key_3_target',
            'key_4_target' => 'key_4_target',
            'key_5_target' => 'key_5_target',
            'key_6_target' => 'key_6_target',
            'key_7_target' => 'key_7_target',
            'key_8_target' => 'key_8_target',
            'key_9_target' => 'key_9_target',
            'key_asterisk_target' => 'key_asterisk_target',
            'key_pound_target' => 'key_pound_target',
            'key_invalid_target' => 'key_invalid_target',
            'key_noInput_target' => 'key_noInput_target',
            'key_0_meta' => 'key_0_meta',
            'key_1_meta' => 'key_1_meta',
            'key_2_meta' => 'key_2_meta',
            'key_3_meta' => 'key_3_meta',
            'key_4_meta' => 'key_4_meta',
            'key_5_meta' => 'key_5_meta',
            'key_6_meta' => 'key_6_meta',
            'key_7_meta' => 'key_7_meta',
            'key_8_meta' => 'key_8_meta',
            'key_9_meta' => 'key_9_meta',
            'key_asterisk_meta' => 'key_asterisk_meta',
            'key_pound_meta' => 'key_pound_meta',
            'key_invalid_meta' => 'key_invalid_meta',
            'key_noInput_meta' => 'key_noInput_meta',
            'scriptExtension' => 'scriptExtension'
        );
    }

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

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'ivr';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {

        $keyTargetAttributes = '';

        foreach ($this->getAvailableKeys() as $key) {
            $keyTargetAttributes .= 'key_' . $key . '_target, ';
        }
        $keyMetaAttributes = str_replace('target', 'meta', $keyTargetAttributes);


        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            //TEST
            array($keyTargetAttributes, 'requiredOnTargetReqiredAction'),
            array($keyMetaAttributes, 'requiredOnTargetReqiredAction'),
            //TEST end
            array('title, extension, announce_file', 'required'),
            array('extension, answer_time, answer_retry', 'numerical', 'integerOnly' => true),
            array('extension', 'length', 'min' => 2, 'max' => 10),
            array('extension', 'ext.PhonalisaValidators.uniqueExtension'),
            array(
                'extension',
                'match',
                'pattern' => '/^[1-9]/',
                'message' => __('USER_MODEL_SHOULD_NOT_START_WITH_ZERO_ERROR_MESSAGE')
            ),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array(
                'title, extension, description, announce_file, answer_time, answer_retry, key_0_action, key_1_action,
                key_2_action, key_3_action, key_4_action, key_5_action, key_6_action, key_7_action, key_8_action,
                key_9_action, key_asterisk_action, key_pound_action, key_0_targetExtension, key_1_targetExtension,
                key_2_targetExtension, key_3_targetExtension, key_4_targetExtension, key_5_targetExtension,
                key_6_targetExtension, key_7_targetExtension, key_8_targetExtension, key_9_targetExtension,
                key_asterisk_targetExtension, key_pound_targetExtension, key_0_targetType, key_1_targetType,
                key_2_targetType, key_3_targetType, key_4_targetType, key_5_targetType, key_6_targetType,
                key_7_targetType, key_8_targetType, key_9_targetType, key_asterisk_targetType, key_pound_targetType,
                key_0_target, key_1_target, key_2_target, key_3_target, key_4_target, key_5_target, key_6_target,
                key_7_target, key_8_target, key_9_target, key_asterisk_target, key_pound_target,key_0_meta',
                'safe', 'on' => 'search'
            ),
            array(
                'description, announce_file, key_0_action, key_1_action, key_2_action, key_3_action, key_4_action,
                key_5_action, key_6_action, key_7_action, key_8_action, key_9_action, key_asterisk_action,
                key_pound_action, key_0_targetExtension, key_1_targetExtension, key_2_targetExtension,
                key_3_targetExtension, key_4_targetExtension, key_5_targetExtension, key_6_targetExtension,
                key_7_targetExtension, key_8_targetExtension, key_9_targetExtension, key_asterisk_targetExtension,
                key_pound_targetExtension, key_0_targetType, key_1_targetType, key_2_targetType, key_3_targetType,
		key_4_targetType, key_5_targetType, key_6_targetType, key_7_targetType, key_8_targetType,
                key_9_targetType, key_asterisk_targetType, key_pound_targetType, key_0_target, key_1_target,
                key_2_target, key_3_target, key_4_target, key_5_target, key_6_target, key_7_target, key_8_target,
                key_9_target, key_asterisk_target, key_pound_target, key_0_meta, key_1_meta, key_2_meta, key_3_meta,
                key_4_meta, key_5_meta, key_6_meta, key_7_meta, key_8_meta, key_9_meta, key_asterisk_meta,
                key_pound_meta, scriptExtension', 'safe'
            ),
            array('title', 'length', 'max' => 50),
        );
    }

    public function requiredOnTargetReqiredAction($attribute, $param)
    {
        $keyIndex = str_replace(array('key_', '_target'), array('', ''), $attribute);
        $keyIndex = str_replace(array('key_', '_meta'), array('', ''), $keyIndex);
        $attr = str_replace(array('key_', $keyIndex . "_"), array('', ''), $attribute);
        $key_action = 'key_' . $keyIndex . '_action';
        $value = $this->$attribute;

        if ((int) $this->$key_action == KeyType::noneSelected) {
            return true;
        }

        if ($value && $value != '---') {
            return true;
        } else {

            if ($attr == 'target') {
                if ($this->$key_action == KeyType::targetNumber || $this->$key_action == KeyType::voiceMail) {
                    $this->addError($attribute, $this->getAttributeLabel($key_action) . ' ' . __('IVR_KEY_' . strtoupper($attr) . '_NOT_DEFINED_ERROR'));
                    return false;
                } else {
                    return true;
                }
            } else if ($attr != 'meta') {
                $this->addError($attribute, $this->getAttributeLabel($key_action) . ' ' . __('IVR_KEY_' . strtoupper($attr) . '_NOT_DEFINED_ERROR'));
                return false;
            }
        }
        return true;
    }

    /**
     * @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(
            'id' => __('IVR_MODEL_ID'),
            'title' => __('IVR_MODEL_TITLE'),
            'extension' => __('IVR_MODEL_EXTENSION'),
            'description' => __('IVR_MODEL_DESCRIPTION'),
            'announce_file' => __('IVR_MODEL_ANNOUNCE_FILE'),
            'answer_time' => __('IVR_MODEL_ANSWER_TIME'),
            'answer_retry' => __('IVR_MODEL_ANSWER_RETRY'),
            'key_noInput_action' => __('IVR_MODEL_ACTION_KEY_NOINPUT'),
            'key_invalid_action' => __('IVR_MODEL_ACTION_KEY_INVALID'),
            'key_0_action' => __('IVR_MODEL_ACTION_KEY_0'),
            'key_1_action' => __('IVR_MODEL_ACTION_KEY_1'),
            'key_2_action' => __('IVR_MODEL_ACTION_KEY_2'),
            'key_3_action' => __('IVR_MODEL_ACTION_KEY_3'),
            'key_4_action' => __('IVR_MODEL_ACTION_KEY_4'),
            'key_5_action' => __('IVR_MODEL_ACTION_KEY_5'),
            'key_6_action' => __('IVR_MODEL_ACTION_KEY_6'),
            'key_7_action' => __('IVR_MODEL_ACTION_KEY_7'),
            'key_8_action' => __('IVR_MODEL_ACTION_KEY_8'),
            'key_9_action' => __('IVR_MODEL_ACTION_KEY_9'),
            'key_asterisk_action' => __('IVR_MODEL_ACTION_KEY_ASTERISK'),
            'key_pound_action' => __('IVR_MODEL_ACTION_KEY_POUND'),
            'scriptExtension' => __('USER_MODEL_SCRIPT_EXTENSION')
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CPhonalisaDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search($order = 'title')
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;
        $filter = $this->getFilter($criteria, $order);
        if ($filter != null) {
            
            $dataprovider = new CPhonalisaDataProvider($this, $filter);
            $routingIVRMax = PhonalisaLicenseManager::routingIVRMax();
            if ($routingIVRMax >= 0) {
                $dataprovider->pagination->pageSize = $dataprovider->pagination->pageSize > $routingIVRMax ? $routingIVRMax : $dataprovider->pagination->pageSize;
                $dataprovider->totalItemCount = $dataprovider->totalItemCount > $routingIVRMax ? $routingIVRMax : $dataprovider->totalItemCount;
            }
            return $dataprovider;
        }
    }

    public function getActionKeys()
    {
        return array(
            KeyType::noneSelected => 'IVR_MODEL_KEY_TYPE_NONE_SELECTED',
            KeyType::hangUp => 'IVR_MODEL_KEY_TYPE_REPLACE',
            KeyType::targetNumber => 'IVR_MODEL_KEY_TYPE_TARGET_NUMBER',
            KeyType::voiceMail => 'IVR_MODEL_KEY_TYPE_VOICE_MAIL',
            KeyType::retryAnnounce => 'IVR_MODEL_KEY_TYPE_RETRY_ANNOUNCE',
        );
    }

    public function getTranslatedActionKeys()
    {
        $translatedKeys = array();

        foreach ($this->getActionKeys() as $index => $key) {
            $translatedKeys[$index] = __($key);
        }
        asort($translatedKeys);

        return $translatedKeys;
    }

    public function getVoiceMailList()
    {
        $models = AudioFile::model()->find(array('type' => 'system'), 'name'); //AllByAttributes(array('type'=>'system'));
        $list = array();

        foreach ($models as $audioFile) {
            $list[$audioFile->id] = $audioFile->name;
        }

        array_unshift($list, '---');

        return $list;
    }

    public function getAudioFileList()
    {
        $models = AudioFile::model()->find(array('type' => AudioFileType::systemType), 'name'); //AllByAttributes(array('type'=>'system'));

        foreach ($models as $key => $model) {
            if (!AudioFileUseCase::compare($model->usecase, AudioFileUseCase::IVR)) {
                unset($models[$key]);
            }
        }

        $list = array();

        foreach ($models as $audioFile) {
            $list[strtolower($audioFile->name)] = $audioFile;
        }
        ksort($list);

        $audioFileList = CHtml::listData($list, 'id', 'name', 'type');
        if (isset($audioFileList[AudioFileType::systemType])) {
            $audioFileList[AudioFileType::getAudioFileTypesAsString(AudioFileType::systemType)] = $audioFileList[AudioFileType::systemType];
        } else {
            $audioFileList = array();
        }
        unset($audioFileList[AudioFileType::systemType]);

        return $audioFileList;
    }

    public function renderAnnounceFile()
    {
        $selectNoneAudioFile = array('' => '---');
        $audioFile = $this->getAudioFileList();
        $audioFileList = array_merge($selectNoneAudioFile, $audioFile);
        return $audioFileList;
    }

    public function getActionKeysData()
    {
        $action_keys = array();

        foreach (range(0, 9) as $action_key_id) {

            $action_keys[] = array(
                'id' => $action_key_id,
                'key' => 'key_' . $action_key_id . '_action',
                'value' => '',
            );
        }

        $action_keys[] = array(
            'id' => '10',
            'key' => 'key_pound_action',
            'value' => '',
        );
        $action_keys[] = array(
            'id' => '11',
            'key' => 'key_asterisk_action',
            'value' => '',
        );

        return $action_keys;
    }

    public function getAvailableRoutingTargets()
    {
        // FIXME: order by extention

        $listData = array();

        $listData['---'] = __('ROUTING_IVR_SELECT_TARGET');

        $users = User::model()->find(array(), 'extension');
        if (!empty($users)) {
            foreach ($users as $user) {
                $listData[__('RENDER_TARGET_USER')][(int) $user->extension][TargetType::User . '_' . base64_encode($user->extension) . '_' . $user->id] = getFormatedUsername($user);
            }
        }

        $groups = Groups::model()->find(array(), 'name');
        if (!empty($groups)) {
            foreach ($groups as $group) {
                if ($group->extension != '') {
                    $listData[__('RENDER_TARGET_GROUP')][(int) $group->extension][TargetType::Group . '_' . base64_encode($group->name) . '_' . $group->id] = '<' . $group->extension . '> ' . $group->name;
                }
            }
        }

        $ivrs = $this->find(array(), 'extension');
        if (!empty($ivrs)) {
            foreach ($ivrs as $ivr) {
                if ($ivr->id != $this->id) {
                    $listData[__('RENDER_TARGET_IVR')][(int) $ivr->extension][TargetType::Ivr . '_' . base64_encode($ivr->title) . '_' . $ivr->id] = '<' . $ivr->extension . '> ' . $ivr->title;
                }
            }
        }

        $callGroups = CallGroup::model()->find(array(), 'extension');
        if (!empty($callGroups)) {
            foreach ($callGroups as $callGroup) {
                $listData[__('CALL_GROUP')][(int) $callGroup->extension][TargetType::CallGroup . '_' . base64_encode($callGroup->name) . '_' . $callGroup->id] = '<' . $callGroup->extension . '> ' . $callGroup->name;
            }
        }

        $queues = Queue::model()->find(array(), 'extension');
        if (!empty($queues)) {
            foreach ($queues as $queue) {
                $listData[__('RENDER_TARGET_QUEUE')][(int) $queue->extension][TargetType::Queue . '_' . base64_encode($queue->name) . '_' . $queue->id] = '<' . $queue->extension . '> ' . $queue->name;
            }
        }

        $conferences = Conference::model()->find(array(), 'extension');
        if (!empty($conferences)) {
            foreach ($conferences as $conference) {
                $listData[__('RENDER_TARGET_CONFERENCE')][(int) $conference->extension][TargetType::Conference . '_' . base64_encode($conference->name) . '_' . $conference->id] = '<' . $conference->extension . '> ' . $conference->name;
            }
        }

        $sortedListData = array();
        foreach ($listData as $type => $data) {
            if (is_array($data)) {
                ksort($data);
                foreach ($data as $value => $label) {
                    foreach ($label as $key => $value) {
                        $sortedListData[$type][$key] = $value;
                    }
                }
            } else {
                $sortedListData[$type] = $data;
            }
        }
        return $sortedListData;
    }

    public function getAvailableUserTargets()
    {
        $listData = array();
        $listData['---'] = __('ROUTING_IVR_SELECT_TARGET');
        $users = User::model()->find(array(), 'extension');
        if (!empty($users)) {
            foreach ($users as $user) {
                $listData[__('RENDER_TARGET_USER')][(int) $user->extension][TargetType::VoiceMail . '_' . base64_encode($user->extension) . '_' . $user->id] = getFormatedUsername($user);
            }
        }
        $sortedListData = array();
        foreach ($listData as $type => $data) {
            if (is_array($data)) {
                ksort($data);
                foreach ($data as $value => $label) {
                    foreach ($label as $key => $value) {
                        $sortedListData[$type][$key] = $value;
                    }
                }
            } else {
                $sortedListData[$type] = $data;
            }
        }
        return $sortedListData;
    }

    public function getAvailableKeys()
    {
        return array(
            '0',
            '1',
            '2',
            '3',
            '4',
            '5',
            '6',
            '7',
            '8',
            '9',
            'asterisk',
            'pound',
            'invalid',
            'noInput',
        );
    }

    public function beforeSave()
    {
        $availableKeys = $this->getAvailableKeys();
        foreach ($availableKeys as $keyName) {
            $meta = 'key_' . $keyName . '_meta';
            if ($this->$meta == '---') {
                $this->$meta = '';
            }
        }
        return parent::beforeSave();
    }
}
