<?php
namespace common\modules\blog\controllers;

use common\components\rules\CommentRule;
use common\components\rules\DeleteRule;
use common\components\rules\UpdateRule;
use common\components\rules\ViewRule;
use common\models\Language;
use common\modules\blog\models\Article;
use common\modules\blog\models\ArticleLang;
use common\modules\blog\models\ArticleMedia;
use common\modules\blog\models\ArticleToCategory;
use yii\data\ActiveDataProvider;
use yii\rbac\DbManager;
use yii\web\Controller;
use yii\web\UploadedFile;

class ArticleController extends Controller
{

	public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Article::find(),
            'pagination' => [
                'pageSize' => 1,
            ],
        ]);
        return $this->render('index', ['dataProvider' => $dataProvider]);
    }

    public function actionCreate()
    {
        $article_langs = array();
        $article = new Article();
        $default_lang = Language::getDefaultLang();
        $images = array();
        $images[$default_lang->language_id]['full'] = new ArticleMedia(['scenario' => ArticleMedia::SCENARIO_FULL]);
        $images[$default_lang->language_id]['preview'] = new ArticleMedia(['scenario' => ArticleMedia::SCENARIO_PREVIEW]);
        $images[0]['additional'] = new ArticleMedia(['scenario' => ArticleMedia::SCENARIO_ADDITIONAL]);
        $article->loadDefaultValues();
        $langs = Language::getActiveLanguages();
        $isValid = false;
        if(!empty(\Yii::$app->request->post())) {
            $isValid = true;
            $article->load(\Yii::$app->request->post());
            $article->user_id = \Yii::$app->user->getId();
            $isValid = $article->validate();
            foreach(\Yii::$app->request->post()['ArticleMedia'] as $lang => $value) {
                foreach($value as $type => $fields) {
                    $images[$lang][$type] = new ArticleMedia(['scenario' => $type]);
                    $images[$lang][$type]->type = $type;
                    $images[$lang][$type]->language_id = $lang;
                    $images[$lang][$type]->imageFile = UploadedFile::getInstance($images[$lang][$type], "[{$lang}][{$type}]imageFile");
                    $isValid = $images[$lang][$type]->validate(['imageFile']) && $isValid;
                }
            }
            $images[0]['additional']->language_id = 0;
            $images[0]['additional']->type = 'additional';
            $images[0]['additional']->imageFile = UploadedFile::getInstances($images[0]['additional'], "[0][additional]imageFile");
            if(empty(\Yii::$app->request->post()['ArticleLang'])) {
                $article_langs[$default_lang->language_id] = new ArticleLang();
                $isValid  = ArticleLang::validateMultiple($article_langs) && $isValid;
            } else {
                foreach(\Yii::$app->request->post()['ArticleLang'] as $index => $article_lang) {
                    $article_langs[$index] = new ArticleLang();
                }
                ArticleLang::loadMultiple($article_langs, \Yii::$app->request->post());
                $isValid = ArticleLang::validateMultiple($article_langs) && $isValid;
            }
        } else {
            $article_langs[$default_lang->language_id] = new ArticleLang();
        }
        if($isValid) {
            $article->save(false);
            $article_categories = \Yii::$app->request->post('Article')['articleCategoriesArray'];
            if(!empty($article_categories)) {
                foreach($article_categories as $article_category) {
                    $articletocategory[$article_category] = new ArticleToCategory();
                    $articletocategory[$article_category]->article_category_id = $article_category;
                    $articletocategory[$article_category]->link('article', $article);
                }
            }
            $first = 1;
            foreach($images as $lang => $value) {
                foreach($value as $type => $fields) {
                    $images[$lang][$type]->upload($article->article_id);
                    if($first && $type != 'additional') {
                        $media_clone = clone $images[$lang][$type];
                        $media_clone->setIsNewRecord(true);
                        unset($media_clone->article_media_id);
                        $media_clone->language_id = 0;
                        $media_clone->upload($article->article_id);
                        unset($media_clone);
                        $first = 0;
                    }
                }
            }
            $first = 1;
            foreach($article_langs as $article_lang) {
                if($first) {
                    $article_lang_clone = clone $article_lang;
                    $article_lang_clone->language_id = 0;
                    $article_lang_clone->link('article', $article);
                    unset($article_lang_clone);
                }
                $article_lang->link('article', $article);
                $first = 0;
            }
            echo "ok";
            //$this->redirect('index');
        } else {
            return $this->render('create', [
                'article_langs' => $article_langs,
                'article' => $article,
                'langs' => $langs,
                'images' => $images
            ]);
        }
    }

    public function actionUpdate($id)
    {
        $article = Article::findOne($id);
        $imagestack = $article->getArticleMedia()->all();
        $images = [];
        $images[0]['additional'][0] = new ArticleMedia(['scenario' => ArticleMedia::SCENARIO_ADDITIONAL]);
        $images[0]['additional'][0]->type = 'additional';
        $images[0]['additional'][0]->language_id = 0;
        foreach($imagestack as $image) {
            if(in_array($image->type, ['full', 'preview'])) {
                $images[$image->language_id][$image->type] = $image;
                $images[$image->language_id][$image->type]->scenario = $image->type;
            } else {
                $images[$image->language_id][$image->type][$image->article_media_id] = $image;
                $images[$image->language_id][$image->type][$image->article_media_id]->scenario = $image->type;
            }
        }
        foreach($images as $lang => $value) {
            $images[$lang]['additional'][0] = new ArticleMedia(['scenario' => ArticleMedia::SCENARIO_ADDITIONAL]);
        }
        $article_langs = $article->getArticleLangs()->where(['>=', 'language_id', '1'])->indexBy('language_id')->all();
        $langs = Language::getActiveLanguages();
        $default_lang = Language::getDefaultLang();
        $isValid = false;
        if(!empty(\Yii::$app->request->post())) {
            $isValid = true;
            $article->load(\Yii::$app->request->post());
            ArticleToCategory::deleteAll(['article_id' => $article->article_id]);
            $article_categories = \Yii::$app->request->post('Article')['articleCategoriesArray'];
            if(!empty($article_categories)) {
                foreach($article_categories as $article_category) {
                    $articletocategory[$article_category] = new ArticleToCategory();
                    $articletocategory[$article_category]->article_category_id = $article_category;
                    $articletocategory[$article_category]->link('article', $article);
                }
            }
            $isValid = $article->validate();
            $images[0]['additional'][0]->type = 'additional';
            $images[0]['additional'][0]->language_id = 0;
            $images[0]['additional'][0]->imageFile = UploadedFile::getInstances($images[0]['additional'][0], "[0][additional]imageFile");
            $isValid = $images[0]['additional'][0]->validate(['imageFile']) && $isValid;
            foreach(\Yii::$app->request->post()['ArticleMedia'] as $lang => $value) {
                foreach($value as $type => $fields) {
                    if(!in_array($type, ['full', 'preview'])) continue;
                    $images[$lang][$type] = new ArticleMedia(['scenario' => $type]);
                    $images[$lang][$type]->language_id = $lang;
                    $images[$lang][$type]->type = $type;
                    $images[$lang][$type]->imageFile = UploadedFile::getInstance($images[$lang][$type], "[{$lang}][{$type}]imageFile");
                    $isValid = $images[$lang][$type]->validate(['imageFile']) && $isValid;
                }
            }
            if(empty(\Yii::$app->request->post()['ArticleLang'])) {
                $isValid  = ArticleLang::validateMultiple($article_langs) && $isValid;
            } else {
                foreach(\Yii::$app->request->post()['ArticleLang'] as $index => $article_lang) {
                    if (!array_key_exists($index, $article_langs)) {
                        $article_langs[$index] = new ArticleLang();
                        $article_langs[$index]->article_id = $article->article_id;
                    }
                }
                ArticleLang::loadMultiple($article_langs, \Yii::$app->request->post());
                $isValid = ArticleLang::validateMultiple($article_langs) && $isValid;
            }
        }
        if($isValid) {
            $article->save(false);
            foreach($images as $lang => $value) {
                foreach($value as $type => $fields) {
                    if($type == 'additional') {
                        $images[$lang][$type][0]->upload($article->id);
                    } else {
                        if(!empty($images[$lang][$type]->imageFile)) {
                            $images[$lang][$type]->replace($article->article_id);
                        }
                    }
                }
            }
            foreach($article_langs as $article_lang) {
                $article_lang->save(false);
            }
            echo "ok";
            //$this->redirect('index');
        } else {
            return $this->render('update', [
                'article_langs' => $article_langs,
                'article' => $article,
                'langs' => $langs,
                'images' => $images
            ]);
        }
    }

    public function actionDelete($id)
    {
        $this->findModel($id)->delete();
        return $this->redirect(['index']);
    }

    protected function findModel($id)
    {
        if (($model = Article::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
