<?php
try
{
	require_once('data/config.php');
	$mysql_servicer=$db_host;//服务器名
	$mysql_username=$db_user ;//数据库用户名
	$mysql_passwrod=$db_pass;//数据库密码
	$mysql_database=$db_name; //要连接的数据库名字
	$DB_PREFIX = $prefix;
	$sql_table_prefix = $DB_PREFIX;
	$requestKind = $_GET["requestKind"];
	//连接数据库
	$conntion=mysql_connect($mysql_servicer,$mysql_username,$mysql_passwrod) or die ("0=不能连接数据库:");
	mysql_select_db($mysql_database) or die("0=不能选择这个数据库，或数据库不存在");  
	mysql_query("SET CHARACTER SET utf8");		
	//授权验证
	$can_continue = true;	
/* 	$user_id = $_GET["user_id"];
	$pwd = $_GET["pwd"];
	$sql="SELECT password FROM `".$sql_table_prefix."admin_user` WHERE user_name = '".$user_id."'";	
	$result=mysql_query($sql,$conntion) or die("0=查询失败！错误是：".mysql_error());
	$count=mysql_num_rows($result);
	if($count=="0")
	{
		echo "0=授权验证失败，用户不存在";
	}
	else
	{
		$row = mysql_fetch_array($result);
		$password = $row["password"];
		if($pwd == $password)
		{
			$can_continue = true;			
		}
		else echo "0=授权验证失败，密码错误";
	} */
	if($can_continue)
	{
		if($requestKind == "0")
		{
			//请求客户资料数据
			$customers_id = $_GET["customers_id"];
			if($customers_id == '')
				$customers_id = 0;
			$sql="SELECT user_id AS customers_id, user_name AS customers_name, email,
				CONCAT(office_phone, ', ', home_phone, ', ', mobile_phone) AS tel,
				'' AS fax 
				FROM `".$sql_table_prefix."users` 
				WHERE user_id > ".$customers_id;
			//设置编码
			mysql_query("set names utf8");			
			//执行sql查询
			$result=mysql_query($sql,$conntion) or die("0=查询失败！错误是：".mysql_error());
			//返回多少条记录
			$count=mysql_num_rows($result);
			if($count=="0"){
				echo ""; //没有记录一定返回空字符串
			}else{
				while($row=mysql_fetch_array($result)){
					$select[] = array("customers_id"=>$row["customers_id"],
					 "customers_name"=>$row["customers_name"],
					 "email"=>$row["email"],
					 "tel"=>$row["tel"],
					 "fax"=>$row["fax"]); 
				}
				echo json_encode($select); 			
			};
		}
		else if($requestKind == "1")
		{
			//请求订单数据
			$begindate = $_GET["begindate"];
			$billno = $_GET["billno"];
			if($billno == '')
				$billno = 0;
			$syncByTime = $_GET["syncByTime"];
			if($syncByTime == '')
				$syncByTime = '0';	
			//从表中提取信息的sql语句
			$sql="SELECT A.goods_id AS orders_products_id,A.goods_name AS product_name, 
				'' AS product_model, 
				A.goods_attr AS product_size,
				A.goods_number AS quantity, 
				A.goods_price AS price, 
				(A.goods_number * A.goods_price) AS total,  
				B.goods_img AS product_image_url,
				C.order_sn AS shipping_order_id,  
				C.consignee AS customer_name, 
				C.email AS email, 
				CONCAT(C.tel, ', ', C.mobile) AS tel, 
				'' AS fax, 
				C.consignee AS shipping_customer_name, 
				'' AS shipping_company, 
				C.address AS shipping_address_1, 
				'' AS shipping_address_2, 
				C.city AS shipping_city, 
				C.zipcode AS shipping_postcode, 
				C.country AS shipping_country, 
				C.province AS shipping_zone, 
				C.shipping_name AS shipping_method, 
				C.pay_name AS payment_method, 
				'RMB'AS currency_code, 
				C.shipping_fee AS shipping_to_rate, /*该字段为快递费用，需要从zen_orders_total表获取ot_shipping类型值并赋值到该字段*/
				C.insure_fee AS insurance_premium, 	
				C.pay_fee AS procedure_fee, 	
				C.goods_amount AS sub_total, 	/*该字段为表身所有产品合计金额，需要从zen_orders_total表获取ot_subtotal类型值并赋值到该字段*/
				C.order_amount AS order_total,
				C.add_time AS shipping_order_date, 
				'' AS ip,
				C.order_status,
				0 AS HasPay
				FROM 
				`".$sql_table_prefix."order_goods` A
				INNER JOIN `".$sql_table_prefix."goods` B ON B.goods_id = A.goods_id
				LEFT JOIN `".$sql_table_prefix."order_info` C ON C.order_id = A.order_id
				WHERE C.add_time >= UNIX_TIMESTAMP('".$begindate."')";
			if($syncByTime == "0")
			{
				//以最大订单号同步为准，而不是以最近同步的订单最大日期
				$sql = $sql." AND C.order_sn > '".$billno."'";
			}					
			//设置编码
			mysql_query("set names utf8");
			//执行sql查询
			$result=mysql_query($sql,$conntion) or die("0=查询失败！错误是：".mysql_error());
			//返回多少条记录
			$count=mysql_num_rows($result);
			if($count=="0"){
				echo ""; //没有记录一定返回空字符串
			}else{			
				while($row=mysql_fetch_array($result)){
					$product_image_urls = array();
					$product_image_url = $row["product_image_url"];
					if(strlen($product_image_url) > 0)
					{		
						array_push($product_image_urls, $product_image_url);
					}				
					$select[] = array("product_name"=>$row["product_name"],
					 "product_sku"=>$row["orders_products_id"],
					 "product_model"=>$row["product_model"],
					 "product_size"=>$row["product_size"],
					 "quantity"=>$row["quantity"],
					 "price"=>$row["price"],
					 "total"=>$row["total"],
					 "product_image_urls"=>$product_image_urls,
					 "shipping_order_id"=>$row["shipping_order_id"],
					 "customer_name"=>$row["customer_name"],
					 "email"=>$row["email"],
					 "tel"=>$row["tel"],
					 "fax"=>$row["fax"],
					 "shipping_customer_name"=>$row["shipping_customer_name"],
					 "shipping_company"=>$row["shipping_company"],
					 "shipping_address_1"=>$row["shipping_address_1"],
					 "shipping_address_2"=>$row["shipping_address_2"],
					 "shipping_city"=>$row["shipping_city"],
					 "shipping_postcode"=>$row["shipping_postcode"],
					 "shipping_country"=>$row["shipping_country"],
					 "shipping_zone"=>$row["shipping_zone"],
					 "shipping_method"=>$row["shipping_method"],
					 "payment_method"=>$row["payment_method"],
					 "currency_code"=>$row["currency_code"],
					 "shipping_to_rate"=>$row["shipping_to_rate"],
					 "insurance_premium"=>$row["insurance_premium"],
					 "procedure_fee"=>$row["procedure_fee"],
					 "sub_total"=>$row["sub_total"],		
					 "order_total"=>$row["order_total"],
					 "shipping_order_date"=>date('Y-m-d G:i:s',$row["shipping_order_date"]),	 
					 "ip"=>$row["ip"],		
					 "order_status"=>$row["order_status"],							 
					 "HasPay"=>$row["HasPay"]); 

				}		
				echo json_encode($select); 
			};
		}
		else if($requestKind == "2")
		{
			//更新订单状态
			$billno = $_GET["billno"];
			$billState = $_GET["billstate"];	
			$comment = $_GET["comment"];			
			if($billno == '')
			{
				echo "0=没有传递订单号";
			}
			if($billState == '')
			{
				echo "0=没有传递订单状态";
			}		
			else
			{
				//设置编码
				mysql_query("set names utf8");
				$sql = "SELECT order_id,consignee FROM `".$sql_table_prefix."order_info` WHERE order_sn = '".$billno."'";
				//执行sql查询
				$result=mysql_query($sql,$conntion) or die("0=查询失败！错误是：".mysql_error());
				//返回多少条记录
				$count=mysql_num_rows($result);
				if($count=="0")
				{
					echo "0=网站后台找不到订单号为 ".$billno." 的订单"; //没有记录一定返回空字符串			
				}
				else
				{
					$cur_datetime = date("Y-m-d G:i:s",time());
					$order_status = 0;
					$shipping_status = 0;
					$pay_status = 0;
					switch($billState)
					{
						case 0://Pending - 等待处理
							$order_status = 0;
							$shipping_status = 0;
							$pay_status = 0;						
							break;
						case 1://Processing - 处理中 
							$order_status = 1;
							$shipping_status = 0;
							$pay_status = 2;						
							break;
						case 2://Shipped - 已发货
							$order_status = 5;
							$shipping_status = 1;
							$pay_status = 2;							
							break;
					}
					$row = mysql_fetch_array($result);
					$order_id = $row["order_id"];
					$comment = urldecode($comment);
					$comment = str_replace(array('<br>','<br/>', '<br />'), "\r\n", $comment); //ZenCart后台订单评论不支持HTML标签，所以这里要替换掉
					$sql = "UPDATE `".$sql_table_prefix."order_info` SET order_status = ".$order_status.", shipping_status = ".$shipping_status.", pay_status = ".$pay_status." WHERE order_sn = '".$billno."'";
					$result = mysql_query($sql, $conntion) or die("0=更新订单号为 ".$billno." 的订单状态失败！错误是：".mysql_error());
					$sql = "INSERT INTO `".$sql_table_prefix.			 "order_action`(order_id,action_user,order_status,shipping_status,pay_status,action_place,log_time,action_note) 
						VALUES(".$order_id.", 'Admin',".$order_status.",".$shipping_status.",".$pay_status.",0,UNIX_TIMESTAMP('".$cur_datetime."'),'".$comment."')";
					$result = mysql_query($sql, $conntion) or die("0=添加订单号为 ".$billno." 的订单状态历史失败！错误是：".mysql_error());
					echo "1=更新网站后台订单号为 ".$billno." 的订单成功.";
				}			
			}
		}
		else if($requestKind == "3")
		{
			//同步特定订单数据
			$billno = $_GET["billno"];
			if($billno == '')
				$billno = 0;
			//从表中提取信息的sql语句
			$sql="SELECT A.goods_id AS orders_products_id,A.goods_name AS product_name, 
				'' AS product_model, 
				A.goods_attr AS product_size,
				A.goods_number AS quantity, 
				A.goods_price AS price, 
				(A.goods_number * A.goods_price) AS total,  
				B.goods_img AS product_image_url,
				C.order_sn AS shipping_order_id,  
				C.consignee AS customer_name, 
				C.email AS email, 
				CONCAT(C.tel, ', ', C.mobile) AS tel, 
				'' AS fax, 
				C.consignee AS shipping_customer_name, 
				'' AS shipping_company, 
				C.address AS shipping_address_1, 
				'' AS shipping_address_2, 
				C.city AS shipping_city, 
				C.zipcode AS shipping_postcode, 
				C.country AS shipping_country, 
				C.province AS shipping_zone, 
				C.shipping_name AS shipping_method, 
				C.pay_name AS payment_method, 
				'RMB'AS currency_code, 
				C.shipping_fee AS shipping_to_rate, /*该字段为快递费用，需要从zen_orders_total表获取ot_shipping类型值并赋值到该字段*/
				C.insure_fee AS insurance_premium, 	
				C.pay_fee AS procedure_fee, 	
				C.goods_amount AS sub_total, 	/*该字段为表身所有产品合计金额，需要从zen_orders_total表获取ot_subtotal类型值并赋值到该字段*/
				C.order_amount AS order_total,
				C.add_time AS shipping_order_date, 
				'' AS ip,
				C.order_status,
				0 AS HasPay
				FROM 
				`".$sql_table_prefix."order_goods` A
				INNER JOIN `".$sql_table_prefix."goods` B ON B.goods_id = A.goods_id
				LEFT JOIN `".$sql_table_prefix."order_info` C ON C.order_id = A.order_id
				WHERE C.order_sn = '".$billno."'";
			//设置编码
			mysql_query("set names utf8");
			//执行sql查询
			$result=mysql_query($sql,$conntion) or die("0=查询失败！错误是：".mysql_error());
			//返回多少条记录
			$count=mysql_num_rows($result);
			if($count=="0"){
				echo ""; //没有记录一定返回空字符串
			}else{			
				while($row=mysql_fetch_array($result)){
					$product_image_urls = array();
					$product_image_url = $row["product_image_url"];
					if(strlen($product_image_url) > 0)
					{		
						array_push($product_image_urls, $product_image_url);
					}				
					$select[] = array("product_name"=>$row["product_name"],
					 "product_sku"=>$row["orders_products_id"],
					 "product_model"=>$row["product_model"],
					 "product_size"=>$row["product_size"],
					 "quantity"=>$row["quantity"],
					 "price"=>$row["price"],
					 "total"=>$row["total"],
					 "product_image_urls"=>$product_image_urls,
					 "shipping_order_id"=>$row["shipping_order_id"],
					 "customer_name"=>$row["customer_name"],
					 "email"=>$row["email"],
					 "tel"=>$row["tel"],
					 "fax"=>$row["fax"],
					 "shipping_customer_name"=>$row["shipping_customer_name"],
					 "shipping_company"=>$row["shipping_company"],
					 "shipping_address_1"=>$row["shipping_address_1"],
					 "shipping_address_2"=>$row["shipping_address_2"],
					 "shipping_city"=>$row["shipping_city"],
					 "shipping_postcode"=>$row["shipping_postcode"],
					 "shipping_country"=>$row["shipping_country"],
					 "shipping_zone"=>$row["shipping_zone"],
					 "shipping_method"=>$row["shipping_method"],
					 "payment_method"=>$row["payment_method"],
					 "currency_code"=>$row["currency_code"],
					 "shipping_to_rate"=>$row["shipping_to_rate"],
					 "insurance_premium"=>$row["insurance_premium"],
					 "procedure_fee"=>$row["procedure_fee"],
					 "sub_total"=>$row["sub_total"],		
					 "order_total"=>$row["order_total"],
					 "shipping_order_date"=>date('Y-m-d G:i:s',$row["shipping_order_date"]),	 
					 "ip"=>$row["ip"],		
					 "order_status"=>$row["order_status"],		
					 "HasPay"=>$row["HasPay"]); 

				}		
				echo json_encode($select); 
			};
		}
		else if($requestKind == "4")
		{
			if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_GET['webSystemKind']))
			{
				//判断临时文件存放路径是否包含用户上传的文件
				if(is_uploaded_file($_FILES["file"]["tmp_name"]))
				{
					$webSystemKind = $_GET['webSystemKind'];
					$subFolderPath = $_GET['subFolderPath'];
					$uploadDir = '';
					switch($webSystemKind)
					{
					case 0://Magento
						$uploadDir = './media/catalog/product/';
						break;
					case 1://ZenCart
						$uploadDir = './images/';
						break;
					case 2://OpenCart
						$uploadDir = './image/';
						break;
					case 3://EcShop
						$uploadDir = './images/';
						break;
					}
					if($uploadDir <> '')
					{
						$fileTypes  = array('jpg', 'jpeg', 'png', 'gif', 'bmp');
						$maxSize    = 1 * 1024 * 1024; //1M
						//为了更高效，将信息存放在变量中
						$upfile = $_FILES["file"];//用一个数组类型的字符串存放上传文件的信息
						$name = $upfile["name"];//便于以后转移文件时命名
						$type = $upfile["type"];//上传文件的类型
						$size = $upfile["size"];//上传文件的大小
						$tmp_file_name = $upfile["tmp_name"];//用户上传文件的临时名称
						$error = $upfile["error"];//上传过程中的错误信息
						$myFileType = substr($upfile['name'], strrpos($upfile['name'], ".") + 1);
						if ($size <= $maxSize) 
						{
							if (in_array($myFileType, $fileTypes)) 
							{
								//调用move_uploaded_file（）函数，进行文件转移
								$toFilePath = $uploadDir.$subFolderPath;
								if(!(file_exists($toFilePath)))
								{
									//create the folder
									mkdir($toFilePath, 0777);
									//give permission to the folder
									@chmod($toFilePath, 0777);//赋予权限
								}
								else
								{
									@chmod($toFilePath, 0777);//赋予权限
								}
								@is_dir($toFilePath) or mkdir($toFilePath, 0777);
								$toFullFileName = $toFilePath.'/'.$name;
								if (@move_uploaded_file($tmp_file_name, $toFullFileName)) 
								{
									//查看是否存在产品，如果没有则添加产品信息，否则都增加产品图片信息
								
								
									$result = 1;
									$resultMsg = '文件上传成功';
								}
								else
								{
									$resultMsg = '文件转移失败';
								}
							}
							else
							{
								$resultMsg = '不支持的文件类型';
							}
						}
						else
						{
							$resultMsg = '文件太大';
						}
					}
					else
					{
						$resultMsg = '未知系统';
					}
				}
				else
				{
					$resultMsg = '临时目录中不存在该上传的文件';
				}
			}
			else
			{
				$resultMsg = '未知请求';
			}
			echo $result.'='.$resultMsg;
		}
	}
}
catch(Exception $e)
{
	echo $e->getMessage();
}	
?>