<?php

namespace backend\controllers;

use Yii;
use common\models\Ad;
use common\models\AdCategory;
use yii\filters\AccessControl;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use common\components\CHelper;
use common\components\Upload;

/**
 * AdController implements the CRUD actions for Product model.
 */
class AdController extends BaseController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['index', 'create','update','delete','display'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                ],
            ],
        ];
    }

    /**
     * Lists all Product models.
     * @return mixed
     */
    public function actionIndex()
    {
        $this->check_access('ad');
        $dataProvider = new ActiveDataProvider([
            'query' => Ad::find(),
            'pagination'=>[
                'pagesize'=>10,
            ],
        ]);

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

    /**
     * Creates a new Product model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $this->check_access('ad');
        $model = new Ad();
        $model->scenario = 'create';
        $model->ordid = 0;
        if(Yii::$app->request->isPost){
            $data_loaded = $model->load(Yii::$app->request->post());
            $instance = UploadedFile::getInstance($model,'img');
            if($instance){
                $uploader = new Upload($instance,['type'=>'image','saveFolder'=>'ad']);
                $model->img = $uploader->upload();
                if(!$model->img){
                    $this->showmsg(0,$uploader->getError());
                    return $this->redirect(Yii::$app->request->getReferrer());
                }
            }
            
            if ($data_loaded && $model->save()) {
                if($instance){
                    $uploader->save();
                }
                $this->showmsg(1,'添加成功！');
                return $this->redirect(['index']);
            }else{
                return $this->redirect(Yii::$app->request->getReferrer());
            }
        }else{
            return $this->render('create',[
                'model'=>$model,
            ]);
        }
    }

    /**
     * Updates an existing Product model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $this->check_access('ad');
        $model = $this->findModel($id);
        $img = $model->img;
        if(Yii::$app->request->isPost){
            $data_loaded = $model->load(Yii::$app->request->post());
            $instance = UploadedFile::getInstance($model,'img');
            if($instance){
                $uploader = new Upload($instance,['type'=>'image','saveFolder'=>'ad']);
                $model->img = $uploader->upload();
                if(!$model->img){
                    $this->showmsg(0,$uploader->getError());
                    return $this->redirect(Yii::$app->request->getReferrer());
                }
            }else{
                $model->img = $img;
            }
            if ($data_loaded && $model->save()) {
                if($instance){
                    $uploader->delete($img,'ad');
                    $uploader->save();
                }
                $this->showmsg(1,'修改成功！');
                return $this->redirect(['index']);
            }else{
                return $this->redirect(Yii::$app->request->getReferrer());
            }
        }else{
            return $this->render('update',[
                'model'=>$model,
            ]);
        }
    }
    public function actionDisplay($id,$display)
    {
        $this->check_access('ad');
        $model = $this->findModel($id);
        $model->display = $display;

        if ($model->save()) {
            $this->showmsg(1,'操作成功！');
            return $this->redirect(['index']);
        } else {
            $this->showmsg(0,'操作失败！');
            return $this->redirect(['index']);
        }
    }

    /**
     * Deletes an existing Product model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->check_access('ad');
        $model = $this->findModel($id);
        $uploader = new Upload();
        $uploader->delete($model->img,'ad');
        $model->delete();
        $this->showmsg(1,'删除成功！');

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

    /**
     * Finds the Product model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Product the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Ad::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
}
