<?php

namespace backend\controllers;

use Yii;
use common\models\Config;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use common\components\CHelper;
use common\components\Upload;

class SysController extends BaseController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        $this->check_access('sys');
        $list = Config::find()->asArray()->indexBy('name')->all();
        if(Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $instance = UploadedFile::getInstanceByName("Config[logo]");
            if($instance){
                $uploader = new Upload($instance,['type'=>'image','saveFolder'=>'logo']);
                $post['logo'] = $uploader->upload();
                if(!$post['logo']){
                    $this->showmsg(0,$uploader->getError());
                    return $this->redirect(Yii::$app->request->getReferrer());
                }
                else
                {
                    $uploader->save();
                }
            }
            foreach ($post as $key => $value) {
                Yii::$app->db->createCommand('UPDATE '.Yii::$app->db->tablePrefix.'config set `value`="'.$value.'" where `name`="'.$key.'"')->execute();
            }
            Config::updateCache();
            $this->showmsg(1,'保存成功！');
            return $this->redirect(Yii::$app->request->getReferrer());
        }
        return $this->render('index', [
            'list' => $list,
        ]);
    }
}
