<?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: SingleController.php
 * Time: 11:36
 */

namespace app\dash\controller;


use app\common\controller\BaseController;
use app\common\toolKit\CommonKit;
use app\common\toolKit\SiteKit;
use think\Db;

class SingleController extends BaseController
{
    private $categoryId;

    private $siteId;

    private $singleDb;

    public function _initialize()
    {
        $categoryId = input('?get.category_id') ? intval(input('get.category_id')) : input('post.category_id',0);
        if (intval($categoryId)===0){
            return json(['success'=>false, 'message'=>lang('Failure')]);
        }
        $this->categoryId = intval($categoryId);
        $this->siteId = SiteKit::currentSiteId();
        $this->singleDb = Db::name('single');
    }

    public function indexAction()
    {
        $item = $this->singleDb->where('category_id', $this->categoryId)->find();
        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','full_text'], $dataFromPost, true)) {
                return json(['success' => false, 'message' => lang('Failure')]);
            }
            if (!$item){
                $dataFromPost['category_id'] = $this->categoryId;
                $dataFromPost['create_time'] = $dataFromPost['update_time'] = time();
                $lastActionItem = $this->singleDb->insertGetId($dataFromPost);
                if (!$lastActionItem){
                    return json(['success'=>false, 'message'=>lang('Failure')]);
                }
            }else{
                $id = intval(input('post.id',0));
                if ($id===0){
                    return json(['success'=>false, 'message'=>lang('Failure')]);
                }
                $dataFromPost['update_time'] = time();
                $this->singleDb->where('id', $id)->update($dataFromPost);
            }
            return json(['success'=>true, 'message'=>lang('Success')]);
        }
        if (!$item){
            $item = ['title'=>'','seo_title'=>'','keywords'=>'','description'=>'','full_text'=>'','id'=>0,'category_id'=>$this->categoryId];
        }
        $this->assign('item', $item);
        return $this->fetch();
    }
}