<?php

class RoutingInbound extends PhonalisaRecord
{

    const TARGET_PATTERN_EXTENSION = '$1';
    const TARGET_PATTERN_ALL_NUMBERS = '(.*)';
    const EMPTY_TARGET_TYPE = '---';

    public $id;
    public $target;         //Target ID
    public $targetType;     //ExtensionType
    public $pattern;
    public $patternType;
    public $gw_id;
    public $sort;
    public $overwriteDialPrefix;
    public $active = 1;
    public $dateTimeProfile;
    public $cid_prefix;
    public $desc;
    public $score = 0;
    public $announcement;

    public static function myAttributes()
    {
        return array(
            'active' => 'active',
            'overwriteDialPrefix' => 'overwriteDialPrefix',
            'target' => 'target',
            'targetType' => 'targetType',
            'pattern' => 'pattern',
            'patternType' => 'patternType',
            'gw_id' => 'gw_id',
            'sort' => 'sort',
            'dateTimeProfile' => 'dateTimeProfile',
            'cid_prefix' => 'cid_prefix',
            'desc' => 'desc',
            'score' => 'score',
            "announcement" => "announcement"
        );
    }

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

    /**
     * @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('pattern, gw_id, sort', 'required'),
            array('target', 'required', 'except' => 'centralDropTarget'),
            array('sort, score', 'numerical', 'integerOnly' => true),
            array('active, target, dateTimeProfile, announcement', 'safe'),
            array('overwriteDialPrefix', 'length', 'max' => 2),
            array('targetType, patternType', 'length', 'max' => 36),
            array('desc', 'length', 'max' => 255),
            array('cid_prefix', 'length', 'max' => 6),
            array('cid_prefix', 'match', 'pattern' => '/^[0-9a-zA-Z_-]*$/'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => __('ROUTING_INBOUND_MODEL_ID'),
            'target' => __('ROUTING_INBOUND_MODEL_TARGET'),
            'pattern' => __('ROUTING_INBOUND_MODEL_PATTERN'),
            'gw_id' => __('ROUTING_INBOUND_MODEL_GW_ID'),
            'sort' => __('ROUTING_INBOUND_MODEL_SORT'),
            'dateTimeProfile' => __('ROUTING_INBOUND_MODEL_DATE_TIME_PROFILE'),
            'overwriteDialPrefix' => __('ROUTING_INBOUND_MODEL_OVERWRITE_DIAL_PREFIX'),
            'active' => __('ROUTING_INBOUND_MODEL_ACTIVE'),
            'cid_prefix' => __('ROUTING_INBOUND_MODEL_CID_PREFIX'),
            'desc' => __('ROUTING_INBOUND_MODEL_DESC'),
            'score' => __('ROUTING_INBOUND_MODEL_SCORE'),
            'announcement' => __("ROUTING_INBOUND_MODEL_ANNOUNCEMENT")
        );
    }

    /**
     * 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()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.
        $arrayModels = array();
        $newmodel = new RoutingInbound();
        if (isset($_GET['gw_id'])) {
            $newmodel->gw_id = $_GET['gw_id'];
        }

        $arrayModels = RoutingInbound::model()->find(array('gw_id' => $newmodel->gw_id), 'sort');
        $newmodel->id = "new";
        $newmodel->sort = "new";
        $arrayModelsCount = count($arrayModels);
        if ($arrayModelsCount >= 1) {
            $lastModel = $arrayModels[$arrayModelsCount - 1];
            $newmodel->patternType = $lastModel->patternType;
            if ($newmodel->patternType === (string) PatternType::ExtensionRange) {
                $newmodel->pattern = $lastModel->pattern;
            }
        }
        $arrayModels[] = $newmodel;

        $dataProvider = new CArrayDataProvider($arrayModels, array(
            'id' => 'key',
            'sort' => array('defaultOrder' => 'sort ASC'),
            'pagination' => false,
        ));
        return $dataProvider;
    }

    public function getCheckBoxDiv($colse = false)
    {
        $checkBoxDiv = '';
        if (!$colse) {
            $checkBoxDiv = '<div style="float:left;padding:5px 10px 0px 5px">';
        } else {
            $checkBoxDiv = '</div>';
        }
        return $checkBoxDiv;
    }

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

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

        $userTargets = $this->getUserTargets();
        if (!empty($userTargets)) {
            $listData[__('RENDER_TARGET_USER')] = $userTargets;
        }

        $grouptargets = $this->getGroupTargets();
        if (!empty($grouptargets)) {
            $listData[__('RENDER_TARGET_GROUP')] = $grouptargets;
        }

        $ivrTargets = $this->getIvrTargets();
        if (!empty($ivrTargets)) {
            $listData[__('RENDER_TARGET_IVR')] = $ivrTargets;
        }

        $callGroupTargets = $this->getCallGroupsTargets();
        if (!empty($callGroupTargets)) {
            $listData[__('CALL_GROUP')] = $callGroupTargets;
        }

        $queueTargets = $this->getQueueTargets();
        if (!empty($queueTargets)) {
            $listData[__('RENDER_TARGET_QUEUE')] = $queueTargets;
        }

        $conferencetargets = $this->getConferenceTargets();
        if (!empty($conferencetargets)) {
            $listData[__('RENDER_TARGET_CONFERENCE')] = $conferencetargets;
        }

        $faxUserTargets = $this->getUserFaxTargets();
        if (!empty($faxUserTargets) && PhonalisaLicenseManager::faxGUIEnabled()) {
            $listData[__('ROUTINGINBOUND_MODEL_TARGET_USER_FAX')] = $faxUserTargets;
        }

        $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;
            }
        }
        $availableRoutingTargets = $sortedListData;
        return $sortedListData;
    }

    public function getAvailableRoutingTargetsByType($type)
    {
        switch ($type) {
            case TargetType::User:
                return $this->getUserTargets();
            case TargetType::Group:
                return $this->getGroupTargets();
            case TargetType::Ivr:
                return $this->getIvrTargets();
            case TargetType::CallGroup:
                return $this->getCallGroupsTargets();
            case TargetType::Queue:
                return $this->getQueueTargets();
            case TargetType::Conference:
                return $this->getConferenceTargets();
            case TargetType::UserFax:
                return $this->getUserFaxTargets();
            case TargetType::UserVoiceMail:
                return $this->getUserVoiceMailTargets();
            case TargetType::Announcement:
                return $this->getAnnouncementTargets();
            default:
                return array(TargetType::Manual => "Manual");
        }
    }

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

    private function getGroupTargets()
    {
        $listData = array();
        $groups = Groups::model()->find(array(), 'extension');
        $availableGroups = array();
        foreach ($groups as $group) {
            if ($group->extension != null) {
                $availableGroups[] = $group;
            }
        }
        if (!empty($availableGroups)) {
            foreach ($availableGroups as $group) {
                $listData[TargetType::Group . '_' . $group->id] = '<' . $group->extension . '> ' . $group->name;
            }
        }
        return $listData;
    }

    private function getIvrTargets()
    {
        $listData = array();
        $ivrs = IVR::model()->find(array(), 'extension');
        if (!empty($ivrs)) {
            foreach ($ivrs as $ivr) {
                $listData[TargetType::Ivr . '_' . $ivr->id] = '<' . $ivr->extension . '> ' . $ivr->title;
            }
        }
        return $listData;
    }

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

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

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

    private function getUserFaxTargets()
    {
        $listData = array();
        $users = User::model()->find(array(), 'extension');
        foreach ($users as $user) {
            $listData[TargetType::UserFax . '_' . $user->id] = getFormatedUsername($user);
        }
        return $listData;
    }

    private function getUserVoiceMailTargets()
    {
        $listData = array();
        $users = User::model()->find(array(), 'extension');
        foreach ($users as $user) {
            $listData[TargetType::UserVoiceMail . '_' . $user->id] = getFormatedUsername($user);
        }
        return $listData;
    }

    private function getAnnouncementTargets()
    {
        $listData = array();
        $announcements = AudioFile::model()->find(array('type' => AudioFileType::systemType), 'name');
        foreach ($announcements as $announcement) {
            if (!empty($announcement->extension)) {
                $listData[TargetType::Announcement . '_' . $announcement->id] = $announcement->name;
            }
        }
        return $listData;
    }

    public function renderGatewayDropdown()
    {
        $gateways = Gateway::model()->findAll();
        if (count($gateways) == 1) {
            return NULL;
        }

        $keyActive = __('ROUTING_INBOUND_MODEL_ACTIVE');
        $keyDisabled = __('ROUTING_INBOUND_MODEL_DISABLED');

        $items['active'] = array('label' => $keyActive);
        $items = $this->getGateways($gateways, $items, "1", "✓ ");
        $items['disabled'] = array('label' => $keyDisabled);
        $items = $this->getGateways($gateways, $items, "0", "× ");

        return $items;
    }

    private function getGateways($gateways, $items, $active, $symbol)
    {
        foreach ($gateways as $gateway) {
            if ($gateway->active === $active) {
                $items[] = array(
                    'label' => $symbol . $gateway->name,
                    'url' => 'index.php?r=routingInbound/default/admin&gw_id=' . $gateway->id,
                    'active' => $gateway->id == $_REQUEST['gw_id'],
                );
            }
        }
        return $items;
    }

//    public static function csvRelevantAttributes($modelName)
//    {
//        return ImportHelper::getCsvRelevantModelAttributes($modelName);
//    }

    public function getExportNotRelevantAttributes()
    {
        return array(
            'gw_id',
            'dateTimeProfile',
        );
    }
}
