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

    public function actionCreate()
    {
        $model = new Licence();
        $this->performAjaxValidation($model);

        if (isset($_POST['Licence'])) {
            $file = CUploadedFile::getInstance($model, 'data');
            if ($file) {
                $status = PhonalisaLicenseManager::storeLicense($file->tempName);
                if ($status !== TRUE) {
                    $model->data = null;
                    $model->addError('data', $status);

                    foreach ($model->getErrors() as $attribute => $errors) {
                        $result[CHtml::activeId($model, $attribute)] = $errors;
                    }

                    echo json_encode(array('errors' => $result));
                    Yii::app()->end();
                }
            } else {
                $model->addError('data', 'darf nicht leer sein');
            }
            Yii::app()->end();
        }
        $this->renderPartial('_form', array('model' => $model), false, true);
    }

    public function actionActivate()
    {
        $model = new Licence('update');

        if (!empty($_REQUEST['licenseTypeSelector'])) {
            $typeSelector = $_REQUEST['licenseTypeSelector'];
            if ($typeSelector === 'selectActivation') {
                $model->scenario = 'activate';
            } else if ($typeSelector === 'selectUpgrade') {
                $model->scenario = 'upgradeLicense';
            }
        }

        $this->performAjaxValidation($model);
        $model = $this->autoFillLicenseForm($model);
        $licenseIsValid = PhonalisaLicenseManager::licenseIsValid();

        if (!$licenseIsValid || $model->scenario === 'update') {
            $model->upgrade_code = PhonalisaLicenseManager::DEFAULT_LICENSE_KEY;
        }

        if (isset($_POST['Licence'])) {
            $postAttributes = $_POST['Licence'];
            foreach ($postAttributes as $postKey => $postAttribute) {
                if ($postAttribute === PhonalisaLicenseManager::DEFAULT_LICENSE_KEY) {
                    $postAttributes[$postKey] = '';
                }
            }

            $model->attributes = $postAttributes;
            $model->system_id = PhonalisaLicenseManager::getSystemID();
            $result = $model->activateLicense();
            if ($result !== true) {
                app()->user->setFlash('error', "<strong>Error " . $result['errorCode'] . ": </strong>" . $result['errorMessage']);
                throw new CHttpException($result["errorCode"], $result["errorMessage"]);
            }
        }
        $this->renderPartial('activate_form', array('model' => $model, 'licenseIsValid' => $licenseIsValid), false, true);
    }

    protected function autoFillLicenseForm($model)
    {
        $licenseInfo = PhonalisaLicenseManager::getLicenseInfo();
        if (PhonalisaLicenseManager::licenseIsValid()) {
            $model->customer_company = (string) @$licenseInfo['company'];
            $model->customer_adr_zip = (string) @$licenseInfo['postcode'];
            $model->customer_email = (string) @$licenseInfo['email'];
            $model->customer_adr_country = (string) @$licenseInfo['country'];
            $model->customer_adr_region = (string) @$licenseInfo['city'];

            $person = (string) trim(@$licenseInfo['person']);
            $nameArray = explode(' ', $person);
            $model->customer_lastname = end($nameArray);
            $model->customer_firstname = trim(str_replace(end($nameArray), '', $person));

            $street = (string) trim(@$licenseInfo['street']);
            $addressArray = explode(' ', $street);
            foreach ($addressArray as $address) {
                if (is_numeric(substr($address, 0, 1))) {
                    $addressStreet = trim(substr($street, 0, strpos($street, $address)));
                    $model->customer_adr_street_number = trim(str_replace($addressStreet, '', $street));
                    $model->customer_adr_street = $addressStreet;
                    break;
                }
            }
        }
        return $model;
    }

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

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $model = new Licence();
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Licence'])) {
            $model->attributes = $_GET['Licence'];
        }
        $this->render('index', array('model' => $model));
    }

    public function actionThirdParty()
    {
        $content = TermsOfUseProvider::text();
        $this->render('thirdParty', array('content' => $content, 'brand' => 'LICENSE_THIRD_PARTY_LICENSES'));
    }

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

    public function actionShowPrivacy()
    {
        $content = PrivacyProvider::text();
        $this->render('thirdParty', array('content' => $content, 'brand' => 'PRIVACY_POLICY_LINK'));
    }

    public function renderGridKeys($data)
    {
        $translationKey = 'LICENSE_INFO_' . strtoupper($data['name']);
        $translation = __($translationKey);
        $html = "<b data-translation-id='$translationKey'>$translation</b>";

        return $html;
    }

    public function renderGridValues($data)
    {
        if ($data['name'] == 'valid' || "activated" == $data['name']) {
            if ((int) $data['value'] == 0) {
                return __("LICENSE_MODEL_UNLIMITED_VALID");
            }
            return $this->getReadableDate($data['value']);
        }
        return $data['value'];
    }

    public function getReadableDate($data)
    {
        $date = PhonalisaDate::userDate($data);
        if ($date == NULL) {
            $date = PhonalisaDate::userDate($data . ' 00:00:00');
        }
        return $date;
    }

    private function getReadableBool($data)
    {
        if ($data['value'] == '1') {
            return __("LICENSE_MODEL_VALUE_ACTIVE");
        } else {
            return __("LICENSE_INFO_VALUE_INACTIVE");
        }
    }

    private function getReadableInt($data)
    {
        if ($data['value'] == '-1') {
            return __("LICENSE_MODEL_VALUE_INFINITE");
        } else {
            return $data['value'];
        }
    }

    public function renderGridUpgradeValue($data)
    {
        if (in_array($data['name'], Licence::UPGRADED_LICENSE_BOOLS)) {
            return $this->getReadableBool($data);
        } else if (in_array($data['name'], Licence::UPGRADED_LICENSE_INTS)) {
            return $this->getReadableInt($data);
        } else if (in_array($data['name'], Licence::UPGRADED_LICENSE_DATES)) {
            return $this->getReadableDate($data['value']);
        }
    }
}
