<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\helpers\json;
use app\models\Items;
use app\models\ItemsSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use app\models\MainCategories;
use app\models\SubCategories;
use app\models\ItemImages;
use app\models\ItemVariations;
use app\models\ItemVariationsSearch;

/**
 * ItemsController implements the CRUD actions for Items model.
 */
class ItemsController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => false,
                        'roles' => ['?'],
                    ],
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
                'denyCallback' => function ($rule, $action) {
                    Yii::$app->session->setFlash('unauthenticated', Yii::t('app', 'You are not authenticated, please login to access this page.'));
                    return $this->redirect(['admins/login']);
                }
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Items models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ItemsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $main_categories = MainCategories::find()->where(['status' => 'Active'])->all();
        $sub_categories = SubCategories::find()->where(['status' => 'Active'])->all();

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'main_categories' => $main_categories,
            'sub_categories' => $sub_categories,
        ]);
    }

    /**
     * Displays a single Items model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        $modelImages = ItemImages::find()->where(['item_id' => $id])->all();
        $item_variations = ItemVariations::find()->where(['item_id' => $id])->all();
        return $this->render('view', [
            'model' => $this->findModel($id),
            'modelImages' => $modelImages,
            'item_variations' => $item_variations,
        ]);
    }

    /**
     * Creates a new Items model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
   
    public function actionGetSubCategories()
    {
        $main_category_id = Yii::$app->request->post();
        $sub_categories = SubCategories::find()->where(['main_category_id' => $main_category_id['val']])->all();
        if ($sub_categories)
        {
            $sub_categories_options[] = "<option>" . Yii::t('app', 'Select Sub Category') . "</option>";
            foreach ($sub_categories as $sub_category) {
                if (Yii::$app->language == 'en') {
                    $sub_categories_options[] = "<option value='" . $sub_category->id . "'>" . $sub_category->english_name . "</option>";
                }
                else {
                    $sub_categories_options[] = "<option value='" . $sub_category->id . "'>" . $sub_category->arabic_name . "</option>";
                }
                
            };
        }
        else 
        {
            $sub_categories_options[] = "<option value=''>-</option>";
        }
        return json_encode($sub_categories_options);  
    }
    public function actionCreate()
    {
        $model = new Items();
        $images = new ItemImages();
        $item_vars = new ItemVariations();

        if ($model->load(Yii::$app->request->post()))
        {
            if($model->save())
            {
                $uploadedImages = UploadedFile::getInstances($images, 'image_path');
                $dir_name = 'items/' . $model->id . '/';
                if(!is_dir($dir_name))
                {
                    mkdir($dir_name, 0777, true);
                }
                foreach ($uploadedImages as $index => $image) {
                    $new_image = new ItemImages();
                    $new_image->image_path = $dir_name.rand(). $image->name;
                    $new_image->item_id = $model->id;
                    $new_image->sort_order = ($index + 1);
                    $new_image->save();
                    $image->saveAs($new_image->image_path);
                }
                if ($item_vars->load(Yii::$app->request->post()))
                {
                    $item_vars->item_id = $model->id;
                    $item_vars->save();
                    if (isset(Yii::$app->request->post()['Vars']))
                    {
                        $other_vars = Yii::$app->request->post()['Vars'];
                        foreach ($other_vars as $index => $var) {
                            $other_var = new ItemVariations();
                            $other_var->item_id = $model->id;
                            $other_var->arabic_description = $var['arabic_description'];
                            $other_var->english_description = $var['english_description'];
                            $other_var->arabic_details = $var['arabic_details'];
                            $other_var->english_details = $var['english_details'];
                            $other_var->price = $var['price'];
                            if (!$other_var->save()) {
                                $other_var->getErrors();
                            }
                        }
                    }
                }
                return $this->redirect(['view', 'id' => $model->id]);
            }
        }

        $main_categories = MainCategories::find()->all();

        return $this->render('create', [
            'model' => $model,
            'main_categories' => $main_categories,
            'images' => $images,
            'item_vars' => $item_vars,
        ]);
    }

    /**
     * Updates an existing Items model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */

    function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $item_vars = ItemVariations::find()->where(['item_id' => $id])->all();
        $vars_count = count($item_vars);
        $item_main_var = ItemVariations::find()->where(['item_id' => $id])->one();
        $other_vars = ItemVariations::find()->where(['item_id' => $id])->andWhere(['<>', 'id', $item_main_var->id])->all();

        if ($model->load(Yii::$app->request->post()))
        {
            if($model->save())
            {
                if ($item_main_var->load(Yii::$app->request->post()))
                {
                    ItemVariations::deleteAll(['item_id' => $id]);
                    $item_main_var = new ItemVariations();
                    $item_main_var->item_id = $model->id;
                    $item_main_var->arabic_description = Yii::$app->request->post()['ItemVariations']['arabic_description'];
                    $item_main_var->english_description = Yii::$app->request->post()['ItemVariations']['english_description'];
                    $item_main_var->arabic_details = Yii::$app->request->post()['ItemVariations']['arabic_details'];
                    $item_main_var->english_details = Yii::$app->request->post()['ItemVariations']['english_details'];
                    $item_main_var->price = Yii::$app->request->post()['ItemVariations']['price'];
                    $item_main_var->save();
                    if (isset(Yii::$app->request->post()['Vars']))
                    {
                        $other_vars = Yii::$app->request->post()['Vars'];
                        foreach ($other_vars as $index => $var) {
                            $other_var = new ItemVariations();
                            $other_var->item_id = $model->id;
                            $other_var->arabic_description = $var['arabic_description'];
                            $other_var->english_description = $var['english_description'];
                            $other_var->arabic_details = $var['arabic_details'];
                            $other_var->english_details = $var['english_details'];
                            $other_var->price = $var['price'];
                            if (!$other_var->save()) {
                                $other_var->getErrors();
                            }
                        }
                    }
                }
                return $this->redirect(['view', 'id' => $model->id]);
            }
        }

        $main_categories = MainCategories::find()->all();
        return $this->render('update', [
            'model' => $model,
            'main_categories' => $main_categories,
            'vars_count' => $vars_count,
            'item_main_var' => $item_main_var,
            'other_vars' => $other_vars,
        ]);
    }

    public function actionUpdateImages($id)
    {
        $modelImages = ItemImages::find()->where(['item_id' => $id])->orderBy(['sort_order' => SORT_ASC])->all();
        $image_count = count($modelImages);
        $item = Items::findOne($id);
        $images = new ItemImages();

        if ($images->load(Yii::$app->request->post()))
        {
            $uploadedImages = UploadedFile::getInstances($images, 'image_path');
            $dir_name = 'items/' . $id . '/';
            if(!is_dir($dir_name))
            {
                mkdir($dir_name, 0777, true);
            }
            foreach ($uploadedImages as $index => $image) {
                $new_image = new ItemImages();
                $new_image->image_path = $dir_name .rand(). $image->name;
                $new_image->item_id = $id;
                $new_image->sort_order = ($image_count + $index + 1);
                $new_image->save();
                $image->saveAs($new_image->image_path);
            }
            Yii::$app->session->setFlash('updated', Yii::t('app', 'Image updated successfuly'));
            return $this->redirect(Yii::$app->request->referrer);
        }

        return $this->render('update-images', [
            'images' => $images,
            'item' => $item,
            'modelImages' => $modelImages,
            'image_count' => $image_count, 
        ]);
    }

    public function actionDeleteImage($id)
    {
        $image = ItemImages::findOne($id)->delete();

        return $this->redirect(Yii::$app->request->referrer);
    }

    public function actionImagesOrder($id)
    {
        $modelImages = ItemImages::find()->where(['item_id' => $id])->orderBy(['sort_order' => SORT_ASC])->all();
        if (Yii::$app->request->post())
        {
            $new_sort_order = Yii::$app->request->post()['images_sort'];
            $new_sort_order = explode(',', $new_sort_order);
            foreach ($modelImages as $index => $image) {
                $image->sort_order = ((int)$new_sort_order[$index] + 1);
                $image->save();
            }
            Yii::$app->session->setFlash('updated', Yii::t('app', 'Images Order updated successfuly'));
            return $this->redirect(Yii::$app->request->referrer);
        }

        $item = Items::findOne($id);
        $images = [];
        foreach ($modelImages as $index => $image) {
            $images[] = ['content' => '<div class="grid-item"><img src="' . Yii::$app->request->baseUrl . '/' . $image->image_path .'" class="image-responsive" style="width:100px; height:100px"></div>'];
        }

        return $this->render('images-order', [
            'item' => $item,
            'images' => $images,
            'modelImages' => $modelImages,
        ]);
    }

    public function actionNewImagesOrder($images)
    {
        if (Yii::$app->request->post())
        {
            return var_dump($images);
        }
    }

    public function actionUpdateVariations()
    {
        $searchModel = new ItemVariationsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $main_categories = MainCategories::find()->where(['status' => 'Active'])->all();
        $sub_categories = SubCategories::find()->where(['status' => 'Active'])->all();
        
        return $this->render('update-variations', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
            'main_categories' => $main_categories,
            'sub_categories' => $sub_categories,
        ]);
    }

    public function actionEditPrice($id)
    {
        if (Yii::$app->request->isAjax){
            $data = Yii::$app->request->get()['ItemVariations']['price'];
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            if ($data)
            {
                $variation = ItemVariations::findOne($id);
                $variation->price = $data;
                if ($variation->save()) {
                    return ['output' => '', 'message' => ''];
                }
                else {
                    return ['output' => '', 'message' => Yii::t('app', 'Invalid Value')];
                }
            }
            else
            {
                return ['output' => '', 'message' => 'failed'];
            }
        }
    }

    public function actionChangeStatus($id)
    {
        if (Yii::$app->request->isAjax){
            $status = Yii::$app->request->get()['Items']['status'];
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            if ($status)
            {
                $item = Items::findOne($id);
                $item->status = $status;
                if ($item->save()) {
                    return ['output' => '', 'message' => ''];
                }
                else {
                    return var_dump($item->getErrors());
                }
            }
            else
            {
                return ['output' => '', 'message' => 'failed'];
            }
        }
    }

    public function actionSelectSubCategory($id)
    {
        if (Yii::$app->request->isAjax){
            $sub_category_id = Yii::$app->request->get()['Items']['sub_category_id'];
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            if ($sub_category_id)
            {
                $item = Items::findOne($id);
                $item->sub_category_id = $sub_category_id;
                $item->status = 'Active';
                if ($item->save()) {
                    return ['output' => '', 'message' => ''];
                }
                else {
                    return var_dump($item->getErrors());
                }
            }
            else
            {
                return ['output' => '', 'message' => 'failed'];
            }
        }
    }

    /**
     * Deletes an existing Items model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        $model_images = $model->itemImages;
        foreach ($model_images as $key => $image) {
            $image->delete();
        }
        $model_vars = $model->itemVariations;
        foreach ($model_vars as $key => $var) {
            $var->delete();
        }
        $model->delete();

        return $this->redirect(['index']);
    }

    public function actionCategorize()
    {
        $searchModel = new ItemsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->query->andWhere(['status'=> 'Uncategorized']);

        return $this->render('categorize', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Finds the Items model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Items the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Items::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
    }
	

		
}
