<?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';

    /**
     * @return list of available group types
     */

    /**
     * @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'),
                //'users'=>array('@'),
                'expression' => AccessManager::checkSessionPermission($this->module->name),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update'),
                //'users'=>array('@'),
                'expression' => AccessManager::checkSessionPermission($this->module->name),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete', 'ringMap'),
                //'users'=>array('@'),
                'expression' => AccessManager::checkSessionPermission($this->module->name),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $this->actionAdmin();
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $model = new CallGroup('search');
        $model->unsetAttributes();  // clear any default values

        if (isset($_GET['CallGroup'])) {
            $model->attributes = $_GET['CallGroup'];
        }
        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $model = new CallGroup();
        $this->processFormAction($model);
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        $model = $this->loadModel($id);
        $this->processFormAction($model);
    }

    protected function processFormAction($model)
    {
        $this->performAjaxValidation($model);
        $this->processCallGroupPost($model);
        $this->renderPartial('_form', array('model' => $model), false, true);
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'call-group-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    protected function processCallGroupPost($model)
    {
        if (isset($_POST['CallGroup'])) {
            $model->attributes = $_POST['CallGroup'];
            $model->attributes = $this->processManualTarget($model);
            TargetHelper::setTargetAttributes('target_type_on_timeout', 'target_on_timeout', $model);
            TargetHelper::setTargetAttributes('target_type_on_busy', 'target_on_busy', $model);
            TargetHelper::setTargetAttributes('target_type_on_nightcircut', 'target_on_nightcircut', $model);
            TargetHelper::setTargetAttributes('target_type_on_empty', 'target_on_empty', $model);
            $this->processModelSave($model);
        }
    }

    protected function processManualTarget($model)
    {
        $post = $_POST['CallGroup'];
        if ($post['target_on_timeout'] == TargetType::Manual) {
            $model->target_on_timeout = TargetType::Manual . '_' . $post['target_on_timeout-manual'];
        }
        if ($post['target_on_busy'] == TargetType::Manual) {
            $model->target_on_busy = TargetType::Manual . '_' . $post['target_on_busy-manual'];
        }
        if ($post['target_on_nightcircut'] == TargetType::Manual) {
            $model->target_on_nightcircut = TargetType::Manual . '_' . $post['target_on_nightcircut-manual'];
        }
        if ($post['target_on_empty'] == TargetType::Manual) {
            $model->target_on_empty = TargetType::Manual . '_' . $post['target_on_empty-manual'];
        }
        return $model;
    }

    protected function processModelSave($model)
    {
        if ($model->save()) {
            $this->processMemberToCallGroup($model);
            $this->savePermissions($model->id);
            $permissionModel = new Permissions();
            $permissionModel->createPermissionsFile();
        } else {
            $this->trowNewCHttpException();
        }
    }

    public function processMemberToCallGroup($model)
    {
        if (isset($_POST['UserToCallGroup'])) {
            $this->deleteUserToCallGroupModel($model);
            foreach ($_POST['UserToCallGroup'] as $value) {
                if (!empty($value['userId'])) {
                    $static_member = '0';
                    if (isset($value['static_member'])) {
                        $static_member = $value['static_member'];
                    }
                    $this->saveUserToCallGroupModel($value['userId'], $model->id, $static_member);
                }
            }
        } else {
            $this->deleteAllMembers($model);
        }
    }

    protected function deleteUserToCallGroupModel($model)
    {
        $newMembers = array();
        foreach ($_POST['UserToCallGroup'] as $value) {
            if (!empty($value['userId'])) {
                $newMembers[] = $value['userId'];
            }
        }
        $currentMembers = UserToCallGroup::model()->findAllByAttributes(array('callGroupId' => $model->id));
        $deleteArray = array();
        foreach ($currentMembers as $currentMember) {
            if (!in_array($currentMember->userId, $newMembers)) {
                $currentMember->delete();
            }
        }
    }

    protected function saveUserToCallGroupModel($userId, $callGroupId, $staticMember)
    {
        $userHasRelationWithThisGroup = UserToCallGroup::model()->findByAttributes(array('userId' => $userId, 'callGroupId' => $callGroupId));

        if (!$userHasRelationWithThisGroup) {
            $userToCallGroupModel = new UserToCallGroup();
            $userToCallGroupModel->userId = $userId;
            $userToCallGroupModel->callGroupId = $callGroupId;
            $userToCallGroupModel->static_member = $staticMember;
            if (!$userToCallGroupModel->save()) {
                $this->trowNewCHttpException();
            }
        } else {
            $userHasRelationWithThisGroup->static_member = $staticMember;
            if (!$userHasRelationWithThisGroup->save()) {
                $this->trowNewCHttpException();
            }
        }
    }

    protected function deleteAllMembers($model)
    {
        if (isset($_POST['yt0'])) {
            $members = UserToCallGroup::model()->findAllByAttributes(array('callGroupId' => $model->id));
            foreach ($members as $member) {
                $member->delete();
            }
        }
    }

    protected function trowNewCHttpException($errorCode = 500, $errorMessage = 'Can not save new data.')
    {
        throw new CHttpException($errorCode, $errorMessage);
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            foreach (UserToCallGroup::model()->findAllByAttributes(array('callGroupId' => $id)) as $relation) {
                $relation->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('admin'));
            }
        } else {
            $this->trowNewCHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model = CallGroup::model()->findByPk($id);
        if ($model === null) {
            $this->trowNewCHttpException(404, 'The requested page does not exist.');
        }
        return $model;
    }

    public function actionRingMap($id)
    {
        $model = $this->loadModel($id);
        $this->processMemberToCallGroup($model);
        $this->processTimeSlots($id);
        $userDataProvider = $model->getUserDataProvider();

        $this->render('ringMap', array(
            'model' => $model,
            'userModel' => User::model(),
            'userDataProvider' => $userDataProvider,
        ));
    }

    protected function processTimeSlots($id)
    {
        if (isset($_POST['TimeSlotsUser'])) {
            foreach ($_POST['TimeSlotsUser'] as $key => $value) {
                $model = User::model()->findByPk($key);
                if ($model == null) {
                    continue;
                }
                $this->saveTimeSlotsToModel($model, $id, $value);
            }
        }
    }

    protected function saveTimeSlotsToModel($model, $id, $values)
    {
        $keyPrefix = 'gc_' . $id . '_';
        $model->setValueForKey($keyPrefix . 'start', $values['start']);
        $model->setValueForKey($keyPrefix . 'end', $values['end']);
        if (!$model->save()) {
            $this->trowNewCHttpException();
        }
    }

    public function renderUserColumn($data, $row, $column)
    {
        $this->renderPartial('memberUserColumn', array('data' => $data, 'row' => $row, 'column' => $column));
    }

    public function renderRingTimeSlider($data, $row, $column)
    {
        $defaultMaxSliderTime = $this->getDefaultMaxSliderTime();
        $this->renderPartial('ringTime', array('data' => $data, 'row' => $row, 'column' => $column, 'defaultMaxSlider' => $defaultMaxSliderTime));
    }

    protected function getDefaultMaxSliderTime()
    {
        $defaultMaxSliderTime = 60;
        if (isset($_GET['id'])) {
            $model = CallGroup::model()->findByPk($_GET['id']);
            $defaultMaxSliderTime = $model->getDefaultMaxSliderTime();
        }
        return $defaultMaxSliderTime;
    }

    public function getTabularFormTabs($form, $model, $class, $maxlength)
    {
        $tabs = array();
        $count = 0;
        $translateKeys["generalData"] = __('QUEUE_MODEL_TAB_MENU_GENERAL_DATA');
        $translateKeys["additionalData"] = __('QUEUE_MODEL_TAB_MENU_ADDITIONAL_DATA');
        $translateKeys['addressbook'] = __('CALL_GROUP_ADDRESSBOOK');

        foreach ($translateKeys as $view => $tabLabel) {
            $tabs[] = array(
                'active' => $count++ === 0,
                'label' => $tabLabel,
                'content' => $this->renderPartialWithContextHelp(
                        $view, array(
                    'form' => $form,
                    'model' => $model,
                    'class' => $class,
                    'maxlength' => $maxlength
                        ), true),
            );
        }
        return $tabs;
    }

    public function renderAddressbookPermissions(PhonalisaRecord $data, $row, $column)
    {
        $htmlOptions = array('class' => $column->id);
        $permission = null;
        $hiddenValue = '0';

        if ($permission == null) {
            $permission = Permissions::model()->getPermissionsArray(
                    array(
                        'type' => $column->id,
                        'groupId' => $column->grid->filter->id,
                        'itemId' => $data->id
                    )
            );
            if ($permission) {
                $checked = true;
            } else {
                $checked = false;
            }
        }

        if (!array_key_exists('disabled', $htmlOptions)) {
            $hiddenValue = '0';
        }

        $html = CHtml::hiddenField('Permissions[' . $data->id . '][' . $column->id . ']', $hiddenValue);
        $html .= CHtml::checkBox('Permissions[' . $data->id . '][' . $column->id . ']', $checked, $htmlOptions);
        return $html;
    }

    public function renderAddressbookName(PhonalisaRecord $data, $row, $column)
    {
        return $data['title'];
    }

    public function renderAddressbookType(PhonalisaRecord $data, $row, $column)
    {
        return AddressbookType::getAddressbookType($data['type']);
    }

    public function savePermissions($modelId)
    {
        foreach ($_POST['Permissions'] as $itemId => $permissionTypes) {
            foreach ($permissionTypes as $permissionName => $value) {
                $oldPermission = Permissions::model()->findByAttributes(
                        array(
                            'groupId' => $modelId,
                            'itemId' => $itemId,
                            'type' => $permissionName
                        )
                );
                if ($value == '0') {
                    if (count($oldPermission)) {
                        $oldPermission->delete();
                    }
                } else {
                    if (!$oldPermission) {
                        $newPermission = new Permissions();
                        $newPermission->type = $permissionName;
                        $newPermission->groupId = $modelId;
                        $newPermission->itemId = $itemId;
                        $newPermission->save();
                    }
                }
            }
        }
    }

    public function renderStaticMember($data, $row, $column)
    {
        $callGroupID = '';
        if (isset($_REQUEST['id'])) {
            $callGroupID = $_REQUEST['id'];
        }
        $attributes = array(
            'userId' => $data->id,
            'callGroupId' => $callGroupID
        );
        $userToCallgroup = UserToCallGroup::model()->findByAttributes($attributes);
        if (!$userToCallgroup) {
            $userToCallgroup = new UserToCallGroup();
        }
        $name = "UserToCallGroup[$row][static_member]";
        $staticMember = '1';
        if (isset($userToCallgroup->static_member)) {
            $staticMember = $userToCallgroup->static_member;
        }
        return CHtml::checkBox($name, $staticMember);
    }
}
