<?php

class MessageController extends RController {

    public function filters() {
        return array(
            'rights',
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

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

    public function actionQuickUpdate() {
        $es = new EditableSaver('Message');
        $es->update();
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate($source_id) {
        $sourceMessage = $this->loadSourceModel($source_id);
        $model = new Message;
        $model->id = $source_id;
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if (isset($_POST['Message'])) {
            $model->attributes = $_POST['Message'];
            if ($model->save()) {
                $this->redirect(array('admin'));
            }
        }
        $this->render('create', array(
            'model' => $model,
            'sourceMessage' => $sourceMessage,
        ));
    }

    public function actionCreateLanguage() {
        if (isset($_POST['language']) && strlen(trim($_POST['language']))) {
            $langauge = trim($_POST['language']);
            if (in_array($langauge, Yii::app()->locale->getLocaleIDs())) {
                $sourceMessages = SourceMessage::model()->findAll();
                if ($sourceMessages) {
                    $sourceMessages = CHtml::listData($sourceMessages, 'id', 'message');
                    $messages = Message::model()->findAllByAttributes(array('language' => $langauge));
                    if ($messages) {
                        foreach ($messages as $message) {
                            unset($sourceMessages[$message->id]);
                        }
                    }
                    

                    foreach ($sourceMessages as $key => $value) {

                        $message = new Message;
                        $message->executeAfterSave = false;
                        $message->id = $key;

                        $message->translation = $value;

                        $message->language = $langauge;
                        if (!$message->save()) {
                            echo '<xmp dir="ltr">', var_dump($message->getErrors()), '</xmp>';
                        }
                    }

                    $this->redirect('admin', array('Message[language]' => $langauge));
                }
            }
        }
        $languages = array();
        $this->render('createLanguage', array(
            'languages' => $languages,
        ));
    }

    /**
     * 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, $language) {
        $sourceMessage = $this->loadSourceModel($id);
        $model = $this->loadModel($id, $language);
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if (isset($_POST['Message'])) {
            $model->attributes = $_POST['Message'];
            if ($model->save()) {
                $this->redirect(array('admin'));
            }
        }
        $this->render('update', array(
            'model' => $model,
            'sourceMessage' => $sourceMessage,
        ));
    }

    /**
     * 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, $language) {
        $this->loadModel($id, $language)->delete();
        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax'])) {
            Yii::app()->user->setFlash('alert-success', Yii::t('admin', 'Item has been successfully deleted.'));
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Message');
        $this->render('admin', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Message('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Message']))
            $model->attributes = $_GET['Message'];
        $this->render('admin', 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 $id the ID of the model to be loaded
     * @return Message the loaded model
     * @throws CHttpException
     */
    public function loadModel($id, $language) {
        $model = Message::model()->findByAttributes(array('id' => $id, 'language' => $language));
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

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

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

}
