<? include $_SERVER["DOCUMENT_ROOT"] . "/common/classes/ApiBase.php" ;?>
<?

/*
 * Admin process
 * add by dev.lee
 */
if (! class_exists("ApiUser"))
{

	class ApiUser extends ApiBase
	{

		function __construct($req)
		{
			parent::__construct($req);
		} 
		
		// 회원 포인트 조회 (http://106.240.232.36:8004/action_front.php?cmd=ApiUser.getInfoOfAvailPoint)
		function getInfoOfAvailPoint()
		{
			$no = $this->appUser["no"];
			
			$sql = "
                SELECT 
                	CASE 
                		WHEN SUM(AMT) IS NULL 
	                	THEN 0 
	                	ELSE SUM(AMT) 
                	END  AS AVAIL_AMT 
                FROM tbl_point_trans 
                WHERE user_fk = '{$no}' AND trans_type='I'
			";
			
			$avail_amt = $this->getValue($sql, "AVAIL_AMT");
			
			$sql = "
				SELECT 
					CASE 
						WHEN SUM(AMT) IS NULL 
						THEN 0 
						ELSE SUM(AMT) 
					END  AS PAY_AMT 
				FROM tbl_point_trans 
				WHERE user_fk = '{$no}' AND trans_type='O'
			";
			
			$pay_amt = $this->getValue($sql, "PAY_AMT");
			
			$use_amt = $avail_amt - $pay_amt;
			
			return $this->makeResultJson("1", "", $use_amt);
		}
		
		// 회원가입 여부 판단 (http://106.240.232.36:8004/action_front.php?cmd=ApiUser.initLogin&id=aa)
		function initLogin()
		{
			$id = $this->req["id"];
			
			$sql = "
				SELECT id 
				FROM v_alive_user 
				WHERE id='{$id}' 
				LIMIT 0,1 
			";
			
			$id = $this->getValue($sql, "id");
			
			$returnCode = - 1;
			if ($id != "")
			{
				$returnCode = 1;
			}
			
			return $this->makeResultJson($returnCode, "");
		}
		
		// 회원 그룹 (http://106.240.232.36:8004/action_front.php?cmd=ApiUser.getListOfMemberGroup)
		function getListOfMemberGroup()
		{
			$name = $this->req["name"];
			$addQuery = "";
			
			if ($name != "")
				$addQuery .= " AND name like '%" . $name . "%'";
			
			$sql = "
				SELECT * 
				FROM v_alive_user_group 
				WHERE 1=1 {$addQuery}
			";
			
			$list = $this->getArray($sql);
			
			if (sizeof($list) > 0)
				return $this->makeResultJson("1", "", $list);
			else
				return $this->makeResultJson("-1000", "내역이 없습니다.");
		}
		
		// 회원 가입 (http://106.240.232.36:8004/action_front.php?cmd=ApiUser.memberJoin)
		function memberJoin()
		{
			$id = $this->req["id"];
			
			$name = $this->req["name"];
			$tel = str_replace(" ", "", $this->req["tel"]);
			$app_type = $this->req["app_type"];
			$group_fk = $this->req["group_fk"];
			$regiType = $this->req["regiType"];
			$memType = $this->req["memType"];
			
			$deviceID = $this->req["deviceID"];
			$deviceTypeID = $this->req["deviceTypeID"];
			$storeTypeID = $this->req["storeTypeID"];
			$registrationKey = $this->req["registrationKey"];
			$appVersion = $this->req["appVersion"];
			
			// $status = ($memType == this.MEM_TYPE_NOMAL) ? "" : "" ;
			
			$sql = "
				SELECT *
				FROM tbl_user
				WHERE `id` = '{$id}' AND `status` = 'Y'
				LIMIT 1
			";
			$regInfo = $this->getRow($sql);
			
			if($regInfo != null)
				return $this->makeResultJson(-100, "이미 회원가입을 하셨습니다.");
			
			// 멤버십 회원 가입 일경우 전화번호 필수
			if ($this->MEM_TYPE_HOLD == $memType)
			{
				if($tel == "")
					return $this->makeResultJson(-101, "제휴회원 요청시 전화번호는 필수 입력사항입니다.");
				
				$sql = "
					SELECT *
					FROM tbl_user
					WHERE `tel` = '{$tel}' AND `status` = 'Y' AND `member_type` != '{$this->MEM_TYPE_NOMAL}'
					LIMIT 1
				";
				$telResult = $this->getRow($sql);
				
				if($telResult != null)
					return $this->makeResultJson(-102, "이미 가입된 멤버십 회원이십니다.");
			}

			$insAssoc = Array(
				"id" => $id,
				"name" => $name,
				"tel" => $tel,
				"app_type" => $app_type,
				"group_fk" => $group_fk,
				"member_type" => $memType,
				"regi_type" => $regiType,
				"device_id" => $deviceID,
				"device_type_id" => $deviceTypeID,
				"storeType_id" => $storeTypeID,
				"reg_dt" => "now()",
				"app_version" => $appVersion,
				"registration_key" => $registrationKey,
				"status" => "Y"
			);
			
			$result = $this->techOfInsertForUpdate("tbl_user", $insAssoc);
			
			$no = $this->mysql_insert_id();
			
			$file_vir_name = "";
			$file_org_name = "";
			
			if ($this->MEM_REGI_EMAIL == $regiType)
			{
				$updateFileData = $this->inFn_Common_fileSave($_FILES);
				
				$file_vir_name = $updateFileData["file"]["saveURL"];
				$file_org_name = $updateFileData["file"]["name"];
			}
			else
			{
				$file_vir_name = $this->req["fileName"];
			}
			
			$insFile = Array(
				"file_org_name" => $file_org_name,
				"file_vir_name" => $file_vir_name,
				"reg_dt" => "now()",
				"pa_no" => $no,
				"file_type" => "ME"
			);
			
			$fileResult = $this->techOfInsertForUpdate("tbl_file", $insFile);
			
			if ($result > 0)
			{
				$returnCode = "1";
				$returnMessage = "가입되었습니다.";
			}
			else
			{
				$returnCode = "-1";
				$returnMessage = "오류가 발생했습니다.";
			}
			
			return $this->makeResultJson($returnCode, $returnMessage, $userInfo);
		}
		
		/**
		 * 멤버쉽 신청
		 * @return string
		 */
		function reqMembership()
		{
			$memType=$this->req["memType"];
			$name = $this->req["name"];
			$tel = str_replace(" ", "", $this->req["tel"]);
			$group_fk = $this->req["group_fk"];
			$no = $this->appUser["no"];
			
			$sql = "
				SELECT *
				FROM tbl_user
				WHERE `no` = '{$no}' AND `status` = 'Y'
				LIMIT 1
			";
			
			$userInfo = $this->getRow($sql);
			
			if($userInfo == null)
			{
				return $this->makeResultJson("-10", "비정상 접근");
			}
			else if($userInfo["member_type"] != 'N')
			{
				return $this->makeResultJson("-100", "이미 멤버쉽을 신청하였습니다.");
			}
			else if($tel == "")
			{
				return $this->makeResultJson(-101, "제휴회원 요청시 전화번호는 필수 입력사항입니다.");
			}
			else
			{
				$sql = "
					SELECT *
					FROM tbl_user
					WHERE `tel` = '{$tel}' AND `status` = 'Y' AND `member_type` != '{$this->MEM_TYPE_NOMAL}'
					LIMIT 1
				";
				$telResult = $this->getRow($sql);
					
				if($telResult != null)
					return $this->makeResultJson(-102, "이미 가입된 멤버십 회원이십니다.");
				
				// 파일 업로드
				if ($_FILES != null && sizeof($_FILES) > 0)
				{
					// 삭제함
					$sql = "
						DELETE FROM tbl_file WHERE pa_no = '{$no}' AND file_type = '{$this->FILE_TYPE_MEM}'
					";
					$this->update($sql);
					
					$updateFileData = $this->inFn_Common_fileSave($_FILES);
				
					$file_vir_name = $updateFileData["file"]["saveURL"];
					$file_org_name = $updateFileData["file"]["name"];
				
					$insFile = Array(
						"file_org_name" => $file_org_name,
						"file_vir_name" => $file_vir_name,
						"reg_dt" => "now()",
						"pa_no" => $no,
						"file_type" => $this->FILE_TYPE_MEM
						);
				
					$fileResult = $this->techOfInsertForUpdate("tbl_file", $insFile);
				}
				
				$sql = "
					UPDATE tbl_user
					SET
						name = '{$name}'
						, tel = '{$tel}'
						, group_fk = '{$group_fk}'
						, member_type = '{$memType}'
					WHERE `no` = '{$no}'
				";
				$this->update($sql);
					
				return $this->makeResultJson("1", "저장되었습니다.", $this->inFn_ApiBase_getInfoOfUser($no));
			}
			
		}
		
		
		// 회원 로그인 (http://106.240.232.36:8004/action_front.php?cmd=ApiUser.userLogin)
		function userLogin()
		{
			$id = $this->req["id"];
			$deviceID = $this->req["deviceID"];
			$deviceTypeID = $this->req["deviceTypeID"];
			$storeTypeID = $this->req["storeTypeID"];
			$registrationKey = $this->req["registrationKey"];
			$appVersion = $this->req["appVersion"];
			
			$param = Array(
				$id,
				$deviceID,
				$deviceTypeID,
				$registrationKey,
				$storeTypeID,
				$appVersion
			);
			
			$sql = $this->strCallProc3("uspU_loginUser", $param);
			
			$result = $this->getMultiArray($sql);
			
			if ($result[0][0]["v_returnCode"] > 0)
			{
				$userInfo = $this->inFn_ApiBase_getInfoOfUser($result[0][0]["v_userNumber"]);
				LoginUtil::doAppLogin($userInfo);
				
				return $this->makeResultJson($result[0][0]["v_returnCode"], $result[0][0]["v_returnMsg"], $userInfo);
			}
			else
			{
				return $this->makeResultJson($result[0][0]["v_returnCode"], $result[0][0]["v_returnMsg"]);
			}
		}
		
		// 비동기 푸시키 갱신 API
		function setUserRegistrationKey()
		{
			$no = $this->appUser["no"];
			$registration_key = $this->req["registration_key"];
			
			if ($no != "-1")
			{
				$sql = "
					UPDATE tbl_user
					SET registration_key = '{$registration_key}'
					WHERE no = '{$no}'
				";
				$this->update($sql);
			}
		}
		
		// 민원 정보공유 푸시 설정
		function setCommentPushOnOff()
		{
			$no = $this->appUser["no"];
			$is_push = $this->req["is_push"];
			
			$sql = "
				UPDATE tbl_user
				SET comm_push = '{$is_push}'
				WHERE `no` = '{$no}'
			";
			$result = $this->update($sql);
			
			return $this->makeResultJson("1", "");
		}
		
		// 민원 정보공유 푸시 설정
		function setInfoPushOnOff()
		{
			$no = $this->appUser["no"];
			$is_push = $this->req["is_push"];
			
			$sql = "
				UPDATE tbl_user
				SET info_push = '{$is_push}'
				WHERE `no` = '{$no}'
			";
			$result = $this->update($sql);
			
			return $this->makeResultJson("1", "");
		}
		
		// 푸시 설정
		function setPushOnOff()
		{
			$no = $this->appUser["no"];
			$is_push = $this->req["is_push"];
			
			$sql = "
				UPDATE tbl_user
				SET is_push = '{$is_push}'
				WHERE `no` = '{$no}'
			";
			$result = $this->update($sql);
			
			return $this->makeResultJson("1", "");
		}
		
		// 렌트 푸시 설정
		function setRentOnOff()
		{
			$no = $this->appUser["no"];
			$is_rent = $this->req["is_push"];
				
			$sql = "
			UPDATE tbl_user
			SET is_rent = '{$is_rent}'
			WHERE `no` = '{$no}'
			";
			$result = $this->update($sql);
				
			return $this->makeResultJson("1", "");
		}
		
		// 로그아웃
		function userLogout()
		{
			$no = $this->appUser["no"];
			
			// 푸시키 초기화
			$sql = "
				UPDATE tbl_user
				SET registration_key = ''
				WHERE no = '{$no}'
			";
			$this->update($sql);
			
			return $this->makeResultJson("1", "");
		}
		
		// 정보수정
		function modifyUserInfo()
		{
			$userNo = $this->appUser["no"];
			$name = $this->req["name"];
			$tel = $this->req["tel"];
			$group_fk = $this->req["group_fk"] ;
			$groupName = $this->req["groupName"] ;
			$is_file_change = $this->req["is_file_change"]; // NEW / DEL / NON
			

			// 삭제함
			if ($is_file_change != "NON")
			{
				$sql = "
					DELETE FROM tbl_file WHERE pa_no = '{$userNo}' AND file_type = '{$this->FILE_TYPE_MEM}'
				";
				$this->update($sql);
			}
			
			// 파일 업로드
			if ($is_file_change == "NEW" && ($_FILES != null && sizeof($_FILES) > 0))
			{
				$updateFileData = $this->inFn_Common_fileSave($_FILES);
				
				$file_vir_name = $updateFileData["file"]["saveURL"];
				$file_org_name = $updateFileData["file"]["name"];
				
				$insFile = Array(
					"file_org_name" => $file_org_name,
					"file_vir_name" => $file_vir_name,
					"reg_dt" => "now()",
					"pa_no" => $userNo,
					"file_type" => $this->FILE_TYPE_MEM
				);
				
				$fileResult = $this->techOfInsertForUpdate("tbl_file", $insFile);
			}
			
			$sql = "
				UPDATE tbl_user
				SET
					name = '{$name}'
					, group_fk = '{$group_fk}'
					, tel = '{$tel}'
				WHERE `no` = '{$userNo}'
			";
			$this->update($sql);
			
			
			
			return $this->makeResultJson("1", "저장되었습니다.", $this->inFn_ApiBase_getInfoOfUser($userNo));
		}

		/**
		 * 회원 사용 포인트 내역 조회
		 * 
		 * @return string
		 */
		function getListOfUserPoint()
		{
			$userNo = $this->appUser["no"];
			
			$this->initPage();
			
			$sql = "
				SELECT COUNT(*)
				FROM tbl_point_trans PT
				JOIN tbl_shop S ON(PT.shop_fk = S.no)
				WHERE PT.user_fk = '{$userNo}' AND PT.trans_type = 'O' AND PT.pay_type = '{$this->PAY_TYPE_USE}'
			";
			
			$this->rownum = $this->getValue($sql, "rn");
			
			$this->setPage($this->rownum);
			
			$sql = "
				SELECT
					PT.*
					, S.name AS shop_name
				FROM tbl_point_trans PT
				JOIN tbl_shop S ON(PT.shop_fk = S.no)
				WHERE PT.user_fk = '{$userNo}' AND PT.trans_type = 'O' AND PT.pay_type = '{$this->PAY_TYPE_USE}'
				ORDER BY PT.no DESC
				LIMIT {$this->startNum}, {$this->endNum}
			";
			
			$list = $this->getArray($sql);
			
			$addData = Array(
				"start_date" => date('Y.m.01', time()),
				"end_date" => date('Y.m', time()) . "." . date('t', time()),
				"avail_point" => $this->inFn_Common_getUserPointBalance($userNo)
			);
			
			if (sizeof($list) > 0)
				return $this->makeResultJson("1", "", $list, $addData);
			else
				return $this->makeResultJson("-1000", "내역이 없습니다.", "", $addData);
		}
		
		/**
		 * 회원 정보 조회
		 */
		function getUserInfo()
		{
			$no			= $this->req["no"];
			
			$userInfo	= $this->inFn_ApiBase_getInfoOfUser($no);
			$addData	= Array("avail_point" => $this->inFn_Common_getUserPointBalance($no));
			
			return $this->makeResultJson("1", "", $userInfo, $addData);
		}
		
		
		
		
		
	} // 클래스 종료
}
?>