<?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 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', 'view', 'selectPhone', 'restoreKey'),
                //'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'),
                //'users'=>array('@'),
                'expression' => AccessManager::checkSessionPermission($this->module->name),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
        $this->render('view', array('model' => $this->loadModel($id)));
    }

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

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['PhoneKey'])) {
            $model->attributes = $_POST['PhoneKey'];
            if ($model->save()) {
                $this->redirect(array('view', 'id' => $model->id));
            }
        }
        $this->render('create', array('model' => $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);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['PhoneKey'])) {
            $model->attributes = $_POST['PhoneKey'];
            if ($model->save()) {
                Yii::app()->user->setFlash('success', '<strong>' . __('CHANGES_SAVED_SUCCSESSFULLY') . '</strong>');
                $this->redirect(array('view', 'id' => $model->id));
            } else {
                Yii::app()->user->setFlash('error', '<strong>' . __('CHANGES_NOT_SAVED_CAUSE_OF_AN_ERROR') . '</strong>');
            }
        }
        $this->render('update', array('model' => $model));
    }

    /**
     * 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();

            // 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 {
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        if (!isset($_REQUEST['phone'])) {
            $this->redirect(array('admin', 'phone' => $this->getCurrentPhoneModelName()));
        } else {
            $this->redirect(array('admin', 'phone' => $_REQUEST['phone']));
        }
    }

    /**
     * Manages all models.
     */
    public function actionAdmin($alert = array())
    {
        $phone = $this->getPhoneModelOfType(@$_REQUEST["phone"]);
        $user = User::model()->findByPk(Yii::app()->user->sudoUser);
        //FIXME !! dont save eny empty key !
        if (isset($_POST['phoneKey'])) {

            $availableLevels = $phone->getAvailableKeyLevels();
            $currentKeys = array();
            foreach ($availableLevels as $level) {
                $currentKeys = array_merge($currentKeys, $phone->getCurrentPhoneKeys($user, $level['level']));
            }

            $newKeys = array();
            foreach ($currentKeys as $key) {
                if (isset($_POST['phoneKey'][$key->name])) {
                    $key_post = $_POST['phoneKey'][$key->name];
                    $key->attributes = $key_post;
                    if ($key->function === 'no') {
                        $key->label = '';
                        $key->number_data = '';
                    }
                    $newKeys[] = $key;
                }
            }

            if ($phone->saveUserDefinedPhoneKeys($user, $newKeys)) {
                ErgophoneHelper::createErgophoneConfigFilesForExtension($user->extension);
                Yii::app()->user->setFlash('success', '<strong>' . __('CHANGES_SAVED_SUCCSESSFULLY') . '</strong>');
            } else {
                Yii::app()->user->setFlash('error', '<strong>' . __('CHANGES_NOT_SAVED_CAUSE_OF_AN_ERROR') . '</strong>');
            }
        }
        $this->render('admin', array(
            'model' => $phone,
            'alert' => $alert,
            'user' => $user,
        ));
    }

    public function getCurrentPhoneModelName()
    {
        $phone = $this->getCurrentPhone();
        if ($phone) {
            return $phone->type;
        }
        //if there is no phone found, give back the first found phone in manufactors
        $phones = PhoneModelFactory::getPhoneManufactorAndModelNames();
        $firstManufactor = $phones[key($phones)];
        return key($firstManufactor);
    }

    private function getPhoneModelOfType($type)
    {
        $phone = new Phones();
        $phone->type = $type;
        return $phone;
    }

    private function getCurrentPhone()
    {
        $user_id = Yii::app()->user->sudoUser;
        $User = User::model()->findByPk($user_id);

        if ($User == null) {
            return null;
        }

        $SipAccounts = $User->getSipAccounts();

        if (count($SipAccounts) != 0) {
            $SipAccount = $SipAccounts[0];
            $Phone = $SipAccount->getPhone();
            if ($Phone) {
                return $Phone;
            }
        }
        return null;
    }

    /**
     * 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 = PhoneKey::model()->findByPk($id);
        if ($model === null) {
            throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $model;
    }

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

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

    public function getSortedAvialableFunctions($phoneKey)
    {
        $availableFunctions = $phoneKey->availableFunctions;
        asort($availableFunctions);
        return $availableFunctions;
    }

    public function renderKeyName($data, $row, $colum)
    {
        return PhoneKey::getKeyNameLabel($data);
    }

    public function getUserQueues()
    {
        $user = app()->user->sudoUserInstance;
        $tiers = Tiers::model()->findAllByAttributes(array('userId' => $user->id));
        $queues = array();
        foreach ($tiers as $tier) {
            $model = Queue::model()->findByPk($tier->queueId);
            if ($model) {
                $queues[$model->extension] = getFormatedNameWithExtension($model->name, $model->extension);
            }
        }
        return $queues;
    }

    public function getUserCallGroup()
    {
        $user = app()->user->sudoUserInstance;
        $userToCallGroups = UserToCallGroup::model()->findAllByAttributes(array('userId' => $user->id));
        $callGroups = array();
        foreach ($userToCallGroups as $userToCallGroup) {
            $model = CallGroup::model()->findByPk($userToCallGroup->callGroupId);
            if ($model) {
                $callGroups[$model->extension] = getFormatedNameWithExtension($model->name, $model->extension);
            }
        }
        return $callGroups;
    }

    public function getForwardList()
    {
        $callForwards = app()->user->sudoUserInstance->getForwardingSets();
        $list = array();
        foreach ($callForwards as $callForward) {
            $callForwardKey = $callForward->getPhoneKey();
            if ($callForwardKey !== '' && $callForwardKey !== null) {
                $list[$callForwardKey] = $callForward->name;
            }
        }
        ksort($list);
        return $list;
    }

    public function actionRestoreKey()
    {
        $id = Yii::app()->request->getParam('id', '');
        $user = User::model()->findByPk(Yii::app()->user->sudoUser);
        $result = array();
        $model = PhoneKey::model()->findByPK($id);
        if (!empty($model->user_id)) {
            $phone = $this->getPhoneModelOfType($model->phone);
            if ($phone && $model->delete()) {
                $result = $this->getDefaultKeyValues($phone->getCurrentPhoneKeys($user, $model->level), $model);
            }
        }
        echo json_encode($result);
    }

    private function getDefaultKeyValues($currentPhoneKeys, $model)
    {
        $result = array();
        foreach ($currentPhoneKeys as $currentKey) {
            if ($currentKey->name == $model->name) {
                $currentKeyName = str_replace(' ', '_', $currentKey->name);
                $result['phoneKey_' . $currentKeyName . '_function'] = $currentKey->function;
                $result['phoneKey_' . $currentKeyName . '_number_data'] = $currentKey->number_data;
                $result['phoneKey_' . $currentKeyName . '_label'] = $currentKey->label;
            }
        }
        return $result;
    }

    public function restoreButtonVisibility($data, $row)
    {
        $visibility = false;
        if (!empty($row->user_id)) {
            $visibility = true;
        }
        return $visibility;
    }
}
