<?php
/**
 * Copyright: Shanghai NuLang Network Technology Co., Ltd.
 * Faith: Some things do not need others to understand.
 * Project: CoverCMS <Your world, your ambition>
 * License: http://www.svipplus.cn/license/
 * Author: The Rain° <rain@svipplus.cn>
 * File: SiteController.php
 * Time: 10:57
 */

namespace app\dash\controller;


use app\common\controller\BaseController;
use app\common\toolKit\CacheKit;
use app\common\toolKit\CommonKit;
use app\common\toolKit\SiteKit;
use Symfony\Component\Filesystem\Filesystem;
use think\Db;

/**
 * Class SiteController
 * @package app\dash\controller
 */
class SiteController extends BaseController
{
    /**
     * @return mixed|\think\response\Json
     */
    public function indexAction()
    {
        $siteId = SiteKit::currentSiteId();
        if (request()->isPost()) {
            $dataFromPost = request()->post('cv/a', null);
            if (is_null($dataFromPost) || !is_array($dataFromPost)) {
                return json(['success' => false, 'message' => lang('Failure')]);
            }
            if (CommonKit::isMissing(['title'], $dataFromPost, true)) {
                return json(['success' => false, 'message' => lang('Failure')]);
            }
            $dataFromPost['status']['o'] = intval($dataFromPost['status']['o']);
            $dataFromPost['status'] = json_encode($dataFromPost['status']);
            $dataFromPost['company_info'] = json_encode($dataFromPost['company_info']);
            Db::name('site')->where('id',$siteId)->update($dataFromPost);
            CacheKit::updateSiteCache();
            return json(['success' => true, 'message' => lang('Success')]);
        }
        $sites = cache('sites');
        $item = $sites[$siteId];
        $item['status'] = json_decode($item['status'], true);
        $item['company_info'] = json_decode($item['company_info'], true);
        $this->assign([
            'item' => $item
        ]);
        return $this->fetch();
    }

    public function updateViewAction()
    {
        if (request()->isPost()) {
            $viewPath = RUNTIME_PATH.'twig';
            $filesystem = new Filesystem();
            if (is_dir($viewPath)){
                $filesystem->remove($viewPath);
            }
            $filesystem->mkdir($viewPath);
            $filesystem->chmod($viewPath,0777, 0000, true);
            return json(['success'=>true, 'message'=>'成功清除模板缓存']);
        }
    }
}