<?php

namespace Server\storage\web;

use Server\storage\StorageService;

class GroupController extends StorageService{

    public function post(){
        global $_GPC, $_W;
        $group = pdo_get($this->tables['group'], array('id'=>intval($_GPC['gid'])));
        $name = trim($_GPC['name']);
        if (empty($name)) return $this->error("分组名称不能为空");
        if (empty($group)){
            $data = array("name"=>$name,"uid"=>$_W['uid'],"uniacid"=>$this->uniacid);
            $complete = pdo_insert($this->tables['group'], $data);
        }else{
            if (is_error($this->verify($group))) return $this->verify($group);
            $complete = pdo_update($this->tables['group'], array('name'=>$name), array('id'=>$group['id']));
        }
        if (!$complete) return $this->error("保存失败，请重试");
        return $this->success("保存成功", referer());
    }

    public function verify($group){
        global $_W;
        if ($group['uniacid']==0){
            if (!$_W['isfounder']) return $this->error("暂无权限");
        }else{
            if ($group['uniacid']!=$this->uniacid) return $this->error("暂无权限");
        }
        return true;
    }

    public function remove(){
        global $_GPC, $_W;
        $group = pdo_get($this->tables['group'], array('id'=>intval($_GPC['gid'])));
        if (empty($group)) return $this->error("找不到该分组");
        if (is_error($this->verify($group))) return $this->verify($group);
        $res = pdo_delete($this->tables['group'], array(
            'id'=>$group['id']
        ));
        if (!$res) return $this->error("删除失败，请重试");
        pdo_update($this->tables['attach'], array('group_id'=>intval($group['pid'])), array('group_id'=>$group['id']));
        return $this->success("删除成功", "refresh");
    }

}
