<?php

/**
 *      [Discuz!] (C)2001-2099 Comsenz Inc.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      $Id: install.php 34718 2014-07-14 08:56:39Z nemohou $
 */

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

if(!$_G['uid']) {
	showmessage('not_loggedin', NULL, array(), array('login' => 1));
}


require_once DISCUZ_ROOT.'./source/plugin/wechat/wechat.lib.class.php';
$tid = intval($_GET['tid']);
$siteid = $_G['wechat']['setting']['wsq_siteid'];



if($_GET['action']=='full'){
	$uid = intval($_G['uid']);
	include 'include/sms_func.php';
	if($_GET['formhash'] != $_G['formhash']){
		$result['showmessage'] = $_G['charset']=='gbk'?iconv('GBK','UTF-8',lang('message','submit_invalid')):lang('message','submit_invalid');
		$result['full'] = 2;
		echo json_encode($result); 
		exit;
	}
	//验证人数
	$applynumber = intval($_GET['applynumber']);  //本次验证人数
	$applynum = DB::result_first("SELECT SUM(applynumber) FROM ".DB::table('xj_eventapply')." WHERE tid='$tid' and verify=1"); //已报名人数
	$applycountnum = DB::result_first("SELECT event_number FROM ".DB::table('xj_event')." WHERE tid='$tid'"); //活动总人数
	if($applycountnum>0){
		if($applynumber > ($applycountnum-$applynum)){
			$result['showmessage'] = $_G['charset']=='gbk'?iconv('GBK','UTF-8',lang('plugin/xj_event', 'baomrsym')):lang('plugin/xj_event', 'baomrsym');
			$result['full'] = 2;
			echo json_encode($result); 
			exit;
		}
	}
	//验证是否重复报名
	$myapplynum = DB::result_first("SELECT count(*) FROM ".DB::table('xj_eventapply')." WHERE tid='$tid' and uid=$uid");
	if($myapplynum > 0){
		$result['showmessage'] = $_G['charset']=='gbk'?iconv('GBK','UTF-8',lang('plugin/xj_event', 'qinwcfbm')):lang('plugin/xj_event', 'qinwcfbm');
		$result['full'] = 2;
		echo json_encode($result); 
		exit;	
	} 
	
	$member = DB::fetch_first("SELECT extcredits1,extcredits2,extcredits3,extcredits4,extcredits5,extcredits6,extcredits7,extcredits8 FROM ".DB::table('common_member_count')." WHERE uid = ".$_G['uid']);
	$items = DB::fetch_first("SELECT starttime,userfield,setting,use_extcredits_num,use_extcredits FROM ".DB::table('xj_event')." WHERE tid = '$tid'");
	$event_starttime = dgmdate($items['starttime'],'dt');
	//判断积分够不够
	if($member['extcredits'.$items['use_extcredits']]<$items['use_extcredits_num']){
		$result['showmessage'] = $_G['setting']['extcredits'][$items['use_extcredits']]['title'].lang('plugin/xj_event', 'bgwfcj');
		$result['showmessage'] = $_G['charset']=='gbk'?iconv('GBK','UTF-8',$result['showmessage']):$result['showmessage'];
		$result['full'] = 2;
		echo json_encode($result); 
		exit;
	}
	
	$userfield = unserialize($items['userfield']);
	$setting = unserialize($items['setting']);
	//判断表单是否有空白。
	foreach($_POST as $key => $value) {
		if(empty($value) && $key != 'message') {
			$result['showmessage'] = lang('message','activity_exile_field');
			$result['showmessage'] = $_G['charset']=='gbk'?iconv('GBK','UTF-8',$result['showmessage']):$result['showmessage'];
			$result['full'] = 2;
			echo json_encode($result); 
			exit;
		}
	}
	$dateline = $_G['timestamp'];
	$eid = intval($_GET['eid']);
	$uid = $_G['uid'];
	$realname = addslashes($_GET['realname']);
	$mobile = addslashes($_GET['mobile']);
	$qq = addslashes($_GET['qq']);
	$bmmessage = addslashes($_GET['message']);

	$ufielddata = array();
	$selectuserfield = unserialize($items['userfield']);
	$sysuserfield = unserialize($_G['setting']['activityfield']);
	foreach($sysuserfield as $key => $value){
		if(in_array($key,$selectuserfield)){
			if(is_array($_GET[$key])){
				$ufielddata[$key] = implode(',',$_GET[$key]);
			}elseif($key=='birthday'){
				$ufielddata[$key] = $_GET['birthyear'].'-'.$_GET['birthmonth'].'-'.$_GET['birthday'];
			}elseif($key=='residecity'){
				$ufielddata[$key] = $_GET['resideprovince'].$_GET['residecity'].$_GET['residedist'].$_GET['residecommunity'];
			}else{
				$ufielddata[$key] = $_GET[$key];
			}
		}
	}
	$ufielddata = serialize($ufielddata);
	
	
	$eventapply = array();
	$eventapply['tid'] = $tid;
	$eventapply['eid'] = $eid;
	$eventapply['uid'] = $uid;
	$eventapply['realname'] = $realname;
	$eventapply['mobile'] = $mobile;
	$eventapply['qq'] = $qq;
	$eventapply['bmmessage'] = $bmmessage;
	$eventapply['dateline'] = $dateline;
	$eventapply['applynumber'] = $applynumber;
	$eventapply['ufielddata'] = $ufielddata;
	$eventapply['seccode'] = random(8,1);
	$eventapply['session'] = intval($_GET['session']);
	
	DB::insert('xj_eventapply',$eventapply);
	
	$num = DB::result_first("SELECT count(*) FROM ".DB::table('xj_event_member_info')." WHERE uid = '$uid'");
	if($num<1){
		DB::query("INSERT INTO ".DB::table('xj_event_member_info')." (uid) VALUES ('$uid')");
	}
	
	//积分操作
	/*
	if($items['use_extcredits_num']>0){
		updatemembercount($_G['uid'],array($items['use_extcredits']=>-$items['use_extcredits_num']));
	}
	*/


	
	//调用微信支付设置
	if(file_exists($xj_event_wxset = DISCUZ_ROOT.'./data/sysdata/cache_xj_event_wxset.php')) {
		@include $xj_event_wxset;
	}
	if($wxset['wsqonly']){
	  $zffyurl = $_G['siteurl']."plugin.php?id=xj_event:wsq_pay&tid=$tid";
	}else{
	  $zffyurl = $_G['siteurl']."plugin.php?id=xj_event:event_pay&tid=$tid";
	}
	
	
	
	
	if($setting['noverify']==1){
		if($setting['eventpay']){
			$result['showmessage'] = lang('plugin/xj_event', 'bmzltjcgxzzrzfym');
			$result['showmessage'] = $_G['charset']=='gbk'?iconv('GBK','UTF-8',$result['showmessage']):$result['showmessage'];
			$result['tourl'] = $zffyurl;
			$result['full'] = 2;
			echo json_encode($result); 
			exit;
		}else{	
			DB::query("update ".DB::table('xj_eventapply')." set verify=1 where tid='$tid' and uid=".$_G['uid']); //自动审核
			//短信操作
			if($setting['seccode'] == 1){
				$message = cutstr($event_title,30).lang('plugin/xj_event', 'hdbmcgrs').':'.$applynumber.lang('plugin/xj_event', 'renyanzhengma').':'.$eventapply['seccode'].' '.lang('plugin/xj_event', 'huodongshijian').':'.$event_starttime;
				xjsendsms(array($eventapply['mobile']),$message,lang('plugin/xj_event', 'maomyzmdx'));
				sendpm($eventapply['uid'],'',$message,$event_uid);
			}
			notification_add($event_uid, 'system', $_G['username'].' '.lang('plugin/xj_event', 'bmcjlnd').' <a href="forum.php?mod=viewthread&tid='.$tid.'" target="_blank">'.$event_title.'</a> '.lang('plugin/xj_event', 'hdxtyzdsh'),array(),0);
			$result['showmessage'] = lang('plugin/xj_event', 'gxnbmcg');
			$result['showmessage'] = $_G['charset']=='gbk'?iconv('GBK','UTF-8',$result['showmessage']):$result['showmessage'];
			$result['tourl'] = "http://wsq.discuz.com/?c=index&a=viewthread&f=wx&tid={$tid}&siteid={$siteid}&_bpage=1";
			$result['full'] = 2;
			echo json_encode($result); 
			exit;
		}
	}else{
		if($setting['eventpay']){
			$result['showmessage'] = lang('plugin/xj_event', 'bmzltjcgxzzrzfym');
			$result['showmessage'] = $_G['charset']=='gbk'?iconv('GBK','UTF-8',$result['showmessage']):$result['showmessage'];
			$result['tourl'] = $zffyurl;
			$result['full'] = 2;
			echo json_encode($result); 
			exit;
		}
		notification_add($event_uid, 'system', 'activity_notice', array(
					'tid' => $tid,
					'subject' => $event_title,
				));
		$result['showmessage'] = lang('plugin/xj_event', 'bmxxtjcgqddsh');
		$result['showmessage'] = $_G['charset']=='gbk'?iconv('GBK','UTF-8',$result['showmessage']):$result['showmessage'];
		$result['tourl'] = "http://wsq.discuz.com/?c=index&a=viewthread&f=wx&tid={$tid}&siteid={$siteid}&_bpage=1";
		$result['full'] = 2;
		echo json_encode($result); 
		exit;
	}
	

}elseif($_GET['action'] == 'cancel'){
	$items = DB::fetch_first("SELECT * FROM ".DB::table('xj_event')." A,".DB::table('forum_thread')." B WHERE A.tid=B.tid AND A.tid = '$tid'");
	if($items['activityexpiration']>$timestamp){
		$count = DB::result_first("SELECT count(*) FROM ".DB::table('xj_eventapply')." WHERE tid = '$tid' and uid = ".$_G['uid']);
		if($count < 1){
			showmessage('Access Denied');
		}
	
		DB::query("DELETE FROM ".DB::table('xj_eventapply')." WHERE tid = '$tid' and uid = ".$_G['uid']);
		//积分操作
		/*
		if($items['use_extcredits_num']>0){
			updatemembercount($_G['uid'],array($items['use_extcredits']=>$items['use_extcredits_num']));
		}
		*/
		//notification_add($items['authorid'], 'system',$_G['username'].' 取消了活动 <a href="forum.php?mod=viewthread&tid='.$tid.'" target="_blank">'.$items['subject'].'</a> 报名',array(),0);
		notification_add($items['authorid'], 'system', 'activity_cancel', array(
				'tid' => $tid,
				'subject' => $items['subject'],
				'reason' => $message
			));
		showmessage(lang('plugin/xj_event', 'cgqxbm'),"http://wsq.discuz.com/?c=index&a=viewthread&f=wx&tid={$tid}&siteid={$siteid}&_bpage=1");
	}else{
		showmessage('Access Denied');
	}
}





