<?php
if(!defined('MOD'))  die("access die");
purviewCheck('vote', 'plugin');
$action=$_GET['action'];
$action=$action ? $action : 'manage';
switch($action)
{
    case 'add':
        if($_POST['insert'] == 1){
            $type   = intval($_POST['type']);
            $passed = intval($_POST['passed']);
			$checkip = intval($_POST['checkip']);
            $option = $_POST['option'];
            $subject= trim($_POST['subject']);
            $totime = trim($_POST['totime']);
            if(!ereg('^[01]+$',$type) || empty($subject) || !ereg('^[01]+$',$passed) || empty($option))  qbase::showmsg('error request');
    	
            if(strpos($totime, "-")) {
                $time = explode("-", $totime);
                $totime = mktime(0, 0, 0, $time[1], $time[2], $time[0]);
    		} else{
                $totime = 0;
    		}
            $query="insert into `".TABLEPRE."votesubject`(subject,type,inputer,addtime,totime,passed,checkip) values('{$subject}','{$type}','{$admin_info['username']}','".$_SERVER['REQUEST_TIME']."','{$totime}','{$passed}',{$checkip})";
            $voteid = qdb::Query($query, true);
			for($i=0;$i<count($option);$i++){
				$option[$i] = trim($option[$i]);
				if(strlen($option[$i]) == 0) continue;
				qdb::Query("insert into `".TABLEPRE."voteoption` (`voteid`,`voteoption`) values('$voteid','".$option[$i]."')");
			}
			qbase::showmsg('操作成功！','default','plugin.php?plugin=vote&action=manage');
    	}else{
            $today=qbase::formatTime("Y-m-d", $_SERVER['REQUEST_TIME']);
            $over=qbase::formatTime("Y-m-d", $_SERVER['REQUEST_TIME']+3600*24*60);
    	}
    break;

    case 'edit':
        if($_POST['insert'] == 1)
    	{
            $voteid = intval($_GET['voteid']);
            $type   = intval($_POST['type']);
            $passed = intval($_POST['passed']);
            $voteoption = $_POST['voteoption'];
            $subject= trim($_POST['subject']);
            $totime = trim($_POST['totime']);
			$checkip = intval($_POST['checkip']);
            $voteoption_new = $_POST['voteoption_new'];
            if(!ereg('^[01]+$',$type) || empty($subject) || !ereg('^[01]+$',$passed)){
                showmsg('error request');
    		}
            if(strpos($totime, "-")) {
                $time = explode("-", $totime);
                $totime = gmmktime(0, 0, 0, $time[1], $time[2], $time[0]) - $timeoffset * 3600;
    		}else{
                $totime = 0;
    		}
            qdb::Query("UPDATE `".TABLEPRE."votesubject` SET subject='{$subject}',type='{$type}',totime='{$totime}',passed='{$passed}', checkip = '{$checkip}'  WHERE voteid='$voteid' limit 1");

            foreach($voteoption as $optionid=>$option){
                if( $option){
                    qdb::Query("UPDATE `".TABLEPRE."voteoption` set `voteoption`='$option' WHERE optionid='{$optionid}' limit 1");
        		}else {//此布实际上已经不需要了
                    qdb::Query("delete from ".TABLEPRE."voteoption where optionid=$optionid limit 1");
        		}
    		}
            if( is_array($voteoption_new))  { //添加新的数据
                foreach($voteoption_new as $val){
                    if($val = trim($val))
                    qdb::Query("insert into `".TABLEPRE."voteoption` (`voteid`,`voteoption`) values('$voteid','".$val."')");
        		}
    		}
            qbase::showmsg('操作成功！','default','plugin.php?plugin=vote&action=manage');
    	} else{
            $voteid = intval($_GET['voteid']);
            $vote  = qdb::queryFirst("SELECT * FROM `".TABLEPRE."votesubject` where voteid='{$voteid}' limit 1");
			if( $admin_info['groupid'] == 3 && $vote['inputer']!=$admin_info['username']) purviewCheckDie();
            $subject = $vote['subject'];
            $voteid  = $vote['voteid'];
			$checkip  = $vote['checkip'];
            $type    = $vote['type'];
            $passed  = $vote['passed'];
            $todate  = $vote['totime'] ? qbase::formatTime("Y-m-d",$vote['totime']) : 0 ;
            $option_r=qdb::fetchAll("select * from `".TABLEPRE."voteoption` where `voteid`=".$voteid." order by optionid asc");
            foreach($option_r as $option){
            	$k++;
                $option['index']=$k;
                $options[]=$option;
    		}
    	}
    break;

    case 'passed':
		checkAdminReferer();
        $voteid = intval($_GET['voteid']);
		if( $admin_info['groupid'] > 2 )
		{
			$vote  = qdb::QueryAlone("SELECT inputer FROM `".TABLEPRE."votesubject` where voteid='$voteid' limit 1");
			if( $vote['inputer']!=$admin_info['username']) purviewCheckDie();
		}
        $passed=intval($_GET['passed']);
        $timestamp=$_SERVER['REQUEST_TIME'];
        qdb::Query("update `".TABLEPRE."votesubject` set passed='$passed' where voteid='$voteid'");
        qbase::showmsg('操作成功！','default','plugin.php?plugin=vote&action=manage');

    break;

    case 'delete':
		checkAdminReferer();
        $voteid=$_GET['voteid']?$_GET['voteid']:$_POST['voteid'];
        $voteids = $voteid;
        $voteid = is_array($voteid) ? trim(implode(',',$voteid)) : intval($voteid);
        qdb::Query("delete from `".TABLEPRE."votesubject` where voteid in ($voteid)");
        qdb::Query("delete from `".TABLEPRE."voteoption` where voteid in ($voteid)");
        qdb::Query("delete from `".TABLEPRE."voteip` where voteid in ($voteid)");
        qbase::showmsg('操作成功！','default','plugin.php?plugin=vote&action=manage');
    break;

    case 'getcode':
		checkAdminReferer();
        $voteid=intval($_GET['voteid']);
        $subject=qdb::queryFirst("SELECT * FROM `".TABLEPRE."votesubject` WHERE voteid='$voteid'");
        if(empty($subject)) qbase::showmsg('对不起，该记录不存在！请返回！','default','plugin.php?plugin=vote&action=manage');
        $type=$subject['type'] ? "checkbox" : "radio";
        $option_type=$subject['type'] ? "option[]":"option";
        $options = qdb::fetchAll("select * from `".TABLEPRE."voteoption` where `voteid`=".$voteid);
    break;

    case 'ajax':
		checkAdminReferer();
        $optionId = intval( $_GET['id']);
        qdb::Query("delete from ".TABLEPRE."voteoption where optionid='$optionId' limit 1");
        $data = array(1);
        header("x-json: " . qbase::jsonencode($data));
        exit();
    break;

    default:
		$pageno  = intval( $_GET['pageno']) ? intval( $_GET['pageno']) : 1 ;
		$pagesize = 20;
		$startid = ($pageno -1)*$pagesize;
		$votes = array();
		$where   = $admin_info['groupid'] > 2 ? " where s.inputer='{$admin_info['username']}'" : '' ;
        $query   = qdb::fetchAll("SELECT s.*, SUM(o.number) as num FROM  `".TABLEPRE."votesubject` as s left join `".TABLEPRE."voteoption` as o on s.voteid=o.voteid $where group by o.voteid  ORDER BY s.passed, s.voteid desc limit $startid, $pagesize");
        foreach($query  as $vote) 
    	{
            $vote['adddate'] = qbase::formatTime("Y-m-d",$vote['addtime']);
            $vote['todate']  = $vote['totime'] ? qbase::formatTime("Y-m-d",$vote['totime']) : "不限";
            $votes[]       = $vote;
    	}
    break;
}
include qbase::template($path . 'plugin/vote');
?>
