<?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'.
     */
    // Disable custom layout
    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',
                'actions' => array('priceList', 'create', 'update', 'delete', 'generateFinalInvoice'),
                'expression' => $this->userIsSystemAdmin(),
            ),
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index'),
                //'users'=>array('@')
                'expression' => AccessManager::checkSessionPermission($this->module->id),
            ),
            array('deny',
                'users' => array('*'),
            )
        );
    }

    /**
     * ::::TRANSLATION TAGS::::
     * PHONALISA_INVOICE
     * PHONALISA_INVOICE_FOR_EXTENSION
     * INVOICE_HEADER_DATE
     * INVOICE_HEADER_TARGET
     * INVOICE_HEADER_DURATION
     * INVOICE_HEADER_PRICE
     * INVOICE_HEADER_PRICE_PER_MINUTE
     * INVOICE_PRICE_SUM
     * INVOICE_PRICE_VAT
     * INVOICE_TOTAL_PRICE
     * INVOICE_MONEY_ON_ACCOUNT
     */
    public function actionGenerateFinalInvoice($id)
    {
        $user = User::model()->findByPk($id);
        if ($user == null) {
            throw new CHttpException(404, 'The requested page does not exist.');
        }
        $attributes = array();
        $attributes["owner_id"] = $id;
        $attributes["direction"] = '0';
        $attributes["typ"] = 'call';
        $attributes["state"] = '8';
        $attributes["to_external"] = "1";
        $ucItems = UCItem::model()->findAllByAttributes($attributes, 1000);
        $generator = new InvoiceGenerator();

        $formatedDate = PhonalisaDate::changeRFC2822EnglishToUserLanguage();

        $generator->init(
                __("PHONALISA_INVOICE"),
                __("PHONALISA_INVOICE_FOR_EXTENSION")
                . " $user->extension - $formatedDate"
        );
        $accountBalance = $this->formatAccountBalance($user->accountBalance);
        $generator->generatePrepaidInvoice($ucItems, $accountBalance);

        foreach ($ucItems as $ucItem) {
            $ucItem->delete();
        }

        $user->accountBalance = "";
        $user->save();
    }

    protected function formatAccountBalance($accountBalance)
    {
        if (strlen($accountBalance) <= 3) {
            $accountBalance.= '0';
        } 
        return $accountBalance;
    }

    /**
     * Manages all models.
     */
    public function actionPriceList()
    {
        $model = new PriceTag();
        $this->render('priceList', array('model' => $model));
    }

    public function loadModel($id)
    {
        $model = PriceTag::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    public function actionUpdate($id)
    {
        $model = $this->loadModel($id);
        $this->performAjaxValidation($model);
        if (isset($_POST['PriceTag'])) {
            $model->attributes = $_POST['PriceTag'];
            if (!$model->save()) {
                // throw exeption ... FIXME ? 
            }
        }
        $this->renderPartialWithContextHelp('_form', array('model' => $model), false, true);
    }

    public function actionCreate()
    {
        $model = new PriceTag();
        $this->performAjaxValidation($model);
        if (isset($_POST['PriceTag'])) {

            $model->attributes = $_POST['PriceTag'];
            if (!$model->save()) {
                // throw exeption ... FIXME ? 
            }
        }
        $this->renderPartialWithContextHelp('_form', array('model' => $model), false, true);
    }

    /**
     * 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.');
        }
    }

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

    public function actionIndex()
    {
        if (isset($_POST['User'])) {
            foreach ($_POST['User'] as $id => $data) {
                $user = User::model()->findByPk($id);
                if ($user != null && isset($data['accountBalance'])) {
                    $user->accountBalance = $data['accountBalance'];
                    $user->save();
                }
            }
            Yii::app()->user->setFlash('success', __('CHANGES_SAVED_SUCCSESSFULLY'));
        }

        $dataProvider = new CArrayDataProvider($this->getBillingUsers(), array(
            'keyField' => 'id'
        ));

        $isSystemAdmin = $this->userIsSystemAdmin();

        $this->render('index', array(
            'isSystemAdmin' => $isSystemAdmin,
            'model' => User::model(),
            'dataProvider' => $dataProvider
        ));
    }

    public function userIsSystemAdmin()
    {
        $user = User::getCurrentRealUser();
        if (!$user) {
            app()->user->logout();
            app()->user->loginRequired();
        }
        return $user->isSystemAdmin;
    }

    private function getBillingUsers()
    {
        $users = array();
        $groups = $this->getBillingGroups();
        foreach ($groups as $group) {
            $users = array_merge($users, $group->getUsers());
        }
        return $users;
    }

    private function getBillingGroups()
    {
        $childGroups = array();
        $parentGroups = Groups::model()->findAllByAttributes(array('accountingEnabled' => "1"));

        foreach ($parentGroups as $parentGroup) {
            $childGroups = array_merge($childGroups, $parentGroup->getChildren(true));
        }

        $allGroups = array_merge($childGroups, $parentGroups);

        return array_unique($allGroups);
    }

    public function renderPrice($data)
    {
        return '<i class="icon-euro"></i> ' . $data->price;
    }

    public function getBalanceColumn($model)
    {
        return $this->renderPartial('balanceInput', array('model' => $model), false, false);
    }

    public function renderBill($data, $row, $column)
    {
        $url = url('adminBilling/default/generateFinalInvoice', array('id' => $data->id));
        $link = l("<i class='icon-file-text' style='color:black'>", $url, array(
            'target'=>"_blank",
            'class' => 'getBill',
            'rel' => 'tooltip',
            'title' => __('BILLING_GET_BILL_PDF'),
            'data-translation-id' => 'BILLING_GET_BILL_PDF',
            'data-translation-traget' => 'GET_BILL_LINK',
                )
        );
        return $link;
    }
}
