<?php

//include(__DIR__.'/../modules/provisioningGeneral/phones/tiptel-2xx/Tiptel.php');
// require_once __DIR__.'/../modules/provisioningGeneral/lib/PhoneModelFactory.php';

/**
 * This is the model class for table "phones".
 *
 * The followings are the available columns in table 'phones':
 * @property integer $id
 * @property string $type
 * @property string $mac_addr
 * @property integer $nobody_index
 * @property integer $added
 * @property string $firmware
 * @property integer $fw_manual_update
 * @property integer $sip_account_id
 */
class Phones extends PhonalisaRecord
{

    public $id;
    public $type;
    public $mac_addr;
    public $nobody_index;
    public $added;
    public $firmware;
    public $firmware_update_key;
    public $fw_manual_update;
    public $sip_account_id;
    public $last_sip_account_id;
    public $descr;
    public $ipv4_address; // this address is important, cause it is used by the provisioning trigger!
    public $last_prov_timestamp;
    public $last_prov_dateTime;
    public $provisioning_profile;
    public $group_phonebook;
    public $privat_phonebook;

    public static function myAttributes()
    {
        return array(
            'type' => 'type',
            'mac_addr' => 'mac_addr',
            'nobody_index' => 'nobody_index',
            'added' => 'added',
            'firmware' => 'firmware',
            'firmware_update_key' => 'firmware_update_key',
            'fw_manual_update' => 'fw_manual_update',
            'sip_account_id' => 'sip_account_id',
            'last_sip_account_id' => 'last_sip_account_id',
            'descr' => 'descr',
            'ipv4_address' => 'ipv4_address',
            'last_prov_timestamp' => 'last_prov_timestamp',
            'last_prov_dateTime' => array('key' => 'last_prov_dateTime', 'type' => 'dateTime'),
            'provisioning_profile' => 'provisioning_profile',
            'group_phonebook' => 'group_phonebook',
            'privat_phonebook' => 'privat_phonebook'
        );
    }

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Phones 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 'phones';
    }

    /**
     * @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('type, mac_addr, nobody_index, added, firmware, fw_manual_update, sip_account_id', 'required'),
            array('last_sip_account_id', 'safe'),
            array('added, fw_manual_update', 'numerical', 'integerOnly' => true),
            array('type', 'length', 'max' => 30),
            array('descr', 'length', 'max' => 70),
            array('mac_addr', 'length', 'max' => 17),
            array('firmware', 'length', 'max' => 25),
            array('firmware_update_key, last_prov_timestamp, last_prov_dateTime', 'safe'), //FIXME !!
            array('ipv4_address', 'length', 'max' => 15),
            array('provisioning_profile, group_phonebook, privat_phonebook', 'length', 'max' => 255),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array(
                'id,'
                . 'type,'
                . 'mac_addr,'
                . 'nobody_index,'
                . 'added, firmware,'
                . 'fw_manual_update,'
                . 'sip_account_id,'
                . 'last_sip_account_id,'
                . 'last_prov_timestamp',
                'safe',
                'on' => 'search'
            ),
        );
    }

    /**
     * @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(
            'sip_account_id' => array(self::BELONGS_TO, 'SipAccounts', 'id')
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => __('PROVISIONING_MODEL_ID'),
            'type' => __('PROVISIONING_MODEL_TYPE'),
            'mac_addr' => __('PROVISIONING_MODEL_MAC_ADDR'),
            'ipv4_address' => __('PROVISIONING_MODEL_IPV4_ADDR'),
            'nobody_index' => __('PROVISIONING_MODEL_NOBODY_INDEX'),
            'added' => __('PROVISIONING_MODEL_ADDED'),
            'firmware' => __('PROVISIONING_MODEL_FIRMEWARE'),
            'fw_manual_update' => __('PROVISIONING_MODEL_FW_MANUAL_UPDATE'),
            'sip_account_id' => __('PROVISIONING_MODEL_SIP_ACCOUNT_ID'),
            'descr' => __('PROVISIONING_MODEL_DESCR'),
            'firmware_update_key' => __('PHONE_MODEL_FIRMWARE_UPDATE_KEY'),
            'last_prov_timestamp' => __('PHONE_MODEL_LAST_PROV_TIMESTAMP'),
            'last_prov_dateTime' => __('PHONE_MODEL_LAST_PROV_TIMESTAMP'),
            'provisioning_profile' => __('USERGROUP_MODEL_PROVISIONING_PROFILE'),
            'group_phonebook' => __('PHONE_MODEL_GROUP_PHONEBOOK', true, 'messages', array("{type}" => __('ADDRESSESS_FORM_HEADER_BUSINESS'))),
            'privat_phonebook' => __('PHONE_MODEL_PRIVATE_PHONEBOOK', true, 'messages', array("{type}" => __('ADDRESSESS_FORM_HEADER_PRIVATE'))),
        );
    }

    public function primaryKey()
    {
        return 'id';
        // For composite primary key, return an array like the following
        // return array('pk1', 'pk2');
    }

    public function getSipAccount()
    {
        if ($this->sip_account_id == null || $this->sip_account_id == "") {
            return null;
        }
        return SipAccounts::model()->findByPk($this->sip_account_id);
    }

    public function renderSipAccount(PhonalisaRecord $data, $row)
    {
        $sipaccount = SipAccounts::model()->findByPk($data->sip_account_id);
        if ($sipaccount == null) {
            return __("Sipaccount with id: ") . $data->sip_account_id . __(" not found.");
        }

        $User = User::model()->findByPk($sipaccount->user_id);
        if ($User) {
            return $sipaccount->authname . " (" . $User->getDisplayName() . ")";
        } else {
            return "Nobody " . $sipaccount->authname;
        }

        return __("Nobody");
    }

    /**
     * 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 = 'type')
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;
        $filter = $this->getFilter($criteria, $order);

        $filter['pagination'] = array(
            'pageSize' => getGridPageSize('phones-grid'),
        );

        if ($filter != null) {
            return new CPhonalisaDataProvider(
                    $this, $filter
            );
        }
        /*
          $criteria->compare('id',$this->id);
          $criteria->compare('type',$this->type,true);
          $criteria->compare('mac_addr',$this->mac_addr,true);
          $criteria->compare('nobody_index',$this->nobody_index);
          $criteria->compare('added',$this->added);
          $criteria->compare('firmware',$this->firmware,true);
          $criteria->compare('fw_manual_update',$this->fw_manual_update);
          $criteria->compare('sip_account_id',$this->sip_account_id);

          return new CPhonalisaDataProvider($this, array(
          'criteria'=>$criteria,
          )); */
    }

    /**
     * Triggers the provisioning of this phone, this will make save a Job with Type Provisioning
     */
    public function triggerProvisioning()
    {
        $job = new Job();
        $job->setType(Job::Provisioning);
        $job->phone_id = $this->id;
        $sipaccount = $this->getSipAccount();
        if ($sipaccount) {
            $job->phone_extension = $sipaccount->authname;
        }
        $job->save();
    }

    public function getPhoneManufactorAndModelNames()
    {
        return PhoneModelFactory::getPhoneManufactorAndModelNames();
    }

    public function getPhoneKeyProfiles($groupId)
    {
        $userGroup = Groups::model()->findByPk($groupId);
        $userGroupKeyProfile = ProvisioningKeyProfile::model()->findByPk($userGroup->keyProfile);

        $parentId = $userGroup->parent;
        $keyProfiles = array();
        $parentIndex = 0;

        while ($parentId != '0') {
            $parentGroup = Groups::model()->findByPk($parentId);
            $parentKeyProfile = ProvisioningKeyProfile::model()->findByPk($parentGroup->keyProfile);
            if ($parentKeyProfile) {
                $keyProfiles["parent_$parentIndex"] = $parentKeyProfile;
                $parentIndex++;
            }
            $parentId = $parentGroup->parent;
        }

        $keyProfiles = array_reverse($keyProfiles);
        if ($userGroupKeyProfile) {
            $keyProfiles['group'] = $userGroupKeyProfile;
        }

        return $keyProfiles;
    }

    public function getPhoneKeysDataProvider(User $user, $level)
    {
        $userKeys = $this->getCurrentPhoneKeys($user, $level);
        $dataProvider = new CArrayDataProvider($userKeys, array('pagination' => false));
        return $dataProvider;
    }

    public function getPhoneKeysDataProviderForKeyProfile(ProvisioningKeyProfile $profile, $level)
    {
        $dataProvider = new CArrayDataProvider($this->getCurrentPhoneKeysForKeyProfile($profile, $level), array(
            'pagination' => false,
        ));
        return $dataProvider;
    }

    public function getCurrentPhoneKeysForKeyProfile($profile, $level)
    {
        $keysMerged = array();
        $phoneAvailableKeys = $this->getAvailableKeys($level);
        if ($profile != null) {
            $profileDefinedKeys = $this->getProfileDefinedPhoneKeys($profile);
        } else {
            $profileDefinedKeys = $phoneAvailableKeys;
        }

        foreach ($profileDefinedKeys as $profileDefinedKey) {
            if (array_key_exists($profileDefinedKey->name, $phoneAvailableKeys)) {
                //overwrite with user defined key data
                // backup of functions
                $originKey = $phoneAvailableKeys[$profileDefinedKey->name];

                $phoneAvailableKeys[$profileDefinedKey->name] = $profileDefinedKey;
                $phoneAvailableKeys[$profileDefinedKey->name]->availableFunctions = $originKey->availableFunctions;
            }
        }
        return array_values($phoneAvailableKeys);
    }

    private function getProfileDefinedPhoneKeys(ProvisioningKeyProfile $profile)
    {
        if ($profile->id != null) {
            return PhoneKey::model()->findAllByAttributes(array('profile_id' => $profile->id, 'phone' => $this->type));
        }
        return array();
    }

    public function saveProfileDefinedPhoneKeys(ProvisioningKeyProfile $profile, $newKeys)
    {
        foreach ($newKeys as $key) {
            if ($key->isButtonEmpty()) {
                if ($key->id == '') {
                    //is new record, and Button is not set? -> ignore
                    continue;
                } else {
                    //is old record, and Button is not set? -> delete!
                    $key->delete();
                }
            } else {
                //is new record, and Button is set? -> save
                //is old record, and Button is set? -> save
                $key->scenario = 'phoneKeyProfile';
                $key->isNewRecord = false;
                $key->profile_id = $profile->id;
                if (!$key->save()) {
                    print_r($key->errors);
                    die("key could not be safed!");
                }
            }
        }
    }

    public function getCurrentProfilePhoneKeys($profile, $level)
    {
        $keysMerged = array();
        $phoneAvailableKeys = $this->getAvailableKeys($level);
        if ($profile != null) {
            $profileDefinedKeys = $this->getProfileDefinedPhoneKeys($profile);
        } else {
            $profileDefinedKeys = $phoneAvailableKeys;
        }

        foreach ($profileDefinedKeys as $profileDefinedKey) {
            if (array_key_exists($profileDefinedKey->name, $phoneAvailableKeys)) {
                //overwrite with user defined key data
                // backup of functions
                $originKey = $phoneAvailableKeys[$profileDefinedKey->name];

                $phoneAvailableKeys[$profileDefinedKey->name] = $profileDefinedKey;
                $phoneAvailableKeys[$profileDefinedKey->name]->availableFunctions = $originKey->availableFunctions;
            }
        }
        return array_values($phoneAvailableKeys);
    }

    public function getCurrentPhoneKeys($user, $level)
    {
        $dummyKeyProfileID = cfg("DUMMY_KEY_PROFILE");
        $phoneAvailableKeys = $this->getAvailableKeys($level);
        if ($user != null) {
            $userDefinedKeys = $this->getUserDefinedPhoneKeys($user);
        } else if ($dummyKeyProfileID) {
            $userDefinedKeys = $this->getDummyKeyProfile($dummyKeyProfileID);
        } else {
            $userDefinedKeys = $phoneAvailableKeys;
        }

        foreach ($userDefinedKeys as $userDefinedKey) {
            if (array_key_exists($userDefinedKey->name, $phoneAvailableKeys)) {
                //overwrite with user defined key data
                // backup of functions
                $originKey = $phoneAvailableKeys[$userDefinedKey->name];

                $phoneAvailableKeys[$userDefinedKey->name] = $userDefinedKey;
                $phoneAvailableKeys[$userDefinedKey->name]->availableFunctions = $originKey->availableFunctions;
                if (startsWith(strtolower($phoneAvailableKeys[$userDefinedKey->name]->phone), 'snom') && empty($phoneAvailableKeys[$userDefinedKey->name]->snomKeyLabel)) {
                    $phoneAvailableKeys[$userDefinedKey->name]->snomKeyLabel = $originKey->snomKeyLabel;
                }
            }
        }
        return array_values($phoneAvailableKeys);
    }

    public function saveUserDefinedPhoneKeys(User $user, $newKeys)
    {
        $result = true;
        foreach ($newKeys as $key) {
            if ($key->isProfileDefined()) {
                continue;
            }
            if (!$this->processTiptelYealinkPhoneKeys($user, $key)) {
                return false;
            }
        }
        $user->triggerYourPhones();
        return true;
    }

    private function processTiptelYealinkPhoneKeys($user, $key)
    {
        $result = true;
        if ($key->profile_id) {
            $attributes = $key->attributes;
            unset($attributes['profile_id']);
            $key = new PhoneKey();
            $key->attributes = $attributes;
        }
        $key->scenario = 'phoneSettings';
        $key->isNewRecord = false;
        $key->user_id = $user->id;
        if (empty($key->function)) {
            $key->label = '';
            $key->number_data = '';
        }
        if (!$key->save()) {
            $result = false;
        }
        return $result;
    }

    private function getUserDefinedPhoneKeys(User $user)
    {
        $profiles = $this->getUserPhoneKeyProfiles($user);
        $profileDefinedKey = array();
        $defaultKeys = array();
        foreach ($profiles as $profile) {
            $profileDefinedKey = PhoneKey::model()->findAllByAttributes(
                    array(
                        'profile_id' => $profile->id,
                        'phone' => $this->type
                    )
            );
            foreach ($profileDefinedKey as $key) {
                if (!isset($defaultKeys[$key->name]) || !$defaultKeys[$key->name]->locked) {
                    if ($key->locked || (isset($key->function) && $key->function !== 'no')) {
                        $defaultKeys[$key->name] = $key;
                    }
                }
            }
        }

        $userDefinedPhonekeys = PhoneKey::model()->findAllByAttributes(
                array(
                    'user_id' => $user->id,
                    'phone' => $this->type
                )
        );
        foreach ($userDefinedPhonekeys as $key) {
            if (!isset($defaultKeys[$key->name]) || !$defaultKeys[$key->name]->locked) {
                $defaultKeys[$key->name] = $key;
            }
        }
        return $defaultKeys;
    }

    private function getUserPhoneKeyProfiles($user)
    {
        $profiles = array();
        if (!empty($user->keyProfile)) {
            $profile = ProvisioningKeyProfile::model()->findByPk($user->keyProfile);
            if ($profile) {
                $profiles['user'] = $profile;
            }
        }
        $groupProfiles = $this->getPhoneKeyProfiles($user->group);
        if ($groupProfiles) {
            $profiles = $groupProfiles + $profiles;
        }
        return $profiles;
    }

    private function getDummyKeyProfile($profileID)
    {
        $defaultKeys = array();
        $profileDefinedKey = PhoneKey::model()->findAllByAttributes(
                array(
                    'profile_id' => $profileID,
                    'phone' => $this->type
                )
        );

        foreach ($profileDefinedKey as $key) {
            $defaultKeys[$key->name] = $key;
        }
        return $defaultKeys;
    }

    private function getAvailableKeys($level)
    {
        $model = PhoneModelFactory::getPhoneModelOfType($this->type);
        if ($model) {
            return $model->getAvailableKeys($level);
        }
        return array();
    }

    public function getAvailableKeyLevels()
    {
        $model = PhoneModelFactory::getPhoneModelOfType($this->type);
        if ($model) {

            return $model->getAvailableKeyLevels();
        }
        return array();
    }

    public function getPhoneModelNameHumanReadable()
    {
        $model = PhoneModelFactory::getPhoneModelOfType($this->type);
        if ($model) {
            return $model->getPhoneModelNameHumanReadable();
        }
        return "";
    }

    public function beforeSave()
    {
        $curr = self::findByPk($this->id);
        if ($curr) {
            if ($curr->sip_account_id != $this->sip_account_id) {
                $this->triggerProvisioning();
                $this->removeAgentFromQueue($curr->sip_account_id);
            }
        }
        return parent::beforeSave();
    }

    public function beforeDelete()
    {
        $this->deletePhoneJobs();
        $this->deleteDummySipAccount();
        $this->removeAgentFromQueue($this->sip_account_id);
        return parent::beforeDelete();
    }

    protected function removeAgentFromQueue($sipAccountID)
    {
        $sipAccount = SipAccounts::model()->findByPk($sipAccountID);
        if ($sipAccount) {
            $userId = $sipAccount->user_id;
            $user = User::model()->findByPk($userId);
            $userSipAccounts = array();
            if ($user) {
                $userSipAccounts = $user->getSipAccounts();
            }
            if ($this->isLastPhone($userSipAccounts)) {
                $this->logoutFromAllQueues($userId);
            }
        }
    }

    protected function isLastPhone($userSipAccounts)
    {
        $wasLastPhone = true;
        foreach ($userSipAccounts as $otherSipAccount) {
            if (!empty($this->getPhonesForOtherSipAccounts($otherSipAccount->getPhones()))) {
                $wasLastPhone = false;
                break;
            }
        }
        return $wasLastPhone;
    }

    protected function getPhonesForOtherSipAccounts($phonesFromSipaccount)
    {
        if ($phonesFromSipaccount == NULL) {
            return $phonesFromSipaccount;
        }

        foreach ($phonesFromSipaccount as $key => $phoneFromSipaccount) {
            if ($phoneFromSipaccount->id == $this->id) {
                unset($phonesFromSipaccount[$key]);
            }
        }
        return $phonesFromSipaccount;
    }

    protected function logoutFromAllQueues($userId)
    {
        $tiers = Tiers::model()->findAllByAttributes(array('userId' => $userId, 'static_member' => '0', 'loggedIn' => '1'));
        foreach ($tiers as $tier) {
            $tier->loggedIn = 0;
            $tier->save();
        }
    }

    protected function deletePhoneJobs()
    {
        $phoneJobs = Job::model()->findAllByAttributes(array('phone_id' => $this->id));
        while (!empty($phoneJobs)) {
            foreach ($phoneJobs as $job) {
                $job->delete();
            }
            $phoneJobs = Job::model()->findAllByAttributes(array('phone_id' => $this->id));
        }
    }

    protected function deleteDummySipAccount()
    {
        $sipAccount = SipAccounts::model()->findByPk($this->nobody_index);
        if ($sipAccount) {
            $sipAccount->delete();
        }
    }

    public function getOptions($translated = true)
    {
        $manufactor = PhoneModelFactory::getManufactorOfType($this->type);

        $options = array();
        if ($manufactor) {
            foreach ($manufactor->getFunctions($translated) as $value => $label) { // FIXME
                $options[$value]['value'] = $value;
                $options[$value]['label'] = $label;
                #$options[$value]['data-translation-id']=$label;
                #$options[$value]['data-translation-target']='TEST';
            }
        } else {
            Log::e('no manufactor found !', 'Phonalisa-Phones-Model getOptions()');
        }
        return $options;
    }

    public function renderFunction($key)
    {
        $availableFunctions = $key->availableFunctions;
        asort($availableFunctions);

        $name = 'phoneKey[' . $key->name . '][function]';

        $function = $key->function;
        if (empty($function) && !$key->isNewRecord) {
            $function = '0';
        }
        //HOTFIX for Yealink js
        $htmlId = str_replace(".", "_", $name);
        $htmlId = str_replace("[", "_", $htmlId);
        $htmlId = str_replace("]", "", $htmlId);
        $htmlId = str_replace(" ", "_", $htmlId);
        return CHtml::dropDownList($name, $function, $availableFunctions, array(
                    'data-translation-target' => 'TEST',
                    'options' => $this->getOptions(),
                    'onChange' => 'toggleKeySelection(this)',
                    'id' => $htmlId,
                        )
        );
    }

    public function renderPhoneNamesDropdown()
    {
        $phones = $this->getPhoneManufactorAndModelNames();

        $items = array();

        $realType = $this->type;

        foreach ($phones as $phoneType => $phonesArray) {
            foreach ($phonesArray as $id => $name) {

                $this->type = $id;
                $keyLevels = $this->getAvailableKeyLevels();
                if (!is_array($keyLevels) || !isset($keyLevels[0])) {
                    continue;
                }
                $this->type = $realType;

                $items[$id] = array(
                    'label' => $name,
                    'url' => url('phonesettingsPhoneKey', array('phone' => $id)),
                );
            }
        }
        return $items;
    }

    // virtual attribute : name
    public function getName()
    {
        $phones = $this->getPhoneManufactorAndModelNames();
        foreach ($phones as $phonesArray) {
            if (array_key_exists($this->type, $phonesArray)) {
                return $phonesArray[$this->type];
            }
        }
        return null;
    }

    public function loggout()
    {
        $this->last_sip_account_id = $this->sip_account_id;
        $this->sip_account_id = $this->nobody_index;
        $this->save();

        // Do not user triggerProvisioning cause this phone is currently logged IN with the old sip account
        // and need to be triggert with this extension!
        $this->triggerProvisioning();

        $job = new Job();
        $job->setType(Job::Provisioning);
        $job->phone_id = $this->id;
        $sipaccount = SipAccounts::model()->findByPk($this->last_sip_account_id);
        if ($sipaccount) {
            $job->phone_extension = $sipaccount->authname;
        }
        $job->save();
    }

    public function loggin()
    {
        $this->sip_account_id = $this->last_sip_account_id;
        $this->last_sip_account_id = null;

        if (!$this->save()) {
            dump($this->errors);
            die('error in Phones::loggin()');
        }
        $this->triggerProvisioning();
    }

    public function getDefinedProvisioningProfiles($groupId)
    {
        $group = Groups::model()->findByPk($groupId);
        $parentGroups = $group->getParentGroups();
        $parameterProfiles = array();
        foreach ($parentGroups as $parentgroup) {
            if ($parentgroup->provisioningProfile != null) {
                $parameterProfiles[] = ProvisioningProfile::model()->findByPk($parentgroup->provisioningProfile);
            }
        }
        $parameterProfiles = array_reverse($parameterProfiles);
        $parameterProfiles[] = ProvisioningProfile::model()->findByPk($group->provisioningProfile);
        return $parameterProfiles;
    }

    public function getCurrentPhoneParameters($user)
    {
        $definedProvisioningProfiles = $this->getDefinedProvisioningProfiles($user->group);
        $definedParams = array();

        foreach ($definedProvisioningProfiles as $profile) {
//             $profileParams[] = $profile->getParamsForPhone($this->type);
            $profileParams = $profile->getParamsForPhone('tiptel-ip28xs');
            foreach ($profileParams as $param) {
                $definedParams[$param->name . '-' . $param->meta] = array(
                    'key' => $param->name,
                    'value' => $param->value,
                    'index' => $param->meta,
                );
            }
        }
        return $definedParams;
    }

