<?php
/** Usage example
 *   class PageController extends AdminController
 *   {
 *       public function actions()
 *       {
 *           return array(
 *               'index' => array(
 *                   'class' => 'StaticDataEditor',
 *
 *                   'submitLabel' => 'Сохранить',
 *                   'section' => 'root',
 *                   'key' => 'index',
 *                   'view' => 'static_editor',
 *                   'model' => array(
 *                       'schema' => array(
 *                           'item1' => array(
 *                               'label' => 'Item #1',
 *                               'default' => null,
 *                           ),
 *                       ),
 *                       'rules' => array(),
 *                   ),
 *                   'form' => array(
 *                       array(
 *                           'type' => 'simpleInput',
 *                           'name' => 'textField',
 *                           'attribute' => 'item1',
 *                           'options' => array(),
 *                       ),
 *                   ),
 *                   'i18nModel' => array(
 *                       'schema' => array(
 *                           'item1' => array(
 *                               'label' => 'Item #1',
 *                               'default' => null,
 *                           ),
 *                       ),
 *                       'rules' => array(),
 *                   ),
 *                   'i18nForm' => array(
 *                       array(
 *                           'type' => 'simpleInput',
 *                           'name' => 'textField',
 *                           'attribute' => 'item1',
 *                           'options' => array(),
 *                       ),
 *                   ),
 *               ),
 *           );
 *       }
 *   }
 */
class StaticDataEditor extends CAction
{
    public $section;
    public $key;

    public $model;
    public $form;

    public $i18nModel;
    public $i18nForm;

    public $redirectUrl = null;
    public $view = null;
    public $submitLabel = 'Save';

    public function init()
    {

    }

    public function run()
    {
        /**
         * @var StaticData $model
         */
        $model = StaticData::model()->findByPk(array(
                'section' => $this->section,
                'key' => $this->key)
        );

        /**
         * @var StaticDataI18n[] $i18nModels
         */
        $criteria = new CDbCriteria();
        $criteria->compare('`section`', $this->section);
        $criteria->compare('`key`', $this->key);

        $criteria->index = 'lang';

        $i18nModels = StaticDataI18n::model()->findAll($criteria);

        if ($model === null) {
            $model = new StaticData();
            $model->key = $this->key;
            $model->section = $this->section;
            $model->setDataAttributes(array());
        }
        foreach (Yii::app()->params['languages'] as $lang) {
            if (!isset($i18nModels[$lang])) {
                $i18nModel = new StaticDataI18n();
                $i18nModel->key = $this->key;
                $i18nModel->section = $this->section;
                $i18nModel->lang = $lang;
                $i18nModel->setDataAttributes(array());
                $i18nModels[$lang] = $i18nModel;
            }
        }

        $dataModel = new DataModel($this->model);
        $dataModel->setAttributes($model->getDataAttributes(), false);
        /** @var $i18nDataModels DataModelI18n[] */
        $i18nDataModels = array();
        foreach (Yii::app()->params['languages'] as $lang) {
            $i18nDataModels[$lang] = new DataModelI18n($this->i18nModel);
            $i18nDataModels[$lang]->setAttributes($i18nModels[$lang]->getDataAttributes(), false);
        }
        if (isset($_POST['DataModel']) || isset($_POST['DataModelI18n'])) {
            if (isset($_POST['DataModel']))
                $dataModel->setAttributes($_POST['DataModel']);

            if (isset($_POST['DataModelI18n'])) {
                foreach ($_POST['DataModelI18n'] as $lang => $post) {
                    if (isset($i18nDataModels[$lang]))
                        $i18nDataModels[$lang]->setAttributes($post);
                }
            }
            $i18nValidation = true;
            foreach ($i18nDataModels as $i18nDataModel) {
                $i18nValidation = $i18nValidation && $i18nDataModel->validate();
            }

            if ($dataModel->validate() && $i18nValidation) {
                $model->setDataAttributes($dataModel->getAttributes());
                $model->save(false);
                foreach (Yii::app()->params['languages'] as $lang) {
                    $i18nModels[$lang]->setDataAttributes($i18nDataModels[$lang]->getAttributes());
                    $i18nModels[$lang]->save(false);
                }
                //redirect to index
                if (isset($this->redirectUrl)) {
                    $this->getController()->redirect($this->redirectUrl);
                }
            }

        }
        //render

        $content = $this->renderForm($dataModel, $i18nDataModels, true);
        if (isset($this->view)) {
            $this->getController()->render($this->view, array('content' => $content));
        } else {
            $this->getController()->renderText($content);
        }
    }

    /**
     * @param DataModel $dataModel
     * @param DataModelI18n[] $i18nDataModels
     * @param bool $processOutput
     * @return null|string
     */
    private function renderForm($dataModel, $i18nDataModels, $processOutput = false)
    {

        $out = null;
        if ($processOutput) {
            ob_start();
        }
        $form = $this->getController()->beginWidget('BHorizontalForm', array());

        $formConfig = array();
        if (!empty($this->form))
            $formConfig[] = array(
                'type' => 'widget',
                'class' => 'FormWidget',
                'config' => array(
                    'form' => $form,
                    'model' => $dataModel,
                    'config' => $this->form,
                ),
            );


        if (!empty($this->i18nForm)) {
            $tabs = array();
            foreach (Yii::app()->params['languages'] as $lang) {
                $tabs[] = array(
                    'label' => Yii::app()->params['languageNames'][$lang],
                    'className' => 'FormWidget',
                    'properties' => array(
                        'form' => $form,
                        'suffix' => $lang,
                        'model' => $i18nDataModels[$lang],
                        'config' => $this->i18nForm,
                    ),
                );
            }
            //CVarDumper::dump($tabs,10,true);
            $formConfig[] = array(
                'type' => 'widget',
                'class' => 'WidgetTabs',
                'config' => array(
                    'tabs' => $tabs,
                ),
            );
        }


        $this->getController()->widget('FormWidget', array(
            'form' => $form,
            'model' => $dataModel,
            'config' => $formConfig,
        ));

        echo '<div class="form-actions"><button type="submit" class="btn btn-large btn-primary">',
        $this->submitLabel,
        '</button></div>';
        if ($processOutput) {
            $out = ob_get_clean();
        }

        return $out;

    }
}