<?php

class DefaultController extends Controller
{

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';
    private $dateTimeProfileCache = null;
    private $availableRoutingTargetsCache = null;
    private $targetTypesWithoutTargets = array(
        TargetType::Extension => TargetType::Extension,
        TargetType::CentralDropTarget => TargetType::CentralDropTarget,
        TargetType::CallThrough => TargetType::CallThrough
    );

    private function getDateTimeProfiles()
    {
        if ($this->dateTimeProfileCache === null) {
            $this->dateTimeProfileCache = DateTimeProfile::model()->find(array(), 'title');
        }
        return $this->dateTimeProfileCache;
    }

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'admin', 'delete', 'ajaxValidate', 'select', 'export', "ajaxUpdateTargetList"),
                //'users'=>array('@'),
                'expression' => AccessManager::checkSessionPermission($this->module->name),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionSelect()
    {
        if (isset($_POST['gw_id'])) {
            $this->redirect(array('admin', 'gw_id' => $_POST['gw_id']));
        } else {
            // Redirect user gateway creating page if no gateways exists
            $this->redirect(array('/routingGateways/'));
        }
    }

    public function actionIndex()
    {
        $models = Gateway::model()->findAll();
        if (count($models) > 0) {
            $gatewayModel = $this->getGatewayModel();
            $this->redirect(array('admin', 'gw_id' => $gatewayModel->id));
        }
        $models = CHtml::listData($models, "id", "name");
        $this->render('create', array(
            'models' => $models,
        ));
    }

    private function getGatewayModel()
    {
        $models = Gateway::model()->find(array('active' => "1"), "name", 1, 0);
        if (empty($models)) {
            $models = Gateway::model()->find(array(), "name", 1, 0);
        }
        return $models[0];
    }

    public function actionAdmin()
    {
        $model = new RoutingInbound('search');
        if (isset($_POST['RoutingInbound'])) {
            foreach ($_POST['RoutingInbound'] as $id => $post) {
                if (isset($post['targetType']) && $post['targetType'] === RoutingInbound::EMPTY_TARGET_TYPE) {
                    continue;
                }
                if (in_array($post['targetType'], $this->targetTypesWithoutTargets) && $post['target'] === RoutingInbound::EMPTY_TARGET_TYPE) {
                    $post['target'] = $post['targetType'];
                }
                $this->updateRoutingRules($id, $post);
            }
        }
        $this->render('admin', array('model' => $model));
    }

    public function updateRoutingRules($id, $post)
    {
        $model = RoutingInbound::model()->findByPk($id);
        if (!$model) {
            $model = new RoutingInbound();
        }
        $model->attributes = $this->getAttributeValues($id, $post);
        if ($model->targetType == TargetType::CentralDropTarget || $model->targetType == TargetType::CallThrough) {
            $model->scenario = 'centralDropTarget';
        }
        $model->save();
    }

    public function getAttributeValues($id, $attributes)
    {
        if ((!isset($attributes['target']) || $attributes['target'] == '') && isset($attributes['targetType'])) {
            $attributes['target'] = $attributes['targetType'];
        }

        if ($attributes['pattern'] === RoutingInbound::EMPTY_TARGET_TYPE) {
            $attributes['pattern'] = '';
            $attributes['customPattern'] = '';
            $attributes['patternType'] = '';
        }
        if ($attributes['target'] === RoutingInbound::EMPTY_TARGET_TYPE) {
            $attributes['target'] = '';
            $attributes['customNumber'] = '';
            $attributes['targetType'] = '';
        }

        if (!$this->getTargetValues($attributes)) {
            $targetType = $attributes['target'];
            $attributes['target'] = $attributes['customNumber'];
            if ($targetType == TargetType::Extension) {
                $attributes['target'] = RoutingInbound::TARGET_PATTERN_EXTENSION;
            }

            if ($targetType == TargetType::CentralDropTarget) {
                $attributes['target'] = '';
            }
            $attributes['targetType'] = $targetType;
        }

        $pattern = $attributes['pattern'];
        $attributes['pattern'] = $attributes['customPattern'];
        $attributes['patternType'] = PatternType::Manual;
        if ($pattern === (string) PatternType::DID) {
            $attributes['pattern'] = RoutingInbound::TARGET_PATTERN_ALL_NUMBERS;
            $attributes['patternType'] = PatternType::DID;
        } else if (startsWith($pattern, (string) PatternType::ExtensionRange)) {
            $extension = explode('_', $pattern);
            $attributes['pattern'] = $extension[1];
            $attributes['patternType'] = PatternType::ExtensionRange;
        }

        if ($attributes['sort'] == 'new') {
            $attributes['sort'] = RoutingInbound::model()->countByAttributes(array('gw_id' => $_GET['gw_id']));
        }
        return $attributes;
    }

    public function getTargetValues(&$postedTarget)
    {
        $targets = explode('_', $postedTarget['target']);
        if (isset($targets[1])) {
            $postedTarget['targetType'] = $targets[0];
            $postedTarget['target'] = $targets[1];
        } else {
            return false;
        }
        return $postedTarget;
    }

    public function actionDelete($id)
    {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $model = RoutingInbound::model()->findByPk($id);
            $model->delete();
            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax'])) {
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array(''));
            }
            Yii::app()->end();
        } else {
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

    public function actionAjaxValidate()
    {
        $model = new RoutingInbound();
        $model->gw_id = 'validate';
        $errors = array();
        foreach ($_REQUEST['RoutingInbound'] as $modelId => $attributes) {
            if ((!isset($attributes['target']) || $attributes['target'] == '') && isset($attributes['targetType'])) {
                $attributes['target'] = $attributes['targetType'];
            }

            $attributes = $this->getFormatedAttribute($attributes, 'pattern', 'customPattern');
            $attributes = $this->getFormatedAttribute($attributes, 'target', 'customNumber');

            $model->attributes = $attributes;
            $sort = $attributes['sort'];
            if ($modelId == 'new') {
                $model->sort = 0;
            }
            $validateOutput = CActiveForm::validate($model);
            $decodetOutput = (array) json_decode($validateOutput);
            foreach ($decodetOutput as $key => $value) {
                //overwrite inputField Id
                $newKey = '';
                foreach (explode('_', $key) as $index => $part) {
                    if ($index == 0) {
                        $newKey .= $part . '_' . $modelId;
                    } else {
                        $newKey .= '_' . $part;
                    }
                }
                $errors[$modelId][$newKey] = $value;
            }
        }
        $errors = $this->removeNewAttributesFromErrorList($errors, 'RoutingInbound_new_pattern');
        $errors = $this->removeNewAttributesFromErrorList($errors, 'RoutingInbound_new_target');
        if (!empty($errors)) {
            echo json_encode($errors);
        }
        Yii::app()->end();
    }

    private function getFormatedAttribute($attributes, $attributeName, $customAttributeName)
    {
        if (!isset($attributes[$attributeName])) {
            $attributes[$attributeName] = "";
        }

        $searchForType = (string) PatternType::Manual;
        if ($attributeName === 'target') {
            $searchForType = (string) TargetType::Manual;
        }

        if (
                $attributes[$attributeName] === RoutingInbound::EMPTY_TARGET_TYPE ||
                ($attributeName === 'target' && $attributes['targetType'] === RoutingInbound::EMPTY_TARGET_TYPE)
        ) {
            $attributes[$attributeName] = '';
            if ($attributeName === 'target' && in_array($attributes['targetType'], $this->targetTypesWithoutTargets)) {
                $attributes[$attributeName] = $attributes['targetType'];
            }
        }
        if ($attributes[$attributeName] == $searchForType) {
            $attributes[$attributeName] = $attributes[$customAttributeName];
        }
        return $attributes;
    }

    private function removeNewAttributesFromErrorList($errors, $attributeName)
    {
        if (isset($errors['new'][$attributeName])) {
            unset($errors['new'][$attributeName]);
            if (empty($errors['new'])) {
                unset($errors['new']);
            }
        }
        return $errors;
    }

    public function renderDescCell($data, $row, $cell)
    {
        $this->renderPartial("desc_input", array("model" => $data));
    }

    public function renderAktivCell($data)
    {
        $this->renderPartial("activeCell", array("data" => $data));
    }

    public function renderPatternCell($data, $row, $cell)
    {
        $listData = $this->getPatternListData($data);
        if (!isset($data->patternType) || $data->patternType === '') {
            $data->patternType = (string) PatternType::Manual;
        }
        if ($data->id === 'new' && !isset($data->patternType)) {
            $data->patternType = RoutingInbound::EMPTY_TARGET_TYPE;
        }

        $selectedPattern = $this->getSelectedRoutingPattern($data);
        $visbleStyle = $this->getPatternCellVisibleStyle($data);
        $name = 'RoutingInbound[' . $data->id . '][pattern]';
        $this->renderPartial("patternCell", array(
            "data" => $data,
            'listData' => $listData,
            'visbleStyle' => $visbleStyle,
            'name' => $name,
            "selectedPattern" => $selectedPattern
        ));
    }

    protected function getPatternListData($data)
    {
        $gateway = Gateway::model()->findByPk($data->gw_id);
        $listData = array(RoutingInbound::EMPTY_TARGET_TYPE => __('ROUTING_INBOUND_SELECT_PATTERN'));

        $didRange = (int) $gateway->did_to - (int) $gateway->did_from;
        if ($didRange <= 20) {
            for ($i = (int) $gateway->did_from; $i <= (int) $gateway->did_to; $i++) {
                $listData[PatternType::ExtensionRange . "_$i"] = $i;
            }
        }

        $listData[PatternType::Manual] = __('RENDER_TARGET_TYPE_MANUAL');
        $listData[PatternType::DID] = __('ROUTING_INBOUND_DID') . " " . RoutingInbound::TARGET_PATTERN_ALL_NUMBERS;
        return $listData;
    }

    protected function getSelectedRoutingPattern($data)
    {
        $selectedTargetNumber = RoutingInbound::EMPTY_TARGET_TYPE;
        if ($data->patternType == (string) PatternType::ExtensionRange) {
            $selectedTargetNumber = $data->patternType . '_';
            $selectedTargetNumber .= $data->pattern;
        }
        if ($data->patternType == (string) PatternType::DID) {
            $selectedTargetNumber = PatternType::DID;
        }
        if ($data->patternType == TargetType::Manual) {
            $selectedTargetNumber = TargetType::Manual;
            if ($data->pattern == RoutingInbound::TARGET_PATTERN_ALL_NUMBERS) {
                $data->patternType = PatternType::DID;
                $selectedTargetNumber = PatternType::DID;
            }
        }
        return $selectedTargetNumber;
    }

    protected function getPatternCellVisibleStyle($data)
    {
        $visbleStyle = '';
        if ($data->patternType != PatternType::Manual) {
            $visbleStyle = 'style="display:inline-block;"';
        }
        return $visbleStyle;
    }

    public function renderTargetCell($data)
    {
        $listData = RoutingInbound::model()->getAvailableRoutingTargetsByType($data->targetType);
        $visbleStyle = $this->getRoutingTargetCellVisibleStyle($data);
        $targetTypeName = 'RoutingInbound[' . $data->id . '][targetType]';
        $targetName = 'RoutingInbound[' . $data->id . '][target]';
        $announcementName = 'RoutingInbound[' . $data->id . '][announcement]';

        $targetTypeList = $this->getTargetTypeList();
        asort($targetTypeList);

        $announcementList = RoutingInbound::model()->getAvailableRoutingTargetsByType(TargetType::Announcement);

        if ($data->targetType === NULL) {
            $data->targetType = RoutingInbound::EMPTY_TARGET_TYPE;
        }

        $this->renderPartial("targetCell", array(
            "targetTypeName" => $targetTypeName,
            "targetName" => $targetName,
            "announcementName" => $announcementName,
            "listData" => $this->changeListDataIfEmpty($listData),
            "targetTypes" => $targetTypeList,
            "announcementList" => $this->changeListDataIfEmpty($announcementList),
            "visbleStyle" => $visbleStyle,
            "data" => $data
        ));
    }

    protected function changeListDataIfEmpty($listData)
    {
        if (count($listData) < 1) {
            $listData = array('---' => '---');
        }
        return $listData;
    }

    protected function getTargetTypeList()
    {
        $targetHelper = new TargetHelper();
        return array(
            RoutingInbound::EMPTY_TARGET_TYPE => __('ROUTING_IVR_SELECT_TARGET'),
            TargetType::User => $targetHelper->getTranslationForTargetType(TargetType::User),
            TargetType::Group => $targetHelper->getTranslationForTargetType(TargetType::Group),
            TargetType::Manual => $targetHelper->getTranslationForTargetType(TargetType::Manual),
            TargetType::Ivr => $targetHelper->getTranslationForTargetType(TargetType::Ivr),
            TargetType::Queue => $targetHelper->getTranslationForTargetType(TargetType::Queue),
            TargetType::Conference => $targetHelper->getTranslationForTargetType(TargetType::Conference),
            TargetType::UserFax => $targetHelper->getTranslationForTargetType(TargetType::UserFax),
            TargetType::CallThrough => $targetHelper->getTranslationForTargetType(TargetType::CallThrough),
            TargetType::UserVoiceMail => $targetHelper->getTranslationForTargetType(TargetType::UserVoiceMail),
            TargetType::CallGroup => $targetHelper->getTranslationForTargetType(TargetType::CallGroup),
            TargetType::CentralDropTarget => $targetHelper->getTranslationForTargetType(TargetType::CentralDropTarget),
            TargetType::Announcement => $targetHelper->getTranslationForTargetType(TargetType::Announcement),
            TargetType::Extension => $targetHelper->getTranslationForTargetType(TargetType::Extension)
        );
    }

    protected function getRoutingTargetCellVisibleStyle($data)
    {
        $visbleStyle = '';
        if ($data->targetType != TargetType::Manual && $data->targetType != RoutingInbound::EMPTY_TARGET_TYPE && isset($data->targetType)) {
            $visbleStyle = 'style="display:inline-block;"';
        }
        return $visbleStyle;
    }

    public function renderDateTimeProfile(PhonalisaRecord $data, $row, $column)
    {
        $listData = array('' => RoutingInbound::EMPTY_TARGET_TYPE);
        $listData = array_merge($listData, CHtml::listData($this->getDateTimeProfiles(), 'id', 'title'));
        $this->renderPartial('dateTimeProfileCell', array('listData' => $listData, 'data' => $data));
    }

    public function renderHiddenSortCell($data)
    {
        $this->renderPartial("hiddenSortCell", array("data" => $data));
    }

    public function renderDialoutPrefixCell($data)
    {
        if ($data->overwriteDialPrefix != '') {
            $checked = true;
            $displayTextField = 'display:inline;';
        } else {
            $checked = false;
            $displayTextField = 'display:none;';
        }
        $this->renderPartial("dialoutPrefixCell", array(
            "data" => $data,
            "checked" => $checked,
            "displayTextField" => $displayTextField
        ));
    }

    public function renderCidPrefixCell($data)
    {
        $this->renderPartial("cidPrefixCell", array("data" => $data));
    }

    public function renderScoreDropdown(PhonalisaRecord $data, $row, $column)
    {
        $listData = array(RoutingInbound::EMPTY_TARGET_TYPE);
        for ($i = 1; $i <= 9; $i++) {
            $text = __('ROUTING_INBOUND_SCORE_LEVEL_NEUTRAL');
            if ($i < 5) {
                $text = __('ROUTING_INBOUND_SCORE_LEVEL_REPUTABLE');
            } else if ($i > 5) {
                $text = __('ROUTING_INBOUND_SCORE_LEVEL_DUBIOUS');
            }
            $listData[$text][$i] = $i;
        }
        $this->renderPartial('scoreCell', array('listData' => $listData, 'data' => $data));
    }

    public function actionExport($gw_id = '')
    {
        if ($gw_id) {
            ExportHelper::exportSpecificModelAsCSV('RoutingInbound', array('gw_id' => $gw_id));
        } else {
            ExportHelper::exportModelAsCSV('RoutingInbound');
        }
    }

    public function actionAjaxUpdateTargetList()
    {
        $type = Yii::app()->request->getPost('type');
        $result = array();
        $result["availableTargets"] = array();

        if ($type == RoutingInbound::EMPTY_TARGET_TYPE) {
            $result["targetType"] = $type;
            echo json_encode($result);
            return;
        }

        $type = (int) $type;
        $result["targetType"] = $type;

        if ($type == TargetType::CallThrough || $type == TargetType::CentralDropTarget || $type == TargetType::Extension) {
            $result["target"] = $type;
            echo json_encode($result);
            return;
        }

        if ($type == TargetType::Manual) {
            $result["availableTargets"][TargetType::Manual] = "Manual";
        } else if ($type == TargetType::Announcement) {
            foreach (RoutingInbound::model()->getAvailableRoutingTargetsByType($type) as $announcementID => $announcementName) {
                $result["availableTargets"][$announcementID] = $announcementName;
            }
        } else {
            foreach (RoutingInbound::model()->getAvailableRoutingTargetsByType($type) as $value => $label) {
                $result["availableTargets"][$value] = $label;
            }
        }

        echo json_encode($result);
    }
}
