<?php

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

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $model = new ProvisioningKeyProfile();
        $defaultPhoneModelName = $this->getDefaultPhoneModelName($model);
        $defaultParameter = $model->getPhoneModelOfType($defaultPhoneModelName);
        $buffer = false;

        $this->performAjaxValidation($model);
        if (isset($_POST['ProvisioningKeyProfile'])) {
            $model->attributes = $_POST['ProvisioningKeyProfile'];
            if (isset($_REQUEST['phone'])) {
                $model->lastEditedPhoneType = $_REQUEST['phone'];
            }
            if ($model->save()) {
                $this->savePhoneKeys($model, $defaultParameter);
                Yii::app()->user->setFlash('success', '<strong>' . __('CHANGES_SAVED_SUCCSESSFULLY') . '</strong>');
                $this->redirect(url('/provisioningKeyProfile/default/index'));
            } else {
                Yii::app()->user->setFlash('error', '<strong>' . __('CHANGES_NOT_SAVED_CAUSE_OF_AN_ERROR') . '</strong>');
                $buffer = true;
            }
        }
        $this->render('_form', array(
            'profile' => $model,
            'defaultParameter' => $defaultParameter,
            'selectedPhone' => $defaultPhoneModelName,
            'buffer' => $buffer
        ));
    }

    /**
     * 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);
        $defaultPhoneModelName = $this->getDefaultPhoneModelName($model);
        $defaultParameter = $model->getPhoneModelOfType($defaultPhoneModelName);
        $buffer = false;
        $this->performAjaxValidation($model);
        if (isset($_POST['ProvisioningKeyProfile'])) {
            $model->attributes = $_POST['ProvisioningKeyProfile'];
            if (isset($_REQUEST['phone'])) {
                $model->lastEditedPhoneType = $_REQUEST['phone'];
            }
            if ($model->save()) {
                $this->savePhoneKeys($model, $defaultParameter);
                $this->updateErgophoneXmlFiles($model);
                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>');
                $buffer = true;
            }
        }
        $this->render('_form', array(
            'profile' => $model,
            'defaultParameter' => $defaultParameter,
            'selectedPhone' => $defaultPhoneModelName,
            'buffer' => $buffer
        ));
    }

    public function updateErgophoneXmlFiles($model)
    {
        $grups = Groups::model()->findAllByAttributes(array('keyProfile' => $model->id));
        foreach ($grups as $group) {
            //triggers the afterSave method from group model.
            $group->save();
        }
    }

    public function bufferPhoneKeys($model, $defaultParameter, $level = '')
    {
        $currentKeys = $defaultParameter->getCurrentProfilePhoneKeys($model, $level);
        $newKeys = array();
        if (isset($_POST['phoneKey'])) {
            foreach ($currentKeys as $key) {
                $key_post = $_POST['phoneKey'][$key->name];
                $key_post['phone'] = $this->getDefaultPhoneModelName($model);
                $key_post['name'] = $key->name;
                $key_post['key_idx'] = $key->key_idx;
                $key_post['level'] = $key->level;
                $key->attributes = $key_post;
                $newKeys[] = $key;
            }
        }
        $dataProvider = new CArrayDataProvider($newKeys, array('pagination' => false));
        return $dataProvider;
    }

    public function savePhoneKeys($model, $defaultParameter)
    {
        $availableLevels = $defaultParameter->getAvailableKeyLevels();
        $currentKeys = array();
        foreach ($availableLevels as $level) {
            $currentKeys = array_merge($currentKeys, $defaultParameter->getCurrentProfilePhoneKeys($model, $level['level']));
        }
        $newKeys = array();
        foreach ($currentKeys as $key) {
            $key_post = $_POST['phoneKey'][$key->name];
            $key_post['phone'] = $this->getDefaultPhoneModelName($model);
            $key_post['name'] = $key->name;
            $key_post['key_idx'] = $key->key_idx;
            $key->attributes = $key_post;
            if ($key->function === 'no') {
                $key->label = '';
                $key->number_data = '';
            }
            $newKeys[] = $key;
        }
        $defaultParameter->saveProfileDefinedPhoneKeys($model, $newKeys);
    }

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

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $model = new ProvisioningKeyProfile();
        $this->render('index', array(
            'model' => $model,
        ));
    }

    /**
     * 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 = ProvisioningKeyProfile::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'] === 'provisioning-key-profile-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function getDefaultPhoneModelName($model)
    {
        $phoneName = 'os15';
        if (isset($_GET['phone'])) {
            $phoneName = $_GET['phone'];
        } else if (!empty($model->lastEditedPhoneType)) {
            $phoneName = $model->lastEditedPhoneType;
        }
        return $phoneName;
    }

    public function renderPhoneNamesDropdown($url = 'create')
    {
        //FIXME !
        if (isset($_GET['id'])) {
            $url = 'update&id=' . $_GET['id'];
        }
        $phone = new Phones();
        $phones = $phone->getPhoneManufactorAndModelNames();
        $items = array();
        foreach ($phones as $phoneType => $phonesArray) {
            foreach ($phonesArray as $id => $name) {
                $phone->type = $id;
                if (!count($phone->getAvailableKeyLevels())) {
                    continue;
                }
                $items[$id] = array(
                    'label' => $name,
                    'url' => url('provisioningKeyProfile/default/' . $url, array('phone' => $id)),
                    'htmlOptions' => array('style' => 'color:red;'),
                );
            }
        }
        return $items;
    }

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

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

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

    public function getAllQueues()
    {
        $queues = Queue::model()->findAll();
        $queuesArray = array();
        foreach ($queues as $queue) {
            $queuesArray[$queue->extension] = getFormatedNameWithExtension($queue->name, $queue->extension);
        }
        return $queuesArray;
    }

    public function getAllCallGroup()
    {
        $callGroups = CallGroup::model()->findAll();
        $callGroupArray = array();
        foreach ($callGroups as $callGroup) {
            $callGroupArray[$callGroup->extension] = getFormatedNameWithExtension($callGroup->name, $callGroup->extension);
        }
        return $callGroupArray;
    }
}
