<?php

namespace app\controllers;

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

/**
 * MainCategoriesController implements the CRUD actions for MainCategories model.
 */
class MainCategoriesController 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 MainCategories models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new MainCategoriesSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

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

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

        if ($model->load(Yii::$app->request->post())) {
            $uplodadedImage = UploadedFile::getInstance($model, 'image_path');
            if ($uplodadedImage)
            {
                $dir_name = 'main-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());
        }

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

    /**
     * Updates an existing MainCategories 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 = 'main-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(['main_category_id' => $id])->one();
        $items = Items::find()->where(['main_category_id' => $id])->andWhere(['status' => 'Active'])->all();
        
        if ($model) {
            if ($model->load(Yii::$app->request->post())) {
                if (!$model->item_id){
                    SpecialItems::deleteAll(['main_category_id' => $id]);
                    return $this->redirect(['view', 'id' => $id]);
                }
                $model->main_category_id = $id;
                $model->sub_category_id = null;
                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 = $id;
            $model->sub_category_id = null;
            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);

        if ($model->subCategories) {
            $special_item = SpecialItems::find()->where(['main_category_id' => $id])->one();
        }

        if ($model->load(Yii::$app->request->post())) {
            
            $uplodadedImage = UploadedFile::getInstance($model, 'image_path');
            if ($uplodadedImage)
            {
                $dir_name = 'main-categories-images/';
                if(!is_dir($dir_name)){
                    mkdir($dir_name, 0777, true);
                }
                $model->image_path = $dir_name.rand() . $uplodadedImage->name;
            }
            
            if (isset(Yii::$app->request->post()['SpecialItems']) && $special_item->load(Yii::$app->request->post())){
                $special_item->main_category_id = $id;
                $special_item->sub_category_id = null;
                $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());
        }

        $items = Items::find()->where(['main_category_id' => $id])->all();

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

    /**
     * Deletes an existing MainCategories 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)
    {
        $this->findModel($id)->delete();

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

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

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

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