<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use app\models\SubCategories;
use app\models\SubCategoriesSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use app\models\SpecialItems;
use app\models\Items;

/**
 * SubCategoriesController implements the CRUD actions for SubCategories model.
 */
class SubCategoriesController 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', 'You are not authenticated, please login to access this page.');
                    return $this->redirect(['admins/login']);
                }
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all SubCategories models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new SubCategoriesSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

    /**
     * Displays a single SubCategories model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new SubCategories model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate($main_cate_id)
    {
        $model = new SubCategories();

        if ($model->load(Yii::$app->request->post())) {
            $uplodadedImage = UploadedFile::getInstance($model, 'image_path');
            if ($uplodadedImage)
            {
                $dir_name = 'sub-categories-images/';
                if(!is_dir($dir_name)){
                    mkdir($dir_name, 0777, true);
                }
                $model->image_path = $dir_name.rand() . $uplodadedImage->name;
            }
            
            $main_category_items = Items::find()->where(['main_category_id' => $main_cate_id])->andWhere(['sub_category_id' => null])->all();
            foreach ($main_category_items as $key => $item) {
                $item->status = "Uncategorized";
                $item->save();
            }
            $model->main_category_id = $main_cate_id;
            if ($model->save()) 
            {
                if ($model->image_path != null)
                {
                   $uplodadedImage->saveAs($model->image_path); 
                }
                return $this->redirect(['main-categories/view', 'id' => $main_cate_id]);
            }
            return var_dump($model->getErrors());
        }

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

    /**
     * Updates an existing SubCategories 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
     */

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $old_image = $model->image_path;
        if ($model->load(Yii::$app->request->post())) {
            $uplodadedImage = UploadedFile::getInstance($model, 'image_path');
            if ($uplodadedImage)
            {
                $dir_name = 'sub-categories-images/';
                if(!is_dir($dir_name)){
                    mkdir($dir_name, 0777, true);
                }
                $model->image_path = $dir_name.rand() . $uplodadedImage->name;
                if ($model->save()) {
                    if ($model->image_path != null) {
                        $uplodadedImage->saveAs($model->image_path); 
                    }
                    return $this->redirect(['view', 'id' => $model->id]);
                }
                return var_dump($model->getErrors());
            }
            else {
                $model->image_path = $old_image;
                if ($model->save()) {
                    return $this->redirect(['view', 'id' => $model->id]);
                }
                return var_dump($model->getErrors());
            }
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    public function actionSpecialItem($id)
    {
        $model = SpecialItems::find()->where(['sub_category_id' => $id])->one();
        $items = Items::find()->where(['sub_category_id' => $id])->andWhere(['status' => 'Active'])->all();
        
        if ($model) {
            if ($model->load(Yii::$app->request->post())) {
                if (!$model->item_id){
                    SpecialItems::deleteAll(['sub_category_id' => $id]);
                    return $this->redirect(['view', 'id' => $id]);
                }
                $model->main_category_id = null;
                $model->sub_category_id = $id;
                if ($model->save()) {
                    return $this->redirect(['view', 'id' => $id]);
                }
                else {
                    return var_dump(false);
                }
            }

            return $this->renderAjax('special-item', [
                'model' => $model,
                'items' => $items
            ]);
        }

        $model = new SpecialItems();
        if ($model->load(Yii::$app->request->post())) {
            $model->main_category_id = null;
            $model->sub_category_id = $id;
            if ($model->save()) {
                return $this->redirect(['view', 'id' => $id]);
            }
            else {
                return var_dump(false);
            }
        }

        
        return $this->renderAjax('special-item', [
            'model' => $model,
            'items' => $items
        ]);
    }
    
    public function actionUpdate1($id)
    {
        $model = $this->findModel($id);
        $special_item = new SpecialItems();
        $items = Items::find()->where(['sub_category_id' => $id])->all();

        if ($model->load(Yii::$app->request->post()) && $special_item->load(Yii::$app->request->post())) {
            $uplodadedImage = UploadedFile::getInstance($model, 'image_path');
            if ($uplodadedImage)
            {
                $dir_name = 'sub-categories-images/';
                if(!is_dir($dir_name)){
                    mkdir($dir_name, 0777, true);
                }
                $model->image_path = $dir_name.rand() . $uplodadedImage->name;
            }
            
            // $model->main_category_id = $main_cate_id;

            $special_item->main_category_id = null;
            $special_item->sub_category_id = $id;
            $special_item->save();

            if ($model->save()) 
            {
                if ($model->image_path != null)
                {
                   $uplodadedImage->saveAs($model->image_path); 
                }
                return $this->redirect(['view', 'id' => $model->id]);
            }
            return var_dump($model->getErrors());
        }

        return $this->render('update', [
            'model' => $model,
            'special_item' => $special_item,
            'items' => $items
        ]);
    }

    /**
     * Deletes an existing SubCategories 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);
        $main_category_id = $model->main_category_id;
        $model->delete();

		$other_sub_category = SubCategories::find()->where(['main_category_id' => $main_category_id])->one();
		if(! $other_sub_category){
            $items = Items::find()->where(['main_category_id' => $main_category_id, 'status' => 'Uncategorized'])->all();
            if($items){
                Items::updateAll(['status' => 'Inactive'], 'main_category_id = ' . $main_category_id);
            }
        }
        return $this->redirect(['main-categories/view', 'id' => $main_category_id]);
    }

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

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