$items = DB::fetch_first("SELECT * FROM ".DB::table('xj_event')." WHERE tid = '$tid'");
$thread =  DB::fetch_first("SELECT subject FROM ".DB::table('forum_thread')." WHERE tid = '$tid'");
$setting = unserialize($items['setting']);
$userfield = unserialize($items['userfield']);
$selectuserfield = unserialize($items['userfield']);
if($selectuserfield) {
	if($selectuserfield) {
		$htmls = $settings = array();
		require_once libfile('function/profile');
		foreach($selectuserfield as $fieldid) {
			if(empty($ufielddata['userfield'])) {
				$memberprofile = C::t('common_member_profile')->fetch($_G['uid']);
				foreach($selectuserfield as $val) {
					$ufielddata['userfield'][$val] = $memberprofile[$val];
				}
				unset($memberprofile);
			}
			$html = profile_setting($fieldid, $ufielddata['userfield'], false, true);
			if($html) {
				$settings[$fieldid] = $_G['cache']['profilesetting'][$fieldid];
				$htmls[$fieldid] = $html;
			}
		}
	}
} else {
	$selectuserfield = '';
}
$applynumber = array();
for($i=1;$i<=$items['event_number_max'];$i++){
	$applynumber[] = $i;
}




?>
<script type="text/javascript" src="http://wsq.discuz.com/cdn/discuz/js/openjs.js"></script>
<script>
	var menu = new Array();
	WSQ.initBtmBar(menu);
	WSQ.showBtmBar();
	WSQ.initPlugin({name:'<?php echo $thread['subject'].lang('plugin/xj_event', 'baomin'); ?>'});

	var initWx = {
		'img': '<?php echo $_G['siteurl']; ?>/static/image/common/logo.png',
		'desc': '<?php echo $_G['bbsname'].lang('plugin/xj_event', 'huodzx'); ?>',
		'title': '<?php echo $thread['subject']; ?>',
	'pluginid':'xj_event:wsq_join_test',
		'param': 'a=1&b=2'
	};
	WSQ.initShareWx(initWx);
