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

    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',
                    'generateData',
                    'rateUcItem',
                    'getFaxPdfDocument',
                    'faxPage',
                    'getVoicemailFile',
                    'getFaxPdf',
                    'createFax',
                    'ajaxImportNumber',
                    'viewAddress',
                    'setRead',
                    'downloadFile',
                    'saveNote',
                    'deleteNote',
                    'delete',
                ),
                'expression' => AccessManager::checkSessionPermission($this->module->name),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionViewAddress($addressReferecne)
    {
        $address = Addresses::model()->findByPk($addressReferecne);
        if ($address) {
            $url = bu()
                    . url(
                            'addressbookAddresses/default/index', array('id' => $address->contact_tid, 'addressId' => $address->id)
            );
            echo json_encode(array('url' => $url));
        }
    }

    public function actionAjaxImportNumber()
    {
        $model = new Addresses();
        $model->tel_work = isset($_POST['number']) ? $_POST['number'] : '';
        $ucItemId = isset($_POST['itemId']) ? $_POST['itemId'] : null;

        $ucItem = UCItem::model()->findByPk($ucItemId);
        if (!$ucItem) {
            throw new CHttpException(404, 'UCItem not found');
        }

        $cfgPrefix = cfg('DP_AUTO_DIALOUT_PREFIX');
        if (trim($cfgPrefix) !== '') {
            $model->tel_work = $this->removeDialOutPrefixIfSet($ucItem, $model->tel_work, $cfgPrefix);
        }

        $user = app()->user->sudoUserInstance;
        $telAttributes = Addresses::getTelAttributes();

        $books = CHtml::listData($user->getAddressbooks('write', true), 'id', 'title');
        $this->performAjaxValidation($model);
        if (isset($_POST['Addresses'])) {
            $number = $_POST['Addresses']['tel_work'];
            $numberAttribute = $this->validateNumberTypeAttributePost($_POST['Addresses']['typeOfNumber']);

            $model->$numberAttribute = $number;
            unset($_POST['Addresses']['tel_work']);

            $model->attributes = $_POST['Addresses'];

            if (!$model->save()) {
                dump($model->errors);
            } else {
                $ucItem = UCItem::model()->findByPk($_POST['itemId']);
                $ucItem->caller_addressbook_id = $model->id;
                $ucItem->save();
            }
        }
        $defaultTypeOfNumber = 'tel_work';
        if ($ucItem->typ === 'fax') {
            $defaultTypeOfNumber = 'tel_fax';
        }

        $this->renderPartial(
                'importNumber', array(
            'model' => $model,
            'itemId' => $_POST['itemId'],
            'books' => $books,
            'defaultTypeOfNumber' => $defaultTypeOfNumber,
            'telAttributes' => $telAttributes
                ), false, true
        );
    }

    private function validateNumberTypeAttributePost($postValue)
    {
        if (!Addresses::isNumberAttribute($postValue)) {
            throw new CHttpException(403, __("CHANGES_NOT_SAVED_CAUSE_OF_AN_ERROR"));
        }
        return $postValue;
    }

    protected function removeDialOutPrefixIfSet($ucItem, $number, $cfgPrefix)
    {
        if ((strpos($number, $cfgPrefix) !== false)) {
            if ($ucItem->valueForKey('from_external') === '1' || (isset($ucItem->direction) && $ucItem->direction === '0') || $ucItem->typ === 'fax') {
                $number = preg_replace("/$cfgPrefix/", '', $number, 1);
            }
        }
        return $number;
    }

    public function actionSaveNote($id)
    {
        $saved = false;

        if (isset($_POST['note'])) {
            $model = $this->loadModel($id);
            $model->note = $_POST['note'];

            $saved = $model->save();
        }

        return json_encode($saved);
    }

    public function actionDeleteNote($id)
    {
        $deleted = false;

        if (isset($_POST)) {
            $model = $this->loadModel($id);
            $model->note = '';
            $deleted = $model->save();
        }

        return json_encode($model->note);
    }

    /**
     * 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()
    {
        $model = new UCItem;
        $total = UCItem::model()->count();

        $pages = new CPagination($total);
        $pages->pageSize = 40;

        $user = app()->user->sudoUserInstance;
        if (!$user) {
            app()->user->logout();
            app()->user->loginRequired();
        }

        $condition['owner_id'] = $user->id;
        foreach ($user->getUserGroupIds() as $groupId) {
            $condition['owner_id'] .= '|' . $groupId;
        }

        foreach ($user->getCallGroupIds() as $callGroupId) {
            $condition['owner_id'] .= '|' . $callGroupId;
        }

        foreach ($user->getUserQueueIds() as $queueId) {
            $condition['owner_id'] .= '|' . $queueId;
        }

        if (isset($_REQUEST['typ']) && $_REQUEST['typ'] == 'vm') {
            $condition['typ'] = 'call';
            $condition['target'] = 'vm-*';
        } elseif (isset($_REQUEST['typ']) && $_REQUEST['typ'] == 'call') {
            $condition['typ'] = 'call|gcall';
        } elseif (isset($_REQUEST['typ']) && $_REQUEST['typ'] == 'callrecording') {
            $condition['typ'] = 'gcall|call|callrecording';
            $condition['record_data'] = '*';
        } else {
            $condition['typ'] = isset($_REQUEST['typ']) ? $_REQUEST['typ'] : '*';
        }

        $items = UCItem::model()->find($condition, 'timestamp DESC', $pages->limit, $pages->offset);
        $this->setItemCallerNames($items);

        $this->render('index', array(
            'items' => $items,
            'pages' => $pages,
            'model' => $model,
            'faxMenuAllowed' => $this->faxMenuIsAllowed($user)
        ));
    }

    public function setItemCallerNames(&$items)
    {
        $interlocutorCache = array();
        foreach ($items as $item) {
            if (!array_key_exists($item->caller_addressbook_id, $interlocutorCache)) {
                $item->callerName = $item->getInterlocutorName();
                $interlocutorCache[$item->caller_addressbook_id] = $item->callerName;
            } else {
                $item->callerName = $interlocutorCache[$item->caller_addressbook_id];
            }
        }
    }

    protected function faxMenuIsAllowed($user)
    {
        if (PhonalisaLicenseManager::faxGUIEnabled() && AccessManager::userSendFaxAllowed($user)) {
            return true;
        }
        return false;
    }

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

    public function getRelativeTime($time)
    {
        return RelativeDateFormatter::timeAgoInWords($time, array('format' => 'd.m.Y'));
    }

    public function actionGetFaxPdfDocument($id = "")
    {
        if ($id == "") {
            $id = $_GET['id'];
        }

        $data = "";
        $length = 0;

        $model = $this->loadModel($id);

        if (
                $model != null &&
                $model->getBinaryField('fax_content_pdf', $data, $length)
        ) {
            $this->renderPartial('_pdfFile', array("data" => $data));
        }
    }

    public function actionFaxPage($id = "", $page = "")
    {
        if ($id == "") {
            $id = $_GET['id'];
            $page = $_GET['page'];
        }

        $data = "";
        $length = 0;

        $model = $this->loadModel($id);

        if (
                $model != null &&
                $model->getBinaryField('fax_content_png_' . $page, $data, $length)
        ) {
            $this->renderPartial('_imagePng', array("data" => $data));
        }
    }

    public function actionRateUcItem()
    {
        $model = UCItem::model()->findByPk($_POST['itemId']);

        $rating = $_POST['rating'];

        if ($rating > 0 && $rating < 6) {
            $model->rating = $rating;
            $model->save();
        }
    }

    public function actionDownloadFile($id)
    {
        $model = Voicemail::model()->findByPk($id);
        if (!$model) {
            $model = UCItem::model()->findByPk($id);
        }

        if ($model) {
            $length = 0;
            $data = "";
            $binaryField = "data";
            if (get_class($model) == 'UCItem') { // change field to record_data, which is used in UCItem
                $binaryField = "record_data";
            }
            $model->getBinaryField($binaryField, $data, $length);
            $this->renderPartial('_downloadFile', array('data' => $data, 'type' => $_GET['type']));
        } else {
            throw new CHttpException(400, 'UCItem not found');
        }
    }

    public function actionGetVoicemailFile($id)
    {
        $binaryField = "data";
        $model = Voicemail::model()->findByPk($id);
        if ($model == null) {
            $model = UCItem::model()->findByPk($id);
            $binaryField = "record_data";
        }
        if ($model == null) {
            throw new CHttpException(400, 'UCItem not found');
        }

        $length = 0;
        $data = "";

        $model->getBinaryField($binaryField, $data, $length);
        $this->renderPartial('_voicemailFile', array('data' => $data, 'length' => $length, 'type' => $_GET['type']));
    }

    public function actionGetFaxPdf($id)
    {
        $model = UCItem::model()->findByPk($id);
        if ($model != null) {
            $length = 0;
            $data = "";
            $fileName = 'Phonalisa_FAX_' . $model->timestamp . ".pdf";
            $model->getBinaryField("fax_content_pdf", $data, $length);
            $this->renderPartial('_faxPdf', array('fileName' => $fileName, 'data' => $data));
        } else {
            throw new CHttpException(400, 'UCItem not found');
        }
    }

    public function actionCreateFax()
    {
        $model = new UCItem('sendFax');
        $this->performAjaxValidation($model);

        if (isset($_POST['UCItem'])) {

            if (isset($_POST['UCItem']['fax_header'])) {
                $header = $_POST['UCItem']['fax_header'];
                $user = app()->user->realUserInstance;

                $headerExplode = explode('_', $header);

                if ($headerExplode[0] == 'user') {
                    $model->fax_header_text = $user->fax_header_text;
                    $model->fax_header_number = $user->fax_header_number;
                } elseif ($headerExplode[0] == 'group') {
                    $group = Groups::model()->findByPk($headerExplode[1]);
                    $model->fax_header_text = $group->fax_header_text;
                    $model->fax_header_number = $group->fax_header_number;
                } elseif ($header == 'system') {
                    $model->fax_header_text = cfg('FAX_HEADER_TEXT');
                    $model->fax_header_number = cfg('FAX_HEADER_NUMBER');
                }
            }

            $date = new DateTime("now", new DateTimeZone('GMT'));
            $model->owner_id = Yii::app()->user->sudoUser;
            $model->typ = 'fax';
            $model->attributes = $_POST['UCItem'];
            $model->direction = 0; // outbound direction
            $model->timestamp = date_format($date, 'Y-m-d H:i:s');
            if ($model->save()) {
                Yii::app()->user->setFlash(
                        'success', '<strong data-translation-id="FAX_SEND_FROM_CONTACT_SUCCSESSFULY">'
                        . __("FAX_SEND_FROM_CONTACT_SUCCSESSFULY")
                        . '</strong>'
                );
                Yii::app()->end();
            }
        }

        $this->renderPartial('createFax', array('model' => $model), false, true);
        Yii::app()->end();
    }

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

    public function actionSetRead($id)
    {
        $model = $this->loadModel($id);
        $model->red = '1';
        echo json_encode($model->save());
    }
}
