<?php
class buy
{
	var $db;
	var $tpl;
	var $page;
	var $pic_save_path;	 
	
	function buy()
	{
		global $db;
		global $config;
		global $tpl;		
		$this -> db     = & $db;
		$this -> tpl    = & $tpl;
		$this -> cTime  = date("Y-m-d H:i");
		$this->pic_save_path = "";//图片保存目录
		if(!empty($_POST))
		{
			include_once($config['webroot'].'/includes/filter_class.php');
			$word=new Text_Filter();
			$_POST['con']=$word->wordsFilter($_POST['con'], $matche_row);
			$_POST['detail']=$word->wordsFilter($_POST['detail'], $matche_row);
			$_POST['title']=$word->wordsFilter($_POST['title'], $matche_row);
		}
	}
	//================求购产品编辑=========
	function del_pro_buy($id)
	{
		global $buid,$config;
		$this->db->query("select a.id from  ".BUYPRO." a,".BUY." b 
				where  b.id=a.buy_id  and a.id=$id and b.userid='$buid' ");
        if($this->db->num_rows()>0)
		{
			$sql="delete  from ".BUYPRO." where id=$id";
			$this->db->query($sql);
			echo 1;
		}
	}
	
	function edit_pro_buy($buyid)
	{
		global $buid,$config;
		foreach($_POST['pname'] as $key=>$val)
		{
			$_POST['number'][$key]*=1;
			$_POST['price'][$key]*=1;
			
			if(!empty($_POST['buyproid'][$key]))
			{
				$sql="update ".BUYPRO."  set 
				`pname`='$val',`number`='".$_POST['number'][$key]."' ,`unit` ='".$_POST['unit'][$key]."',`price`='".$_POST['price'][$key]."' 
				 where id='".$_POST['buyproid'][$key]."'";
				 
				$this->db->query($sql);
			}
			else
			{	
				$sql="INSERT INTO ".BUYPRO." (`buy_id` ,`pname` ,`number` ,`unit` ,`price` 
				)VALUES ('$buyid', '$val','".$_POST['number'][$key]."','".$_POST['unit'][$key]."','".$_POST['price'][$key]."')";
				$this->db->query($sql);
			}
			
		}
	}
	
