<?php
!function_exists('readover') && exit('Forbidden');

if ($action == "new") {
	InitGP(array('endtime','obtitle','retitle','umpire'));
	$endtime = PwStrtoTime($endtime);
	$endtime < $timestamp && Showmsg('debate_time');
	if (empty($obtitle) || empty($retitle)) {
		Showmsg('debate_notitle');
	} elseif (strlen($obtitle)>255 || strlen($retitle)>255) {
		Showmsg('debate_titlelen');
	}
	if ($umpire) {
		$umpireuid = $db->get_value("SELECT uid FROM pw_members WHERE username=".pwEscape($umpire));
		empty($umpireuid) && Showmsg('debate_noumpire');
	} else {
		$umpire = $windid;
	}
} elseif ($action == "reply" && $_POST['step']) {
	$standpoint = (int)GetGP('standpoint');
	if ($standpoint==1 || $standpoint==2) {
		$pwSQL = array();$count = $upSQL = '';
		$debatestand = $db->get_value("SELECT standpoint FROM pw_debatedata WHERE pid='0' AND tid=".pwEscape($tid)."AND authorid=".pwEscape($winduid));
		if ($debatestand) {
			$count = $db->get_value("SELECT COUNT(*) as count FROM pw_debatedata WHERE pid>'0' AND tid=".pwEscape($tid)."AND authorid=".pwEscape($winduid));
			$standpoint	= $debatestand;
		}
		$pwSQL[] = array(
			'tid'			=> $tid,
			'pid'			=> $pid,
			'authorid'		=> $winduid,
			'standpoint'	=> $standpoint,
			'postdate'		=> $timestamp,
			'vote'			=> 0,
			'voteids'		=> ''
		);
		if (empty($count)) {
			if ($standpoint == 1) {
				$upSQL = 'obposts=obposts+1';
			} else {
				$upSQL = 'reposts=reposts+1';
			}
		}
		if (!$debatestand) {
			$pwSQL[] = array(
				'tid'			=> $tid,
				'pid'			=> 0,
				'authorid'		=> $winduid,
				'standpoint'	=> $standpoint,
				'postdate'		=> $timestamp,
				'vote'			=> 0,
				'voteids'		=> ''
			);
			if ($standpoint == 1) {
				$upSQL .= ($upSQL ? ',' : '').'obvote=obvote+1';
			} else {
				$upSQL .= ($upSQL ? ',' : '').'revote=revote+1';
			}
		}
		$upSQL && $db->update("UPDATE pw_debates SET $upSQL WHERE tid=".pwEscape($tid));
		$pwSQL && $db->update("INSERT INTO pw_debatedata (tid,pid,authorid,standpoint,postdate,vote,voteids) VALUES".pwSqlMulti($pwSQL));
	}
} elseif ($action == "modify") {
	$debate = $db->get_one("SELECT endtime,judge FROM pw_debates WHERE tid=".pwEscape($tid));
	if ($debate && (!$debate['judge'] && $debate['endtime']>$timestamp)) {
		InitGP(array('endtime','obtitle','retitle','umpire'));
		$endtime = PwStrtoTime($endtime);
		$endtime < $timestamp && Showmsg('debate_time');
		if (empty($obtitle) || empty($retitle)) {
			Showmsg('debate_notitle');
		} elseif (strlen($obtitle)>255 || strlen($retitle)>255) {
			Showmsg('debate_titlelen');
		}
		if ($umpire) {
			$umpireuid = $db->get_value("SELECT uid FROM pw_members WHERE username=".pwEscape($umpire));
			empty($umpireuid) && Showmsg('debate_noumpire');
		}
		$db->update("UPDATE pw_debates SET" . pwSqlSingle(array(
			'obtitle'	=> $obtitle,
			'retitle'	=> $retitle,
			'endtime'	=> $endtime,
			'umpire'	=> $umpire,
			'judge'		=> 0
		)) . "WHERE tid=" . pwEscape($tid));
	}
}
?>