</script>
    
    
<style type="text/css">
    #container {margin:5px;}
    body {height:100%;}
	.input1{padding:14px; line-height:14px; width:100%;-moz-border-radius: 4px; -webkit-border-radius: 4px; border-radius:4px; border:1px solid #d8d8d8;}
    select{height:42px;-webkit-appearance:none;appearance:none;border:none;font-size:14px;padding:0px 10px;display:block;width:100%;-webkit-box-sizing:border-box;box-sizing:border-box;background-color: #FFFFFF;color:#aaa;border-radius:4px;}
	.selectdiv{margin-top:0px;outline:none;-moz-border-radius: 4px; -webkit-border-radius: 4px; border-radius:4px; border:1px solid #d8d8d8;position:relative;}
	.checkbox {
 width: 19px;
 height: 25px;
 padding: 0 5px 0 0;
 background: url(checkbox.png) no-repeat;
 display: block;
 float: left;
}
	label{float:left; font-size:14px; line-height:30px;}
</style>
<script type="text/javascript" src="source/plugin/xj_event/js/jquery.js"></script>
<script type="text/javascript">
$(function(){ 
     $("#testbtn").click(function(){
		  $.ajax({ 
			  type: 'POST', 
			  url: 'plugin.php?id=xj_event:wsq_join&tid=<?php echo $tid; ?>&action=full', 
			  //data: {level:'fff', roomnumber:'bbb'},
			  data:$('#bmform').serialize(),
			  dataType: 'json', 
			  cache: false, 
			  error: function(){ 
				  alert('error'); 
				  return false; 
			  }, 
			  success:function(json){ 
			  	  if(json.full == 2){
					  alert(json.showmessage);
					  if(json.tourl != null){
					  	top.location.href=json.tourl;
					  }
					  return false;		  
				  }
				  if(json.full == 1){
					  alert('<?php echo lang('plugin/xj_event','gxnbmcg'); ?>');
					  window.location.href="http://wsq.discuz.com/?c=index&a=viewthread&f=wx&tid=<?php echo $tid; ?>&siteid=<?php echo $siteid; ?>&_bpage=1";
					  return true;
				  }else{
					  alert('error'); 
					  return false; 
				  }
			  } 
		  });
    }); 
}); 

function showdistrict(container, elems, totallevel, changelevel, containertype) {
	var pid = changelevel >= 1 && elems[0] && $("#"+elems[0]) ? $("#"+elems[0]).find('option:selected').attr('did') : 0;
	var cid = changelevel >= 2 && elems[1] && $("#"+elems[1]) ? $("#"+elems[1]).find('option:selected').attr('did') : 0;
	var did = changelevel >= 3 && elems[2] && $("#"+elems[2]) ? $("#"+elems[2]).find('option:selected').attr('did') : 0;
	var coid = changelevel >= 4 && elems[3] && $("#"+elems[3]) ? $("#"+elems[3]).find('option:selected').attr('did') : 0;
	var url = "home.php?mod=misc&ac=ajax&op=district&container="+container+"&containertype="+containertype
		+"&province="+elems[0]+"&city="+elems[1]+"&district="+elems[2]+"&community="+elems[3]
		+"&pid="+pid + "&cid="+cid+"&did="+did+"&coid="+coid+'&level='+totallevel+'&handlekey='+container+'&inajax=1'+(!changelevel ? '&showdefault=1' : '');
	ajaxget(url, container, '');
}

function ajaxget(aurl,acontainer,c){
	$.ajax({ 
		type: 'GET', 
		url: aurl, 
		dataType: 'xml', 
		cache: false, 
		error: function(){ 
			alert('error'); 
			return false; 
		}, 
		success:function(xml){ 
			$("#"+acontainer).html($(xml).find('root').text());
		} 
	});
}

</script>
</head>
<body>
<div>
	<div style="height:20px;">
    	<?php echo $setting['session']; ?>
    </div>
    <form name="bmform" id="bmform">
    <input type="hidden" name="formhash" value="<?php echo $_G['formhash'];?>" />
    <input type="hidden" name="eid" value="<?php echo $items['eid'];?>" />

	<?php if($setting['session']){ ?>
    <div style="padding:10px 30px;">
        <div class="selectdiv"> 
        <select name="session"> 
        <option><?php echo lang('plugin/xj_event','huodongcc'); ?></option>
        <?php foreach($setting['session'] as $key=>$value){ ?>
        <option value="<?php echo $key; ?>"><?php echo $value; ?></option>
        <?php } ?>
        </select> 
        </div> 
    </div>
	<?php }?>
    
	<?php 
	
	if(!empty($selectuserfield)){
    	foreach($selectuserfield as $fieldid){
			if($settings[$fieldid]['available']){
				if($settings[$fieldid]['formtype'] != 'file'){
					$htmls[$fieldid] = str_replace('class="px"','class="input1" placeholder="'.$settings[$fieldid]['title'].'"',$htmls[$fieldid]);
            		$htmls[$fieldid] = preg_replace("/<div.+<\/div>/is", "", $htmls[$fieldid]);
					if(strpos($htmls[$fieldid],'select')>0){
						$htmls[$fieldid] = str_replace('tabindex="1">','tabindex="1"><option>'.$settings[$fieldid]['title'].'</option>',$htmls[$fieldid]);
						echo '<div style="padding:10px 30px;">'.$htmls[$fieldid].'</div>';
					}elseif(strpos($htmls[$fieldid],'checkbox')>0){
						//$htmls[$fieldid] = str_replace('type="checkbox"','type="checkbox" class="checkbox"',$htmls[$fieldid]);
						echo '<div style="padding:10px 30px;">'.$htmls[$fieldid].'<div style="clear:both;"></div></div>';
					}else{
						echo '<div style="padding:10px 30px;">'.$htmls[$fieldid].'</div>';
					}
				}else{
				}
			}
		}
	}
    ?>
    
    
    
    
    <div style="padding:10px 30px;">
        <div class="selectdiv"> 
        <select name="applynumber"> 
        <option value=""><?php echo lang('plugin/xj_event','baomingrs'); ?></option>
        <?php foreach($applynumber as $key=>$value){ ?>
        <option value="<?php echo $value; ?>"><?php echo $value; ?></option>
        <?php } ?>
        </select> 
        </div> 
    </div>

	<div style="padding:10px 30px;">
    	<input name="message" type="text" placeholder="<?php echo lang('plugin/xj_event','liuyan'); ?>" class="input1">
    </div>
	</form>

	<a href="javascript:" id="testbtn" style="display:block; height:44px; line-height:44px; text-align:center; background-color:#ff4a00; color:#FFF;-moz-border-radius: 4px; -webkit-border-radius: 4px; border-radius:4px; margin:10px 30px; font-size:16px; font-weight:bold;"><?php echo lang('plugin/xj_event','baomin'); ?></a>
    
</div>  
</body>
</html>
