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

use common\models\Language;
use common\modules\blog\models\Article;
use common\modules\blog\models\ArticleCategory;
use common\modules\blog\models\ArticleCategoryLang;
use common\modules\blog\models\ArticleCategoryMedia;
use common\modules\blog\models\ArticleLang;
use yii\data\ActiveDataProvider;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\UploadedFile;

class CategoryController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post']
                ]
            ]
        ];
    }

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

    public function actionCreate()
    {
        $category_langs = array();
        $category = new ArticleCategory();
        $default_lang = Language::getDefaultLang();
        $images = array();
        $images[$default_lang->language_id]['full'] = new ArticleCategoryMedia(['scenario' => ArticleCategoryMedia::SCENARIO_FULL]);
        $images[$default_lang->language_id]['preview'] = new ArticleCategoryMedia(['scenario' => ArticleCategoryMedia::SCENARIO_PREVIEW]);
        $images[0]['additional'] = new ArticleCategoryMedia(['scenario' => ArticleCategoryMedia::SCENARIO_ADDITIONAL]);
        $category->loadDefaultValues();
        $langs = Language::getActiveLanguages();
        $isValid = false;
        if(!empty(\Yii::$app->request->post())) {
            $isValid = true;
            $category->load(\Yii::$app->request->post());
            $isValid = $category->validate();
            foreach(\Yii::$app->request->post()['ArticleCategoryMedia'] as $lang => $value) {
                foreach($value as $type => $fields) {
                    $images[$lang][$type] = new ArticleCategoryMedia(['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()['ArticleCategoryLang'])) {
                $category_langs[$default_lang->language_id] = new ArticleCategoryLang();
                $isValid  = ArticleCategoryLang::validateMultiple($category_langs) && $isValid;
            } else {
                foreach(\Yii::$app->request->post()['ArticleCategoryLang'] as $index => $category_lang) {
                    $category_langs[$index] = new ArticleCategoryLang();
                }
                ArticleCategoryLang::loadMultiple($category_langs, \Yii::$app->request->post());
                $isValid = ArticleCategoryLang::validateMultiple($category_langs) && $isValid;
            }
        } else {
            $category_langs[$default_lang->language_id] = new ArticleCategoryLang();
        }
        if($isValid) {
            $category->save(false);
            $first = 1;
            foreach($images as $lang => $value) {
                foreach($value as $type => $fields) {
                    $images[$lang][$type]->upload($category->article_category_id);
                    if($first && $type != 'additional') {
                        $media_clone = clone $images[$lang][$type];
                        $media_clone->setIsNewRecord(true);
                        unset($media_clone->article_category_media_id);
                        $media_clone->language_id = 0;
                        $media_clone->upload($category->article_category_id);
                        unset($media_clone);
                        $first = 0;
                    }
                }
            }
            $first = 1;
            foreach($category_langs as $category_lang) {
                if($first) {
                    $category_lang_clone = clone $category_lang;
                    $category_lang_clone->language_id = 0;
                    $category_lang_clone->link('category', $category);
                    unset($category_lang_clone);
                }
                $category_lang->link('category', $category);
                $first = 0;
            }
            echo "ok";
            //$this->redirect('index');
        } else {
            return $this->render('create', [
                'category_langs' => $category_langs,
                'category' => $category,
                'langs' => $langs,
                'images' => $images
            ]);
        }
    }

    public function actionUpdate($id)
    {
        $category = ArticleCategory::findOne($id);
        $imagestack = $category->getArticleCategoryMedia()->all();
        $images = [];
        $images[0]['additional'][0] = new ArticleCategoryMedia(['scenario' => ArticleCategoryMedia::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_category_media_id] = $image;
                $images[$image->language_id][$image->type][$image->article_category_media_id]->scenario = $image->type;
            }
        }
        foreach($images as $lang => $value) {
            $images[$lang]['additional'][0] = new ArticleCategoryMedia(['scenario' => ArticleCategoryMedia::SCENARIO_ADDITIONAL]);
        }
        $category_langs = $category->getArticleCategoryLangs()->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;
            $category->load(\Yii::$app->request->post());
            $isValid = $category->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()['ArticleCategoryMedia'] as $lang => $value) {
                foreach($value as $type => $fields) {
                    if(!in_array($type, ['full', 'preview'])) continue;
                    $images[$lang][$type] = new ArticleCategoryMedia(['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()['ArticleCategoryLang'])) {
                $isValid  = ArticleCategoryLang::validateMultiple($category_langs) && $isValid;
            } else {
                foreach(\Yii::$app->request->post()['ArticleCategoryLang'] as $index => $category_lang) {
                    if(!array_key_exists($index, $category_langs)) {
                        $category_langs[$index] = new ArticleCategoryLang();
                        $category_langs[$index]->article_category_id = $category->article_category_id;
                    }
                }
                ArticleCategoryLang::loadMultiple($category_langs, \Yii::$app->request->post());
                $isValid = ArticleCategoryLang::validateMultiple($category_langs) && $isValid;
            }
        }
        if($isValid) {
            $category->save(false);
            foreach($images as $lang => $value) {
                foreach($value as $type => $fields) {
                    if($type == 'additional') {
                        $images[$lang][$type][0]->upload($category->article_category_id);
                    } else {
                        if(!empty($images[$lang][$type]->imageFile)) {
                            $images[$lang][$type]->replace($category->article_category_id);
                        }
                    }
                }
            }
            foreach($category_langs as $category_lang) {
                $category_lang->save(false);
            }
            echo "ok";
            //$this->redirect('index');
        } else {
            return $this->render('update', [
                'category_langs' => $category_langs,
                'category' => $category,
                'langs' => $langs,
                'images' => $images
            ]);
        }
    }

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

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