<?php

define('IN_PHPMPS', true);
require 'include/common.php';
require '../include/com.fun.php';
chkadmin('com');
$_REQUEST['act'] = $_REQUEST['act'] ? trim($_REQUEST['act']) : 'list' ;

switch ($_REQUEST['act'])
{
	case 'add':
	  $mappoint = $CFG['map'] ? explode(',', $CFG['map']) : '';
	  $cats = com_cat_options();  
	  $info_area = area_options($areaid);
	  include tpl('add_com', 'com');
	break;

	case 'postok':
	$PNG_TEMP_DIR = '../phpqrcode/'.DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;  
    $PNG_WEB_DIR = 'temp/';  
    require '../phpqrcode/qrlib.php';    // QRcode lib  
	
	$catid     = $_POST['catid'] ? intval($_POST['catid']) : '';
	$comname   = $_POST['comname'] ? htmlspecialchars(trim($_POST['comname'])) : '';
	$areaid   = $_POST['areaid'] ? intval($_POST['areaid']) : '';
	$postdate  = time();
	$introduce = $_POST['content'] ? htmlspecialchars(trim($_POST['content'])) : '';;
	$hours     = $_POST['hours'] ? htmlspecialchars(trim($_POST['hours'])) : '';
	$phone     = $_POST['phone'] ? trim($_POST['phone']) : '';
	$address   = $_POST['address'] ? trim($_POST['address']) : '';
	$is_check  = $CFG['post_check'] == '1' ?  '0' : '1';
	
    if(empty($comname))showmsg("标题不能为空");
    if(empty($phone) && empty($qq) && empty($email))showmsg("联系方式必须填写一项");
	check_words(array($comname, $introduce));
	
    $sql = "insert into {$table}com (userid,catid,areaid,comname,introduce,phone,postdate,address,hours,is_check) 
	values ('0','$catid','$areaid','$comname','$introduce','$phone','$postdate','$address','$hours',$is_check)";
    $res = $db->query($sql);
	$id = $db->insert_id();
	//生成二维码
	$datavalue = $CFG['weburl'].'/url/m.php?id='.$id; // data  
    $ecc = 'H'; // L-smallest, M, Q, H-best  
    $size = 4; // 1-50  
  
    $filename = $PNG_TEMP_DIR.$id.'.png';  
    QRcode::png($datavalue, $filename, $ecc, $size, 2);  
    chmod($filename, 0777);

	//添加配置文件
	$sql = "insert into {$table}com_config (comid,userid) values ('$id','0')";
    $res = $db->query($sql);
	//
	$alled = array('png','jpg','gif','jpeg');
	$exname = strtolower(trim(substr(strrchr($_FILES['thumb']['name'], '.'), 1)));
	if(checkupfile($_FILES['thumb']['tmp_name']) && $_FILES['thumb']['tmp_name'] != 'none' && $_FILES['thumb']['tmp_name'] && $_FILES['thumb']['name'] && $_FILES['thumb']['size']<'523298' && in_array($exname,$alled)) {

		$thumb_name = $id.'_thumb'. '.' . end(explode('.', $_FILES['thumb']['name']));
		$dir = PHPMPS_ROOT . 'data/com/thumb';
		if(!is_dir($dir)) {
			if(@mkdir(rtrim($dir,'/'), 0777))@chmod($dir, 0777);
		}
		$to = $dir.'/'. $thumb_name;
		CreateSmallImage($_FILES['thumb']['tmp_name'], $to, $CFG['com_thumbwidth'], $CFG['com_thumbheight']);
		$image = 'data/com/thumb/'. $thumb_name;
		$db->query("update {$table}com set thumb='$image' where comid='$id' ");
	}

	showmsg("恭喜您，商家添加成功！", "com.php?act=add");
	break;

	case 'list':
		$cats = com_cat_options();
        $area = area_options();
		$page = empty($_REQUEST[page])? 1 : intval($_REQUEST['page']);

		$catid    = empty($_REQUEST['cat']) ? 0 : intval($_REQUEST['cat']);
		$areaid   = empty($_REQUEST['area']) ? 0 : intval($_REQUEST['area']);
		$typeid   = empty($_REQUEST['type']) ? 0 : intval($_REQUEST['type']);
		$keywords = empty($_REQUEST['keywords']) ? '' : trim($_REQUEST['keywords']);
		
		$where = '';
		$where = $catid > 0 ? " and catid='$catid'": '';
		$where .= $areaid > 0 ? " and areaid IN (" . get_area_children($areaid) . ")": '';
		
		switch($typeid)
		{
			case '1':
				$where .= " and is_check=1 ";
			break;

			case '2':
				$where .= " and is_check=0 ";
			break;

			case '3':
				$where .= " and is_pro>".time();
			break;

			case '4':
				$where .= " and is_top>".time();
			break;
		}
		
		if (!empty($keywords)) {
			$where .= " AND (title LIKE '%$keywords%' OR content LIKE '%$keywords%')";
		}
		
		if(empty($where) && !isset($_POST['cat']) && !isset($_POST['area']) && !isset($_POST['keywords']) && isset($_GET['page'])) {
			$_SESSION['where'] = $_SESSION['where'];
		} elseif(empty($where) && isset($_POST)) {
			$_SESSION['where'] = '';
		} elseif(!empty($where))
		{
			$_SESSION['where'] = $where;
		}

		$sql = "SELECT COUNT(*) FROM {$table}com WHERE 1 $_SESSION[where]";
		$count = $db->getOne($sql);
		$pager = get_pager('com.php',array('act'=>'list'),$count,$page,'15'); 
		$sql = "SELECT a.*,b.fc FROM {$table}com as a left join {$table}com_config as b on a.comid=b.comid WHERE 1 $_SESSION[where] ORDER BY a.comid DESC,postdate DESC LIMIT $pager[start],$pager[size]";
		$res = $db->query($sql);
		$articles = array();
		while($row=$db->fetchRow($res)) {
			$row['comname']  = cut_str($row['comname'],'10');
			$row['postdate'] = date('Y-m-d', $row['postdate']);
			$row['fc'] = empty($row['fc']) ? '<font color=red>无分成</font>' : $row['fc'].'%';
			$row['is_check'] = $row['is_check']==1 ? '是' : '<font color=red>否</font>';
			$articles[]      = $row;
		}
		$here = "商家列表";
		$action = array('name'=>'添加商家', 'href'=>'category.php?act=add');
	    include tpl('list_com', 'com');
	break;

	case 'edit':
		$id = intval($_REQUEST['id']);
		$sql = "SELECT * FROM {$table}com WHERE comid = '$id'";
		$info = $db->getRow($sql);
		$userinfo['gold'] = $db->getOne("SELECT gold FROM {$table}member where userid=".$info['userid']);
		$com_cfg = $db->getOne("select fc from {$table}com_config where comid='$id'");
		$countnum = $db->getRow("select sum(yjia) as allmoneys,sum(fc) as sermoneys,sum(value) as sisomoneys,sum(value-fc) as sorumoneys from {$table}pay_exchange where comid='$id'");
		$countnum['allmoneys'] = number_format($countnum['allmoneys'],2);
		$countnum['sermoneys'] = number_format($countnum['sermoneys'],2);
		$countnum['sisomoneys'] = number_format($countnum['sisomoneys'],2);
		$countnum['sorumoneys'] = number_format($countnum['sorumoneys'],2);
		if(empty($info)){show('信息不存在','index.php');}
		extract($info);
		$postdate = date('Y年m月d日', $postdate);
		$info_area = area_options($areaid);
		$refer = $_SERVER['HTTP_REFERER'];
		include tpl('edit_com', 'com');
	break;

	case 'update':
		$comid    = intval($_POST['id']);
		$comname  = $_POST['comname'] ? htmlspecialchars(trim($_POST['comname'])) : '';
		$areaid   = $_POST['areaid'] ? intval($_POST['areaid']) : '';
		$content  = $_POST['content'] ? htmlspecialchars(trim($_POST['content'])) : '';
		$shoptip = $_POST['shoptip'] ? htmlspecialchars(trim($_POST['shoptip'])) : '';
		$phone    = $_POST['phone'] ? trim($_POST['phone']) : '';
		$address  = $_POST['address'] ? trim($_POST['address']) : '';
		$mappoint = $_POST['mappoint'] ? trim($_POST['mappoint']) : '';
		$hours     = $_POST['hours'] ? htmlspecialchars(trim($_POST['hours'])) : '';
		$is_check  = trim($_POST['is_check']);
		$fc = $_POST['fc'] ? trim($_POST['fc']) : '0';
		$userid       = $_POST['userid']>0 ? intval($_POST['userid']) : '0';

		if(empty($comname))showmsg("名称不能为空");

		$sql = "UPDATE {$table}com SET
				areaid='$areaid',
				userid='$userid',
				comname='$comname',
				introduce='$content',
				phone='$phone',
				shoptip='$shoptip',
				mappoint='$mappoint',
				address='$address',
				hours='$hours',
				is_check='$is_check'
				where comid = '$comid' ";
		$res = $db->query($sql);
		$db->query("UPDATE {$table}com_config SET fc='$fc' WHERE comid='$comid'");
		if($userid>0){
			$db->query("UPDATE {$table}com_config SET userid='$userid' WHERE comid='$comid'");
		}
		admin_log("编辑信息 $comid 成功");
		$refer = trim($_POST['refer']);
		show('修改成功', $refer);
	break;

	case 'batch':
		$id = is_array($_REQUEST['id']) ? join(',', $_REQUEST['id']) : intval($_REQUEST['id']);
		if(empty($id))show('没有选择记录');
		if(empty($_REQUEST['type']))show('没有选择操作');
		switch ($_REQUEST['type'])
		{
			case 'delete':
				//删除图片
				$sql = "SELECT thumb FROM {$table}com WHERE comid IN ($id)";
				$image = $db->getAll($sql);
				foreach((array)$image AS $val) {
					if($val[thumb] != '' && is_file(PHPMPS_ROOT.$val[thumb])) {
						@unlink(PHPMPS_ROOT.$val[thumb]);
					}
				}
				$sql = "DELETE FROM {$table}com WHERE comid in ($id)";
				$res = $db->query($sql);
				
				//删除评论
				$sql = "DELETE FROM {$table}com_comment WHERE comid IN ($id)";
				$db->query($sql);

				//删除图片
				$sql = "SELECT path FROM {$table}com_image WHERE comid IN ($id)";
				$image = $db->getAll($sql);
				foreach((array)$image AS $val){
					if($val[path] != '' && is_file('../'.$val[path])){
						@unlink('../'.$val[path]);
					}
				}

				$sql = "DELETE FROM {$table}com_image WHERE comid IN ($id)";
				$db->query($sql);
				
				//删除COM_CONFIG配置
				$sql = "DELETE FROM {$table}com_config WHERE comid IN ($id)";
				$db->query($sql);

				admin_log("删除记录 $id 成功");
				show('删除信息成功', $_SERVER['HTTP_REFERER']);
			break;

			case 'is_check':
				$sql = "UPDATE {$table}com SET is_check=1 WHERE comid IN ($id)";
				$re = $db->query($sql);
				admin_log("审核记录 $id 成功");
				show('审核成功', $_SERVER['HTTP_REFERER']);
			break;
		}
	break;
	
	case 'com_tx':
	    $comid = $_REQUEST['comid'] ? intval($_REQUEST['comid']) : '';
		if(empty($comid)){
			$sqls = "";
			$sqls1 = "";
		}else{
			$sqls = " and a.comid='$comid'";
			$sqls1 = " and comid='$comid'";
		}
		$page = empty($_REQUEST['page'])? 1 : intval($_REQUEST['page']);
		$sql = "SELECT COUNT(*) FROM {$table}pay_tx where tid=1 $sqls1";
		$count = $db->getOne($sql);
		$pager = get_pager('com.php',array('act'=>'com_tx'),$count,$page,'20');
		
		$sql = "SELECT a.*,c.comname FROM {$table}pay_tx as a left join {$table}com as c on a.comid=c.comid where tid=1 $sqls ORDER BY txtime DESC LIMIT $pager[start],$pager[size]"; 
		$res = $db->query($sql);
		$usertx = array();
		while($row=$db->fetchRow($res)) {
			$row['soxus'] = ($row['money']*$row['soxu']/100)."(".$row['soxu']."%)"; 
			$row['siti'] = $row['money']-($row['money']*$row['soxu']/100);
			$row['txtime'] = date('Y-m-d H:i',$row['txtime']);
			$usertx[] = $row;
		}
	    $here = "会员提现记录";
	    include tpl('com_tx');
	break;
	
	case 'com_tx_no';
		$id = $_REQUEST['id'] ? intval($_REQUEST['id']) : '';
		if(empty($id))show("参数错误");
        $r = $db->getRow("SELECT money,userid FROM {$table}pay_tx WHERE id='$id'");
        $db->query("update {$table}member set gold=gold+".$r['money']." where userid=".$r['userid']);
        $db->query("update {$table}pay_tx set zuangtai=2 where id='$id'");
        show("提现退回成功，金额已返回到商家帐户！");
    break;
	
	case 'com_tx_yes';
	    $id = $_REQUEST['id'] ? intval($_REQUEST['id']) : '';
		if(empty($id))show("参数错误");
		$db->query("update {$table}pay_tx set zuangtai=1 where id='$id'");
		show("提现成功！");
	break;
	
	case 'add':
		if($_POST['dosubmit'])
		{
			if($_POST['token']!=$CFG['crypt']) show('提交错误');
			extract($_REQUEST);
            $amount = floatval($amount);
			if(empty($operation))show("参数错误");
			if(empty($stype))show("参数错误");
			$r = $db->getOne("SELECT comid FROM {$table}com WHERE comid='$comid'");
			if(!$r)show('不存在此商家');
			if($stype=='sms'){
			  $balance = "sms_num";
			  $balatxt = "[短信-".$comid."]";
			  $paytype = "SMS";
			}elseif($stype=='credit'){
			  $balance = "jf_num";
			  $balatxt = "[积分-".$comid."]";
			  $paytype = "CRE";
			} //$operation  + -
			$time = time();
			$year = date('Y', $time);
			$month = date('m', $time);
			$date = date('Y-m-d', $time);

			$note = htmlspecialchars_deep($note);
			$note = $balatxt.cut_str($note, 100);
			
			if($operation == '+')
			{
			    $mtype="入款";
			}
			elseif($operation == '-')
			{
			    $mtype="扣款";
			}
			
            $db->query("update {$table}com set $balance=$balance $operation $amount where comid='$comid'");
			$db->query("INSERT INTO {$table}pay (typeid,note,paytype,amount,balance,userid,year,month,date,inputtime,inputer,ip) VALUES('1','$note','$mtype','$amount','$money','$userid','$year','$month','$date','$time','system','$ip')");
			if($operation == '+'){
			$db->query("INSERT INTO {$table}pay_online (`paycenter`,`userid`,`comid`,`orderid`,`moneytype`,`amount`,`nums`,`trade_fee`,`status`,`sendtime`,`receivetime`,`ip`) VALUES('system','$_userid','$comid','99999','$paytype','$money','$amount','$trade_fee','1','$time','$time','$ip')");
			}
			//$url = 'com.php?act=add';
			show('操作成功');
		}
		else
		{
			if(!isset($typeid)) $typeid = 0;
			if(!isset($comid)) $comid = '';
			if(!isset($amount)) $amount = '';
			if(!isset($note)) $note = '';
			$comid = $_REQUEST['comid'] ? intval($_REQUEST['comid']) : '';
			$typeid = $_REQUEST['type'] ? trim($_REQUEST['type']) : '';
			if($comid){
			  $comname = $db->getOne("SELECT comname FROM {$table}com WHERE comid='$comid'");
			  if(!$comname)show('不存在此商铺');
			}
			include tpl('add_com_pay');
		}
	break;
}
?>