	function add_buy()
	{
		if(empty($_POST['catid'])&&empty($_POST['title']))
			return false;
		global $buid,$config;
		//===================================过滤<a
		$ifpay=empty($_SESSION["IFPAY"])?1:$_SESSION["IFPAY"];
		if($config['replace_outside_link_'.$ifpay]==1)
			$_POST["detail"]=replace_outside_link($_POST["detail"]);
		//======================================
		$cpc=$this->get_user_pv($buid);
		if(empty($_POST['con']))
		   $con=csubstr(strip_tags($_POST["desc"]),0,100);
		else
		   $con=htmlspecialchars($_POST["con"]);
		$title=htmlspecialchars($_POST["title"]);
		//##=====================添加图片
		if(!$admin)
		{
			include_once("$config[webroot]/includes/admin_class.php");
			$admin = new admin();
		}
		$catid=$_POST['catid'];
		if(!empty($_POST['tcatid']))
			$catid=$_POST['tcatid'];
		if(!empty($_POST['scatid']))
			$catid=$_POST['scatid'];
		if(!empty($_POST['sscatid']))
			$catid=$_POST['sscatid'];
		$infoCheck=$config['infoCheck_'.$ifpay];
		$seller_need=!empty($_POST['seller_need'])?implode(',',$_POST['seller_need']):'';//需求
		//=====================添加图片
		$pic = implode(',',array_unique($_POST['pic']));
		
		$sql="INSERT INTO ".BUY." (`userid`,`user`,`catid`,`title`,`keywords`,`con`
		,`desc`,`pic` ,`country` ,`province` ,`city` ,`valid_time` ,`buy_time` 
		,`delivery_time` ,`uptime` ,`seller_country` ,`seller_province` ,`seller_city` ,`seller_need` ,`statu`,type
		)
		VALUES ('$buid','$cpc[user]','$catid','$_POST[title]','$_POST[keywords]', 
		'$_POST[con]','$_POST[desc]','$pic','$cpc[country]','$cpc[province]','$cpc[city]',
		'$_POST[valid_time]','$_POST[buy_time]','$_POST[delivery_time]','".$this -> cTime ."', '$_POST[country]', '$_POST[province]', '$_POST[city]', '$seller_need','$infoCheck','$_POST[type]')";
		$this->db->query($sql);
		$id=$this->db->lastid();
		//------添加商品----------------------
		if(!empty($id))
		{
			$this->edit_pro_buy($id);
		}
		//--------------------------------------------------标签 
		//include_once($config['webroot']."/includes/tag_inc.php");
		//add_tags($_POST['keyword'],2,$id);
		//--------------------------------------------------积分
		//include($config['webroot']."/includes/point_inc.php");
		//if($point_config['point']=='1'&&$point_config['$buy_pic']!='0')
		//	renew_point('',$point_config['add_buy']);
		//-------------------------------------------------
		return $id;
	}
	
	
	function edit_buy()
	{
		$editID=$_POST['editID'];
		global $buid,$config;
		//===================================过滤<a
		$ifpay=empty($_SESSION["IFPAY"])?1:$_SESSION["IFPAY"];
		if($config['replace_outside_link_'.$ifpay]==1)
			$_POST["desc"]=replace_outside_link($_POST["desc"]);
		//------------------------------------
		$infoCheck=$config['infoCheck_'.$ifpay];
		$title=htmlspecialchars($_POST["title"]);
		
		if(empty($_POST['con']))
		   $con=csubstr(strip_tags($_POST["detail"]),0,100);
		else
		   $con=htmlspecialchars($_POST["con"]);
		$cpc=$this->get_user_pv($buid);
		$sub_sql='';
		$pic=array();
		if(!empty($_POST['dele_pic'])||!empty($_POST['pic']))
		{	
			if(!$admin)
			{
				include_once("$config[webroot]/includes/admin_class.php");
				$admin = new admin();
			}
			$this->db->query("select pic from ".BUY." WHERE id='$_POST[editID]' and userid='$buid'");
			$pic = $this->db->fetchField('pic');
			$pic = $admin->update_pro_pic( $pic );
			$pic = implode(',',array_unique($_POST['pic']));
			$sub_sql .= ",pic='$pic'";
		}
		$catid=$_POST['catid'];
		if(!empty($_POST['tcatid']))
			$catid=$_POST['tcatid'];
		if(!empty($_POST['scatid']))
			$catid=$_POST['scatid'];
		if(!empty($_POST['sscatid']))
			$catid=$_POST['sscatid'];
		$seller_need=!empty($_POST['seller_need'])?implode(',',$_POST['seller_need']):'';//需求
		
		$sql="update ".BUY." SET  
			`user`='$cpc[user]',`catid`='$catid',`title`='$_POST[title]',
			`keywords`='$_POST[keywords]',`con`='$_POST[con]',`desc`='$_POST[desc]'
			,`country`='$cpc[country]',`province`='$cpc[province]',
			`city`='$cpc[city]',`valid_time`='$_POST[valid_time]',`buy_time`='$_POST[buy_time]' 
			,`delivery_time`='$_POST[delivery_time]',`uptime`='".$this -> cTime."' 
			,`seller_country`='$_POST[country]',`seller_province`='$_POST[province]',
			`seller_city`='$_POST[city]',`seller_need`='$seller_need',statu='$infoCheck',type='$_POST[type]' $sub_sql 
		 where `userid`='$buid' and id='$editID'";
	
		$re=$this->db->query($sql);
		if($re)
		{	
			$this->edit_pro_buy($editID);
		}
		return true;
	}

	function get_user_pv($userid)
	{
		$sql="select * from ".ALLUSER." where userid='$userid'";
		$this->db->query($sql);
		$re=$this->db->fetchRow();
		foreach($re as $key=>$v)
		{
			if(!is_array($v))
				$re[$key]=addslashes($v);
		}
		return $re;
	}
	
	function buy_list()
	{
		global $buid;
		if(isset($_GET['statu']))
		{	
			$_GET['statu']*=1;
			if($_GET['statu']=='1')
				$sql=" and statu>=1 ";
			else
				$sql=" and statu='$_GET[statu]' ";
		}
		$_GET['id']*=1;
		if(!empty($_GET['id']))
			$sql=" and id='$_GET[id]' ";
		
		$sql="select id,title,uptime,statu,pic,keywords from ".BUY." 
			where  userid='$buid' $sql order by uptime desc";
		$this->db->query($sql);
		//=============================
	  	$page = new Page;
		$page->listRows=20;
		if (!$page->__get('totalRows')){
			$page->totalRows =$this->db->num_rows();
		}
        $sql .= "  limit ".$page->firstRow.",4";
		//=============================
		$res=$this->db->getRows();
		foreach($res as $pl)
		{
			$this->db->query('select count(*) as num from '.BUYQPRO.' where buy_id='.$pl['id']);
			$pl["bnum"]=$this->db->fetchField('num');
			
		
			$pl['img'] = $this->get_cover_img($pl['pic'] );
			
			if( $pl['img']=='')
				$pl['nopic']=1;
			$re["list"][]=$pl;
		}
		$re["page"]=$page->prompt();
		return $re;
	}
	
	
	function del_buy($id,$uid=NULL)
	{
		global $buid,$config;
		if(!empty($uid))
			$buid=$uid;
		/*	
		include($config['webroot']."/includes/point_inc.php");
		if($point_config['point']=='1'&&$point_config['del_buy']!='0')
			renew_point('',$point_config['del_buy']);
		*/
		$this->db->query("select catid,pic from ".BUY." where id='$id' and userid='$buid'");
		$re=$this->db->fetchRow();
		//update_cat_nums($re['catid'],'del','buy');

		//--------------------------删除扩展信息
		$this->db->query("delete from  ".BUY." where id='$id' and userid='$buid'");
		$this->db->query("delete from  ".BUYPRO." where buy_id='$id'");
		$this->db->query("delete from  ".BUYQPRO." where buy_id='$id'");
		
		include_once($config['webroot']."/includes/tag_inc.php");
		del_tag($id,2);

		//---------------------------删除图片
		if($re['pic']!='')
		{
			$pic = explode( ',',$re['pic'] );
			foreach($pic as $i)
			{
				@unlink($config['webroot'].'/'.$this->pic_save_path."$i");
				@unlink($config['webroot'].'/'.$this->pic_save_path.substr($i,0,strrpos($i,'/')+1).'big_'.substr($i,strrpos($i,'/')+1));
			}
		}
	}
	
	function update_buy($id)
	{
		global $buid,$config;
		if($id=="all")
		{
			include("includes/point_inc.php");
			if($point_config['point']=='1'&&$point_config['renew_buy']!='0')
			renew_point('',$point_config['renew_buy']);
			$sql="update ".BUY." SET uptime='$this->cTime' where userid='$buid'";
		}
		else
			$sql="update ".BUY." SET uptime='$this->cTime' where id='$id'";
		$this->db->query($sql);
	}

	
	function buy_detail($id)
	{
		if($id)
		{
			global $config,$buid;
			include_once($config['webroot']."/includes/tag_inc.php");
			$sql="select a.* from ".BUY." a  where a.id='$id' and a.userid='$buid'";
			$this->db->query($sql);
			$re=$this->db->fetchRow();
			$sql="select ext_table from ".OCAT." where catid='$re[catid]'";
			$this->db->query($sql);
			
			$re['ext_table']=$this->db->fetchField('ext_table');
			$re['ocatid']=$re['catid'];
			if(strlen($re['catid'])>8)
				$re['sscatid']=$re['catid'];
			if(strlen($re['catid'])>6)
				$re['scatid']=substr($re['catid'],0,8);
			if(strlen($re['catid'])>4)
				$re['tcatid']=substr($re['catid'],0,6);
			$re['catid']=substr($re['catid'],0,4);
			
			
			$re['keyword']= get_tags($id,2);
			$this->db->query("select * from ".BUYPRO." where buy_id='$id'");
			$re['prolist']=$this->db->getRows();
			$re['seller_need']=explode(',',$re['seller_need']);
			//=================================
			if(!empty($re['pic'])){
				$pic = $this->get_cover_img( $prod['pic'] );
				$re['cover_big'] = $pic ;
				$re['pic'] = explode(",",$re['pic']);		
			}		
			return $re;
		}
	}
	
	//--------------------------------------
	function company_other_buy($uid,$type=NULL,$limit=NULL)
	{
		if(!empty($limit))
			$sub_sql="limit 0,$limit";
		$sql="select title,id,type,pic from ".BUY." where userid='$uid' $sub_sql";
		$this->db->query($sql);
		$res=$this->db->getRows();
		foreach($res as $pl)
		{
			$pl['img'] = $this->get_cover_img($pl['pic']);
			$re[]= $pl;
		}
		return $re;
	}
	
	function same_cat_buy($catid)
	{
		if(!empty($_POST['province']))
			$subsql=" and a.province='$_POST[province]'  and statu>0";

		$sql="select * from ".BUY." a left join ".ALLUSER." b on a.userid=b.userid
		 	  where 
			  a.catid='$catid' $subsql order by a.statu desc limit 10";		
		$this->db->query($sql);
		$samepro=$this->db->getRows();
		foreach($samepro as $k=>$v)
		{
			$samepro[$k]['pic']=explode(",",$v['pic']);
		}
		
		return $samepro;
	}

	//##产品封面
	function get_cover_img( $pic='' )
	{
		global $config;
		if($pic=='' )
			return NULL;
		$pic = explode( ',',$pic );
		foreach( $pic as $v ){
			
			if(file_exists(str_replace($config['weburl'],$config['webroot'],$v)))
			{
			return $v;
			}
		}
		return '';
	}
	
	function getProTypeName($prod)
	{
		if(!empty($prod))
		{
			$sql = "select cat from ".OCAT." where catid in($prod)";
			$this->db->query($sql);
			$fieldlist="";
			$res=$this->db->getRows();
			foreach($res as $v)
			{
				if($v["cat"]!="")
				$fieldlist.=$v["cat"]."->";
			}
			$fieldlist = trim($fieldlist,"->");
		}
		return $fieldlist;
	}
	function buy_merge_user($array)
	{
		$old_uid=$array['old_uid'];
		$new_uid=$array['new_uid'];

		$sql = "update ".BUY." set userid='$new_uid' where userid='$old_uid'";
		$this->db->query($sql);
		$sql = "update ".OFFERDETAIL." set userid='$new_uid' where userid='$old_uid'";
		$this->db->query($sql);
	}
	function add_user_common_cat($cid)
	{
		global $buid;
		//-------------------
		$cid=explode(",",$cid);
		$id=$cid[0];
		if(!empty($cid[1]))
			$id=$cid[1];
		if(!empty($cid[2]))
			$id=$cid[2];
		if(!empty($cid[3]))
			$id=$cid[3];
		$sql="select id from ".SHOPSETTING." where company_id='$bcid'";
		$this->db->query($sql);
		$rec=$this->db->fetchRow();
		if($rec['id'])
			$sql="update ".SHOPSETTING." set common_cat=REPLACE(common_cat,',$id',''),common_cat=concat(common_cat,',$id') where userid='$buid'";
		else
			$sql="insert into ".SHOPSETTING." (userid,rec_pro,common_cat) values ('$buid','',',$id')";
		$re=$this->db->query($sql);
	}
	function space_buy_detail($id)
	{
		if(is_numeric($id))
		{
			global $config;
				$sql="select a.* from ".BUY." a  where a.id='$id' ";
			$this->db->query($sql);
			$re=$this->db->fetchRow();
			
			//$re['keyword']= get_tags($id,2);
			$this->db->query("select * from ".BUYPRO." where buy_id='$id'");
			$re['prolist']=$this->db->getRows();
			$re['deff_time']= ceil(((strtotime(date($re['valid_time']))+24*60*60)-time())/(24*60*60));
			$re['f_time']= ceil((time()-strtotime($re['uptime']))/(24*60*60));
			$re['f_time']=$re['f_time']<=0?'今':$re['f_time'];
			
			$this->db->query("select count(*) as num from ".BUYQPRO." where buy_id='$id'");
			$re['pro_num']=$this->db->fetchField('num');
			//=================================
			if(!empty($re['pic']))
			{
				$pic = $this->get_cover_img( $re['pic'] );
				$re['cover'] = $pic;
				$re['pic'] = explode(",",$re['pic']);		
			}		
			
			return $re;
		}
		else
		{
			header("Location: 404.php");
		    exit();
		}
	}
}
?>