///TEST 

    public function getManufactor()
    {
        $manufactor = PhoneModelFactory::getManufactorOfType($this->type);
        return get_class($manufactor);
    }

///TEST end

    public function humanReadableSearchFilterForType()
    {
        $list = array();
        $models = Phones::model()->findAll();

        foreach ($models as $model) {
            $allPhones = PhoneModelFactory::getPhoneManufactorAndModelNames();
            foreach ($allPhones as $phones) {
                foreach ($phones as $key => $value) {
                    if ($key == $model->type) {
                        $list[$key] = $value;
                    }
                }
            }
        }

        $selected = '';
        if (isset($_REQUEST['Phones']['type'])) {
            $selected = $_REQUEST['Phones']['type'];
        }
        asort($list);
        return $list;
    }

    public function humanReadableSearchFilterForSipAccountID()
    {
        $list = array();
        $models = Phones::model()->findAll();

        foreach ($models as $model) {
            $sipAccount = SipAccounts::model()->findByPk($model->sip_account_id);
            if ($sipAccount == null) {
                continue;
            }
            $user = User::model()->findByPk($sipAccount->user_id);
            $userName = "Nobody " . $sipAccount->authname;
            if ($user) {
                $userName = $sipAccount->authname . " (" . $user->getDisplayName() . ")";
            }
            $list[$model->sip_account_id] = $userName;
        }

        $selected = '';
        if (isset($_REQUEST['Phones']['sip_account_id'])) {
            $selected = $_REQUEST['Phones']['sip_account_id'];
        }
        asort($list);
        return $list;
    }

    public function getCallServiceURL($to, $id, $phone, $clip)
    {
        $phoneModel = PhoneModelFactory::getPhoneModelOfType($phone->type);
        return $phoneModel->getCallServiceURL($to, $id, $clip);
    }
}
