<?php

	include $_SERVER["DOCUMENT_ROOT"].'/common/lib/comm.php';
	include $_SERVER['DOCUMENT_ROOT'].'/common/lib/aligo.php';
	include $_SERVER['DOCUMENT_ROOT'].'/common/aap_chk_m.php';

	$table_name = "aap_master";

	$PageNo = trim(avoid_crack($_REQUEST["PageNo"]));

	$s_cd_dealer 	= $_SESSION['s_cd_dealer'];
	$s_cd_dealer_p 	= $_SESSION['s_cd_dealer_p'];

	$mode = trim(avoid_crack($_POST["mode"]));

	// $cd_dealer  			= trim(avoid_crack($_POST["cd_dealer"]));
	// $cd_dealerid  			= trim(avoid_crack($_POST["cd_dealerid"]));
	// $cd_dealer_p  			= trim(avoid_crack($_POST["cd_dealer_p"]));
	// $nm_pass  				= trim(avoid_crack($_POST["nm_pass"]));
	// $ds_type  				= trim(avoid_crack($_POST["ds_type"]));

	$cd_sale  				= trim(avoid_crack($_POST["cd_sale"]));
	$nm_price  				= trim(avoid_crack($_POST["nm_price"]));
	$nm_score_postscript  	= trim(avoid_crack($_POST["nm_score_postscript"]));
	$nm_cont_postscript  	= trim(avoid_crack($_POST["nm_cont_postscript"]));

    $nm_manager_name  		= trim(avoid_crack($_REQUEST["nm_manager_name"]));
    $nm_manager_tel  		= trim(avoid_crack($_REQUEST["nm_manager_tel"]));

	$nm_contract_date  		= trim(avoid_crack($_REQUEST["nm_contract_date"]));

	$s_cd_dealerid 	= $_SESSION['s_cd_dealerid'];
//	$PageNo = trim(avoid_crack($_POST["PageNo"]));

	$upload_path =  $_SERVER['DOCUMENT_ROOT'].UPLOAD_PATH."aap/";

	$RES = array('CODE'=>'9999', 'MSG'=>'');
	try {

		switch($mode) {
			//입찰하기
			case "Tender" :

				// $s_cd_dealerid 	= $_SESSION['s_cd_dealerid'];
				$s_nm_email 	= $_SESSION['s_nm_email'];
				$s_nm_name 		= $_SESSION['s_nm_name'];
				$s_nm_hp 		= $_SESSION['s_nm_hp'];
				$s_aap_ds_type 		= $_SESSION['s_aap_ds_type'];
				$s_cd_dealer 	= $_SESSION['s_cd_dealer'];
				$s_cd_dealer_p 	= $_SESSION['s_cd_dealer_p'];
				$s_nm_area 		= $_SESSION['s_nm_area'];
				// $nm_price 		= $_REQUEST['nm_price'];

				$nm_price 		= preg_replace("/[^0-9]*/s", "", $nm_price);

				$tender_sql = "SELECT count(*) as cnt FROM tender_master a WHERE a.cd_sale = '".$cd_sale."' and cd_dealer = '$s_cd_dealer' and ds_delind ='N'  LIMIT 1";
				$tender_res = mysql_query($tender_sql);
				$tender_col = mysql_fetch_array($tender_res);

				if($tender_col['cnt'] > 0) {
					throw new Exception("이미 입찰한 차량입니다.", "9990");
				}


				$sale_sql = "SELECT s.*
								, getRemainTime(s.ds_auction_time, s.dt_approve, now()) as time_limit_tender
								, b.nm_model
								, d.nm_brand
								, aap.nm_hp as aap_nm_hp
								, s.nm_hp as user_nm_hp
								, sa.nm_hp as sa_nm_hp
								FROM sale_master s
								INNER JOIN car_master c ON c.cd_car = s.cd_car
								LEFT OUTER JOIN car_model b on (c.cd_model = b.cd_model)
								LEFT OUTER JOIN car_brand d on (c.cd_brand = d.cd_brand)
								LEFT OUTER JOIN aap_master aap on aap.cd_dealer = s.cd_aap_dealer
								LEFT OUTER JOIN sa_master sa on sa.cd_user = s.cd_user
									WHERE cd_sale = '$cd_sale'
										AND s.ds_delind = 'N'
								LIMIT 1";
				// echo $sale_sql;
				// exit;
				$sale_res = mysql_query($sale_sql);
				$sale_col = mysql_fetch_array($sale_res);
				if(empty($sale_col['cd_sale'])) {
					throw new Exception("입찰가능한 차량이 아닙니다.\n새로고침 후에 이용해 주세요", "9990");
				}
				if($sale_col['ds_status'] != "E0") {
					throw new Exception("입찰가능한 차량이 아닙니다.\n새로고침 후에 이용해 주세요", "9989");
				}
				if($sale_col['time_limit_tender'] == "0분") {
					throw new Exception("입찰가능 시간이 종료되었습니다.", "9989");
				}


				$tender_sql = "SELECT * FROM tender_master
									WHERE cd_dealer = '$s_cd_dealer' and cd_sale = '$cd_sale' AND ds_delind = 'N' LIMIT 1";
				$tender_res = mysql_query($tender_sql);
				$tender = mysql_fetch_array($tender_res);

				if(!empty($tender['ds_status'])) {
					throw new Exception("이미 입찰 참여한 차량입니다.", "9990");
				}


				$aap_sql = "SELECT * FROM aap_master
									WHERE cd_dealer = '$s_cd_dealer' LIMIT 1";
				$aap_res = mysql_query($aap_sql);
				$aap = mysql_fetch_array($aap_res);

				if($aap['ds_type'] != "D1") {
					// AlertBack("부관리자만 입찰 수정 할 수 있습니다.");
					throw new Exception("부관리자만 입찰할 수 있습니다.", "9990");
				}

				// print_r($sale_col);
				//SA가 등록한 매물
				//2023-11-12 사용자/SA 모두 딜러수수료, 판매 수수료 책정되게 수정
				// //SA가 등록한 매물
				// if($sale_col['is_staff'] == "Y") {
				// 	$commission = get_sa_aap_commission($nm_price, $sale_col['ds_tradein'], $sale_col['nm_brand'], $sale_col['is_staff']);
				// 	// $nm_ex_vat_price = round((int)$nm_price - ((int)$commission/10000));
				// 	// $nm_ex_vat_price = $commission;
				//
				// 	$user_commission = get_sa_user_commission($nm_price, $sale_col['ds_tradein'], $sale_col['nm_brand'], $sale_col['is_staff']);
				// 	$nm_ex_vat_price = ((int)$nm_price - ceil((int)$user_commission/10000));
				// }
				// //사용자가 등록한 매물
				// else {
				// 	$commission = 0;
				// 	$nm_ex_vat_price = $nm_price;
				// }

				$commission = get_sa_aap_commission($nm_price, $sale_col['ds_tradein'], $sale_col['nm_brand'], $sale_col['is_staff']);
				// $nm_ex_vat_price = round((int)$nm_price - ((int)$commission/10000));
				// $nm_ex_vat_price = $commission;

				$user_commission = get_sa_user_commission($nm_price, $sale_col['ds_tradein'], $sale_col['nm_brand'], $sale_col['is_staff']);
				$nm_ex_vat_price = ((int)$nm_price - ceil((int)$user_commission/10000));


				if($_SERVER['REMOTE_ADDR'] == '220.86.24.199') {
					// echo 'nm_price:'.$nm_price.'<br/>';
					// echo 'ds_tradein:'.$sale_col['ds_tradein'].'<br/>';
					// echo 'nm_brand:'.$sale_col['nm_brand'].'<br/>';
					// echo 'is_staff:'.$sale_col['is_staff'].'<br/>';
					// echo 'commission:'.$commission.'<br/>';
					// echo 'nm_ex_vat_price:'.$nm_ex_vat_price.'<br/>';
					// echo 'nm_user_ex_vat_price:'.$nm_user_ex_vat_price.'<br/>';
					// exit;
				}

				// echo $commission;
				// exit;

				$cur_date = date("Y-m-d H:i:s");
				$limit_date = date("Y-m-d H:i:s", strtotime($sale_col['dt_approve']." + 2 hours"));

				//최고가 계산
				$max_tender_sql = "SELECT max(cast(nm_price as UNSIGNED)) as max_nm_price FROM tender_master
										WHERE cd_sale = '$cd_sale' AND ds_delind = 'N' LIMIT 1";
				$max_tender_res = mysql_query($max_tender_sql);
				$max_tender = mysql_fetch_array($max_tender_res);

				//조건이 4개 여서 분할함
				//최고가가 갱신이 되면 사용자 또는 SA에게 1회 문자 전달
				//입찰 시작시간 2시간 이후 최초 1회만 전달
				// if($_SERVER['REMOTE_ADDR'] == '220.86.24.199') {
				// 	echo 'dt_approve:'.$sale_col['dt_approve'];
				// 	echo 'limit_date:'.$limit_date;
				// 	echo 'cur_date:'.$cur_date;
				// 	echo $sale_col['is_staff'];
				// 	print_r($sale_col);
				// 	exit;
				// }
				// echo 'dt_approve:'.$sale_col['dt_approve'];
				// echo 'limit_date:'.$limit_date;
				// echo 'cur_date:'.$cur_date;
				// echo $sale_col['is_staff'];
				// print_r($sale_col);
				// exit;
				if($limit_date < $cur_date && $sale_col['send_max_price_cnt'] < 1) {
					//기존 입찰자가 있고, 기존 입찰가 보다 가격이 높고,
					if(!empty($max_tender['max_nm_price']) && (int)$max_tender['max_nm_price'] < (int)$nm_price) {
						// send_aap_sell_refresh_to_sa

						// print_r($max_tender);
						// exit;
						# SMS 발송
						# 1. 사용자에게
						$aligo = new Aligo();
						$aligo->getToken();

						$recieve_nm_hp = "";
						if($sale_col['is_staff'] == "Y") {
							$recieve_nm_hp	= $sale_col['sa_nm_hp'];
						}else {
							$recieve_nm_hp	= $sale_col['user_nm_hp'];
						}

						$ALIGO_DATA = array();
						$ALIGO_DATA['seller'] 		= $sale_col['nm_name'];
						$ALIGO_DATA['car_brand'] 	= $sale_col['nm_brand'];
						$ALIGO_DATA['car_model'] 	= $sale_col['nm_model'];
						// $ALIGO_DATA['price'] 		= $nm_price;
						//2023-11-12 수수료 적용금액으로 변경
						$ALIGO_DATA['price'] 		= $nm_ex_vat_price;
						$ALIGO_DATA['recv_phone'] 	= $recieve_nm_hp;

						// print_r($ALIGO_DATA);
						// exit;

						$response = $aligo->send_aap_sell_refresh_to_sa($ALIGO_DATA);
						unset($ALIGO_DATA);

						if($response['code'] != "0") {
							// echo $response['message'];
						}

						$sql = "UPDATE sale_master SET
									send_max_price_cnt = send_max_price_cnt + 1
								WHERE cd_sale = '".$cd_sale."'";
						;
						// echo $sql;
						// exit;
						$result = mysql_query($sql);
					}

				}


				$sql = "INSERT INTO tender_master (
							cd_sale,  cd_user,  cd_dealer,  cd_dealer_p,  ds_type,  ds_usertype,  nm_name
							,  nm_tel,  nm_hp,  nm_email,  nm_price,  nm_cont,  ds_status
							,  dt_insert,  nm_insert,  dt_update,  nm_update,  ds_delind
							, nm_commission, nm_ex_vat_price
						)
						SELECT  cd_sale,  cd_user,  $s_cd_dealer cd_dealer,  $s_cd_dealer_p cd_dealer_p,  ds_type,  '$s_aap_ds_type' ds_usertype,  '$aap[nm_name]'
						,  '$s_nm_hp' nm_tel,  '$s_nm_hp' nm_hp,  '$s_nm_email' nm_email,  $nm_price nm_price, '' nm_cont,  'A0' ds_status
						,  now() dt_insert,  '$s_cd_dealerid' nm_insert,  now() dt_update,  '$s_cd_dealerid' nm_update,  'N' ds_delind
						, '$commission', '$nm_ex_vat_price'
							FROM sale_master where cd_sale = '".$cd_sale."'";
				;
				// echo $sql;
				// exit;
				$result = mysql_query($sql);


				// $result  = $dbCon->query($sql);

				// $sql="update sale_master
				// 		set
				// 			ds_status = 'E0'
				// 			, nm_price = '0'
				// 			, ds_aap_status = 'Z0'
				// 			, dt_update = now()
				// 			, nm_update = '$s_cd_dealerid'
				// 		WHERE  cd_sale = $cd_sale";
				//
				// $result  = mysql_query($sql,$connect);


				if (!$result) {
					throw new Exception("입찰 실패하였습니다.", "9990");

				}

				$RES['CODE'] = "0000";
				$RES['MSG'] = "정상처리.";
			break;

			//낙찰하기
			case "TenderSuccess" :

				$cd_sale 		= trim(avoid_crack($_POST["cd_sale"]));
				$cd_tender 		= trim(avoid_crack($_POST["cd_tender"]));
				$nm_price 		= trim(avoid_crack($_POST["nm_price"]));

				// $sql="update tender_master set
				// 			ds_status = 'Z0'
				// 			, dt_update = now()
				// 			, nm_update = '$cd_userid'
				// 		WHERE  cd_tender = $cd_tender";
				//
				// $result  = mysql_query($sql,$connect);

				$sale_sql = "SELECT * FROM sale_master a WHERE cd_sale = '$cd_sale' LIMIT 1";
				$sale_res = mysql_query($sale_sql);
				$sale_col = mysql_fetch_array($sale_res);

				if(empty($sale_col['cd_sale'])) {
					throw new Exception("낙찰가능한 차량이 아닙니다.\n새로고침 후에 이용해 주세요", "9990");
				}
				if($sale_col['ds_status'] != "Z0") {
					throw new Exception("낙찰가능한 차량이 아닙니다.\n새로고침 후에 이용해 주세요", "9989");
				}

				$tender_sql = "SELECT * FROM tender_master a WHERE a.cd_sale = '".$cd_sale."' and cd_dealer = '$s_cd_dealer' and ds_delind ='N'  LIMIT 1";
				$tender_res = mysql_query($tender_sql);
				$tender_col = mysql_fetch_array($tender_res);

				if(empty($tender_col['cd_tender'])) {
					throw new Exception("입찰한 차량만 낙찰 수락할 수 있습니다.\n새로고침 후에 이용해 주세요", "9990");
				}

				if($tender_col['ds_status'] != "Z0") {
					throw new Exception("사용자가 낙찰한 차량만 낙찰 수락할 수 있습니다.", "9990");
				}
				if($tender_col['ds_lock_status'] == "A0") {
					throw new Exception("관리자가 락을 설정한 상태이므로 낙찰할 수 없습니다.", "9989");
				}

				$aap_sql = "SELECT * FROM aap_master
									WHERE cd_dealer = '$s_cd_dealer' LIMIT 1";
				$aap_res = mysql_query($aap_sql);
				$aap = mysql_fetch_array($aap_res);

				if($aap['ds_type'] != "D1") {
					// AlertBack("부관리자만 입찰 수정 할 수 있습니다.");
					throw new Exception("부관리자만 입찰할 수 있습니다.", "9990");
				}

				$sql="update sale_master set
							ds_status = 'Z0'
							, ds_status_contract = ''
							, ds_status_contract_step1 = 'Y'
							, dt_update = now()
							, nm_update = '$s_cd_dealerid'
						WHERE cd_sale = '".$cd_sale."'  ";
				//, nm_price = '$nm_price'
				// echo $sql;
				// exit;
				$result  = mysql_query($sql,$connect);
				if (!$result) {
					throw new Exception("낙찰에 실패하였습니다.", "9990");
				}

				$RES['CODE'] = "0000";
				$RES['MSG'] = "정상처리.";

				// if ($result) {
				// 	AlertRedirect("낙찰하기 성공하였습니다.","sell_view.php?cd_sale=$cd_sale&ds_status_sale=Z0&ds_status=Z0");
				//
				//  }else{
				// 	AlertRedirect("낙찰하기 실패하였습니다.","sell_view.php?cd_sale=$cd_sale&ds_status_sale=Z0&ds_status=Z0");
				//  }
			break;

			//유찰하기
			case "TenderDrop" :

				$cd_sale 				= trim(avoid_crack($_POST["cd_sale"]));
				$cd_tender 				= trim(avoid_crack($_POST["cd_tender"]));
				$ds_status_contract 	= trim(avoid_crack($_POST["ds_status_contract"]));
				$nm_cont_tender_error 	= addslashes($_POST["nm_cont_tender_error"]);

				// $sql="update tender_master set
				// 			ds_status = 'Z0'
				// 			, dt_update = now()
				// 			, nm_update = '$cd_userid'
				// 		WHERE  cd_tender = $cd_tender";
				//
				// $result  = mysql_query($sql,$connect);


				$tender_sql = "SELECT count(*) as cnt FROM tender_master a WHERE a.cd_sale = '".$cd_sale."' and cd_dealer = '$s_cd_dealer' and ds_delind ='N' AND ds_status = 'Z0' LIMIT 1";
				$tender_res = mysql_query($tender_sql);
				$tender_col = mysql_fetch_array($tender_res);

				if($tender_col['cnt'] < 1) {
					throw new Exception("본인이 낙찰된 차량만 유찰할 수 있습니다.", "9990");
				}

				$sale_sql = "SELECT *
								FROM sale_master s
								WHERE cd_sale = '$cd_sale'
								LIMIT 1";
				// echo $sale_sql;
				// exit;
				$sale_res = mysql_query($sale_sql);
				$sale_col = mysql_fetch_array($sale_res);

				if(empty($sale_col['cd_sale'])) {
					throw new Exception("유찰가능한 차량이 아닙니다.\n새로고침 후에 이용해 주세요", "9990");
				}
				if($sale_col['ds_status'] != "Z0") {
					throw new Exception("유찰가능한 차량이 아닙니다.\n새로고침 후에 이용해 주세요", "9990");
				}

				$aap_sql = "SELECT * FROM aap_master
									WHERE cd_dealer = '$s_cd_dealer' LIMIT 1";
				$aap_res = mysql_query($aap_sql);
				$aap = mysql_fetch_array($aap_res);

				if($aap['ds_type'] != "D1") {
					// AlertBack("부관리자만 입찰 수정 할 수 있습니다.");
					throw new Exception("부관리자만 유찰할 수 있습니다.", "9990");
				}

				$tender_sql = "SELECT * FROM tender_master a WHERE a.cd_sale = '".$cd_sale."' and cd_dealer = '$s_cd_dealer' and ds_delind ='N'  LIMIT 1";
				$tender_res = mysql_query($tender_sql);
				$tender_col = mysql_fetch_array($tender_res);

				if($tender_col['ds_lock_status'] == "A0") {
					throw new Exception("관리자가 락을 설정한 상태이므로 유찰할 수 없습니다.", "9989");
				}

				$sql="update sale_master set
							ds_status = 'ZE'
							, ds_status_contract = '$ds_status_contract'
							, nm_cont_tender_error = '$nm_cont_tender_error'
							, dt_drop = now()
							, dt_update = now()
							, nm_update = '$s_cd_dealerid'
						WHERE cd_sale = '".$cd_sale."' ";
				// echo $sql;
				// exit;
				$result  = mysql_query($sql,$connect);
				if (!$result) {
					throw new Exception("유찰에 실패하였습니다.", "9990");
				}

				$RES['CODE'] = "0000";
				$RES['MSG'] = "정상처리.";

				// if ($result) {
				// 	AlertRedirect("낙찰하기 성공하였습니다.","sell_view.php?cd_sale=$cd_sale&ds_status_sale=Z0&ds_status=Z0");
				//
				//  }else{
				// 	AlertRedirect("낙찰하기 실패하였습니다.","sell_view.php?cd_sale=$cd_sale&ds_status_sale=Z0&ds_status=Z0");
				//  }
			break;

			//금액수정
			case "TenderModify" :


				// $s_aap_ds_type 		= $_SESSION['s_aap_ds_type'];

				$cd_sale 		= trim(avoid_crack($_POST["cd_sale"]));
				$cd_tender 		= trim(avoid_crack($_POST["cd_tender"]));
				$nm_price 		= trim(avoid_crack($_POST["nm_price"]));


				$sale_sql = "SELECT s.*
								, getRemainTime(s.ds_auction_time, s.dt_approve, now()) as time_limit_tender
								, b.nm_model
								, d.nm_brand
								FROM sale_master s
								INNER JOIN car_master c ON c.cd_car = s.cd_car
								LEFT OUTER JOIN car_model b on (c.cd_model = b.cd_model)
								LEFT OUTER JOIN car_brand d on (c.cd_brand = d.cd_brand)
									WHERE cd_sale = '$cd_sale'
										AND s.ds_delind = 'N'
								LIMIT 1";
				// echo $sale_sql;
				// exit;
				$sale_res = mysql_query($sale_sql);
				$sale_col = mysql_fetch_array($sale_res);
				if(empty($sale_col['cd_sale'])) {
					throw new Exception("입찰수정한 차량이 아닙니다.\n새로고침 후에 이용해 주세요", "9990");
				}
				if($sale_col['ds_status'] != "E0") {
					throw new Exception("입찰중인건만 입찰 수정할 수 있습니다.", "9990");
				}


				$aap_sql = "SELECT * FROM aap_master a WHERE cd_dealer = '$s_cd_dealer' LIMIT 1";
				$aap_res = mysql_query($aap_sql);
				$aap = mysql_fetch_array($aap_res);


				$cd_tender_sql = "select cd_tender, nm_modify_cnt, t.dt_insert as first_trade, t.nm_price as old_nm_price
									-- , (select ds_status from sale_master s where s.cd_sale = t.cd_sale) as sale_ds_status
									, (select getRemainTime(s.ds_auction_time, s.dt_approve, now()) from sale_master s where s.cd_sale = t.cd_sale) as time_limit_tender
										from tender_master t
											where t.ds_delind ='N'
												and t.cd_sale = '$cd_sale'
												and t.cd_dealer_p = '$s_cd_dealer_p'
												limit 1";
				// echo $cd_tender_sql;
				// exit;
				//first_trade
				$cd_tender_row = mysql_fetch_array(mysql_query($cd_tender_sql));

				if($aap['ds_type'] != "D1") {
					// AlertBack("부관리자만 입찰 수정 할 수 있습니다.");
					throw new Exception("부관리자만 입찰 수정 할 수 있습니다.", "9990");
				}
				// if($cd_tender_row['sale_ds_status'] != "E0") {
				// 	// AlertBack("입찰중인건만 입찰 수정할 수 있습니다.");
				// 	throw new Exception("입찰중인건만 입찰 수정할 수 있습니다.", "9990");
				// }
				if(empty($cd_tender_row['cd_tender'])) {
					// AlertBack("입찰참여내역이 있는건만 입찰 수정할 수 있습니다.");
					throw new Exception("입찰참여내역이 있는건만 입찰 수정할 수 있습니다.", "9990");
				}
				if($cd_tender_row['nm_modify_cnt'] != 0) {
					// AlertBack("입찰수정은 최대 1번까지만 가능합니다.");
					throw new Exception("입찰수정은 최대 1번까지만 가능합니다.", "9990");
				}

				if($cd_tender_row['time_limit_tender'] == "0분") {
					// AlertBack("입찰가능시간에만 수정할 수 있습니다.");
					//2023-10-17일 입찰 시간은 빼달라고 함
					// throw new Exception("입찰가능시간에만 수정할 수 있습니다.", "9990");
				}
				if($_SESSION['s_ds_status_p'] != "Z0") {
					// AlertBack("승인되지 않은 사용자는 입찰 수정할 수 없습니다");
					throw new Exception("승인되지 않은 AAP는 입찰 수정할 수 없습니다.", "9990");
				}

				//2021-12-27 수정사항
				/*
					딜러 최초입찰시 금액기재후 5분이내는
					최초입찰금액보다 하향만 1회 수정가능

					5분이후에는 1회 금액 수정시에는 상향만 가능입니다.
				*/
				$cur_date = date("YmdHis");
				$standard_date = date("YmdHis", strtotime($cd_tender_row['first_trade']. " +5min"));
				// echo $cur_date.'<br/>';
				// echo $standard_date.'<br/>';
				//+5분의 날짜가 현재 시간 보다 작으면
				//5분 이내일 경우
				// if($standard_date >= $cur_date) {
				// 	//기존 입찰한 금액 보다 현재 입력한 금액이 크면
				// 	if($cd_tender_row['old_nm_price'] < $nm_price) {
				// 		AlertBack("최초 입찰 후 5분이내는 최초입찰금액보다 하향만 가능합니다.");
				// 		throw new Exception("최초 입찰 후 5분이내는 최초입찰금액보다 하향만 가능합니다.", "9990");
				// 	};
				// }else {
				// 	// echo $cd_tender_row['old_nm_price']."<br/>";
				// 	// echo $nm_price."<br/>";
				// 	//기존 입찰한 금액 보다 현재 입력한 금액이 작으면
				// 	if($cd_tender_row['old_nm_price'] > $nm_price) {
				// 		AlertBack("최초 입찰 후 5분이후에는 최초입찰금액보다 상향만 가능합니다.");
				// 		throw new Exception("최초 입찰 후 5분이후에는 최초입찰금액보다 상향만 가능합니다.", "9990");
				// 	};
				// }

				// print_r($sale_col);
				//2023-11-12 사용자/SA 모두 딜러수수료, 판매 수수료 책정되게 수정
				// //SA가 등록한 매물
				// if($sale_col['is_staff'] == "Y") {
				// 	$commission = get_sa_aap_commission($nm_price, $sale_col['ds_tradein'], $sale_col['nm_brand'], $sale_col['is_staff']);
				// 	// $nm_ex_vat_price = round((int)$nm_price - ((int)$commission/10000));
				// 	// $nm_ex_vat_price = $commission;
				//
				// 	$user_commission = get_sa_user_commission($nm_price, $sale_col['ds_tradein'], $sale_col['nm_brand'], $sale_col['is_staff']);
				// 	$nm_ex_vat_price = ((int)$nm_price - ceil((int)$user_commission/10000));
				// }
				// //사용자가 등록한 매물
				// else {
				// 	$commission = 0;
				// 	$nm_ex_vat_price = $nm_price;
				// }

				$commission = get_sa_aap_commission($nm_price, $sale_col['ds_tradein'], $sale_col['nm_brand'], $sale_col['is_staff']);
				// $nm_ex_vat_price = round((int)$nm_price - ((int)$commission/10000));
				// $nm_ex_vat_price = $commission;

				$user_commission = get_sa_user_commission($nm_price, $sale_col['ds_tradein'], $sale_col['nm_brand'], $sale_col['is_staff']);
				$nm_ex_vat_price = ((int)$nm_price - ceil((int)$user_commission/10000));

				// echo $commission;
				// exit;

				// $table_name = " sale_master a";
				// $_whereis = "  a.cd_sale = '".$cd_sale."' and ds_delind ='N' ";
				// $sale = $dbCon->selectDAO("auction_type", $table_name, $_whereis);

				// $price_sql = "";
				// if($sale['auction_type'] == 'A') {
				// 	$price_sql = " , nm_modify_price = '$nm_orig_price' ";
				// 	$price_sql.= " , nm_orig_price = '$nm_orig_price' ";
				// }


				$sql = "UPDATE tender_master SET
							nm_price = '$nm_price'
							, nm_modify_cnt = nm_modify_cnt + 1
							, nm_commission = '$commission'
							, nm_ex_vat_price = '$nm_ex_vat_price'
							, dt_update = now()
							, nm_update = '$s_cd_dealerid'
							$price_sql
						WHERE cd_sale = '".$cd_sale."'
							AND cd_tender = '".$cd_tender."'
							AND cd_dealer = '$s_cd_dealer'  ";
				// echo $sql;
				// exit;
				$result  = mysql_query($sql,$connect);

				if(!$result) {
					throw new Exception("입찰 수정 실패하였습니다.", "9990");
				}

				$RES['CODE'] = "0000";
				$RES['MSG'] = "정상처리.";
			break;




			//Contract Step 1
			case "ContractStep1" :

				$cd_sale 				= trim(avoid_crack($_POST["cd_sale"]));
		//		$cd_tender 				= trim(avoid_crack($_POST["cd_tender"]));
				$ds_status_contract_step1 = trim(avoid_crack($_POST["ds_status_contract_step1"]));

				$sale_sql = "SELECT * FROM sale_master a WHERE cd_sale = '$cd_sale' LIMIT 1";
				$sale_res = mysql_query($sale_sql);
				$sale_col = mysql_fetch_array($sale_res);

				if(empty($sale_col['cd_sale'])) {
					throw new Exception("낙찰한 차량만 수정가능합니다.\n새로고침 후에 이용해 주세요", "9990");
				}
				if($sale_col['ds_status'] != "Z0") {
					throw new Exception("낙찰한 차량만 수정가능합니다.\n새로고침 후에 이용해 주세요", "9990");
				}

				$tender_sql = "SELECT * FROM tender_master a WHERE a.cd_sale = '".$cd_sale."' and cd_dealer = '$s_cd_dealer' and ds_delind ='N'  LIMIT 1";
				$tender_res = mysql_query($tender_sql);
				$tender_col = mysql_fetch_array($tender_res);

				if(empty($tender_col['cd_tender'])) {
					throw new Exception("낙찰한 차량만 수정가능합니다.\n새로고침 후에 이용해 주세요", "9990");
				}

				if($tender_col['ds_status'] != "Z0") {
					throw new Exception("낙찰한 차량만 수정가능합니다.\n새로고침 후에 이용해 주세요", "9990");
				}

				$aap_sql = "SELECT * FROM aap_master
									WHERE cd_dealer = '$s_cd_dealer' LIMIT 1";
				$aap_res = mysql_query($aap_sql);
				$aap = mysql_fetch_array($aap_res);

				if($aap['ds_type'] != "D1") {
					// AlertBack("부관리자만 입찰 수정 할 수 있습니다.");
					throw new Exception("부관리자만 입찰할 수 있습니다.", "9990");
				}

				$sql="UPDATE sale_master SET
							ds_status_contract_step1 = '$ds_status_contract_step1'
							, dt_update = now()
							, nm_update = '$s_cd_dealerid'
						WHERE  cd_sale = $cd_sale";
				// $result  = mysql_query($sql,$connect);

				if (!$result) {
					throw new Exception("등록 실패하였습니다.", "9990");
				}
				$RES['CODE'] = "0000";
				$RES['MSG'] = "정상처리.";

			break;

			//Contract Step 2
			case "ContractStep2" :

				$cd_sale 				= trim(avoid_crack($_POST["cd_sale"]));
		//		$cd_tender 				= trim(avoid_crack($_POST["cd_tender"]));
				$nm_contract_date 		= trim(avoid_crack($_POST["nm_contract_date"]));
				$ds_status_contract_step2 = "Y";


				$sale_sql = "SELECT * FROM sale_master a WHERE cd_sale = '$cd_sale' LIMIT 1";
				$sale_res = mysql_query($sale_sql);
				$sale_col = mysql_fetch_array($sale_res);

				if(empty($sale_col['cd_sale'])) {
					throw new Exception("낙찰한 차량만 수정가능합니다.\n새로고침 후에 이용해 주세요", "9990");
				}
				if($sale_col['ds_status'] != "Z0") {
					throw new Exception("낙찰한 차량만 수정가능합니다.\n새로고침 후에 이용해 주세요", "9990");
				}

				$tender_sql = "SELECT * FROM tender_master a WHERE a.cd_sale = '".$cd_sale."' and cd_dealer = '$s_cd_dealer' and ds_delind ='N'  LIMIT 1";
				$tender_res = mysql_query($tender_sql);
				$tender_col = mysql_fetch_array($tender_res);

				if(empty($tender_col['cd_tender'])) {
					throw new Exception("낙찰한 차량만 수정가능합니다.\n새로고침 후에 이용해 주세요", "9990");
				}

				if($tender_col['ds_status'] != "Z0") {
					throw new Exception("낙찰한 차량만 수정가능합니다.\n새로고침 후에 이용해 주세요", "9990");
				}

				$aap_sql = "SELECT * FROM aap_master
									WHERE cd_dealer = '$s_cd_dealer' LIMIT 1";
				$aap_res = mysql_query($aap_sql);
				$aap = mysql_fetch_array($aap_res);

				if($aap['ds_type'] != "D1") {
					// AlertBack("부관리자만 입찰 수정 할 수 있습니다.");
					throw new Exception("부관리자만 입찰할 수 있습니다.", "9990");
				}


				$sql="UPDATE sale_master SET
							ds_status_contract_step2 = '$ds_status_contract_step2'
							, nm_contract_date = '$nm_contract_date'
							, dt_update = now()
							, nm_update = '$s_cd_dealerid'
						WHERE  cd_sale = $cd_sale";
// echo $sql;
// exit;
				$result  = mysql_query($sql,$connect);

				if (!$result) {
					throw new Exception("등록 실패하였습니다.", "9990");
				}
				$RES['CODE'] = "0000";
				$RES['MSG'] = "정상처리.";

			break;

			//Contract Step 3
			case "ContractStep3" :

				$cd_sale 					= trim(avoid_crack($_POST["cd_sale"]));
		//		$cd_tender = trim(avoid_crack($_POST["cd_tender"]));
				$ds_status_contract 		= trim(avoid_crack($_POST["ds_status_contract"]));
				$nm_price_final 			= trim(avoid_crack($_POST["nm_price_final"]));
				$nm_contract_cont_final 	= trim(avoid_crack($_POST["nm_contract_cont_final"]));
				$nm_contract_fail_reason 	= trim(avoid_crack($_POST["nm_contract_fail_reason"]));
				$ds_status_contract_step3 	= "Y";

				$sale_sql = "SELECT * FROM sale_master a WHERE cd_sale = '$cd_sale' LIMIT 1";
				$sale_res = mysql_query($sale_sql);
				$sale_col = mysql_fetch_array($sale_res);

				if(empty($sale_col['cd_sale'])) {
					throw new Exception("낙찰한 차량만 수정가능합니다.\n새로고침 후에 이용해 주세요", "9990");
				}
				if($sale_col['ds_status'] != "Z0") {
					throw new Exception("낙찰한 차량만 수정가능합니다.\n새로고침 후에 이용해 주세요", "9990");
				}

				$tender_sql = "SELECT * FROM tender_master a WHERE a.cd_sale = '".$cd_sale."' and cd_dealer = '$s_cd_dealer' and ds_delind ='N'  LIMIT 1";
				$tender_res = mysql_query($tender_sql);
				$tender_col = mysql_fetch_array($tender_res);

				if(empty($tender_col['cd_tender'])) {
					throw new Exception("낙찰한 차량만 수정가능합니다.\n새로고침 후에 이용해 주세요", "9990");
				}

				if($tender_col['ds_status'] != "Z0") {
					throw new Exception("낙찰한 차량만 수정가능합니다.\n새로고침 후에 이용해 주세요", "9990");
				}

				$aap_sql = "SELECT * FROM aap_master
									WHERE cd_dealer = '$s_cd_dealer' LIMIT 1";
				$aap_res = mysql_query($aap_sql);
				$aap = mysql_fetch_array($aap_res);

				if($aap['ds_type'] != "D1") {
					// AlertBack("부관리자만 입찰 수정 할 수 있습니다.");
					throw new Exception("부관리자만 입찰할 수 있습니다.", "9990");
				}


				if (is_uploaded_file($_FILES['nm_file_chk1']['tmp_name'])) {
					if($_FILES['nm_file_chk1']['size'] > 0 ){
						$upload_file_name_chk1 = upload($_FILES['nm_file_chk1'],$upload_path."contract_step/".$cd_sale."_detail", 800, array('gif',  'jpeg', 'jpg','png','bmp' ,'ttif'));
						if($upload_file_name_chk1==false){
							throw new Exception("첨부파일 업로드 실패 하였습니다.", "9990");
						}
					}
				}

				if (is_uploaded_file($_FILES['nm_file_chk2']['tmp_name'])) {
					if($_FILES['nm_file_chk2']['size'] > 0 ){
						$upload_file_name_chk2 = upload($_FILES['nm_file_chk2'],$upload_path."contract_step/".$cd_sale."_detail", 800, array('gif',  'jpeg', 'jpg','png','bmp' ,'ttif'));
						if($upload_file_name_chk2==false){
							throw new Exception("첨부파일 업로드 실패 하였습니다.", "9990");
						}
					}
				}

				if (is_uploaded_file($_FILES['nm_file_chk3']['tmp_name'])) {
					if($_FILES['nm_file_chk3']['size'] > 0 ){
						$upload_file_name_chk3 = upload($_FILES['nm_file_chk3'],$upload_path."contract_step/".$cd_sale."_detail", 800, array('gif',  'jpeg', 'jpg','png','bmp' ,'ttif'));
						if($upload_file_name_chk3==false){
							throw new Exception("첨부파일 업로드 실패 하였습니다.", "9990");
						}
					}
				}

				if (is_uploaded_file($_FILES['nm_file_chk4']['tmp_name'])) {
					if($_FILES['nm_file_chk4']['size'] > 0 ){
						$upload_file_name_chk4 = upload($_FILES['nm_file_chk4'],$upload_path."contract_step/".$cd_sale."_detail", 800, array('gif',  'jpeg', 'jpg','png','bmp' ,'ttif'));
						if($upload_file_name_chk4==false){
							throw new Exception("첨부파일 업로드 실패 하였습니다.", "9990");
						}
					}
				}

				if (is_uploaded_file($_FILES['nm_file_chk5']['tmp_name'])) {
					if($_FILES['nm_file_chk5']['size'] > 0 ){
						$upload_file_name_chk5 = upload($_FILES['nm_file_chk5'],$upload_path."contract_step/".$cd_sale."_detail", 800, array('gif',  'jpeg', 'jpg','png','bmp' ,'ttif'));
						if($upload_file_name_chk5==false){
							throw new Exception("첨부파일 업로드 실패 하였습니다.", "9990");
						}
					}
				}

				// $ds_status = "Z0";
				// $ds_aap_status = "Z1";
				// #거래연기, 실패시는 유찰로 보내달라함
				// if($ds_status_contract != "Z0") {
				// 	//해당 딜러 fail_cnt = 1
				// 	// $sql = "update tender_master set
				// 	// 			nm_fail_cnt = 1
				// 	// 			, ds_status = 'ZE'
				// 	// 			, dt_update = now()
				// 	// 			, nm_update = '$s_cd_dealerid'
				// 	// 		where cd_sale = '".$cd_sale."'";
				// 	// 			//cd_dealer = '$s_cd_dealer'
				// 	// // echo $sql;
				// 	// $result  = $dbCon->query($sql);
				// 	//
				// 	// // $add_query = " , ds_status = 'ZE' ";
				// 	// $ds_status = "ZE";
				// 	// $ds_aap_status = "ZE";
				// }
				// print_r($_FILES);
				// exit;

				//거래 연기시 일자 추가
				$add_delay_sql = "";
				if($ds_status_contract == "B0") {
					$add_delay_sql = " , dt_delay = now() ";
				}
				//거래실패시 일자 추가
				$add_fail_sql = "";
				if($ds_status_contract == "C0") {
					$add_fail_sql = " , dt_fail = now() ";
				}
				$sql="UPDATE sale_master SET
							ds_status_contract_step3 = '$ds_status_contract_step3'
							, ds_status_contract = '$ds_status_contract'
							, nm_price_final = '$nm_price_final'
							, nm_contract_cont_final = '$nm_contract_cont_final'
							, nm_contract_fail_reason = '$nm_contract_fail_reason'
							, nm_file_chk1 = case when '$upload_file_name_chk1' = '' then nm_file_chk1 else '$upload_file_name_chk1' end
							, nm_file_chk2 = case when '$upload_file_name_chk2' = '' then nm_file_chk2 else '$upload_file_name_chk2' end
							, nm_file_chk3 = case when '$upload_file_name_chk3' = '' then nm_file_chk3 else '$upload_file_name_chk3' end
							, nm_file_chk4 = case when '$upload_file_name_chk4' = '' then nm_file_chk4 else '$upload_file_name_chk4' end
							, nm_file_chk5 = case when '$upload_file_name_chk5' = '' then nm_file_chk5 else '$upload_file_name_chk5' end
							, dt_update = now()
							, nm_update = '$s_cd_dealerid'
							$add_delay_sql
							$add_fail_sql
							$add_query
						WHERE  cd_sale = $cd_sale";
		// echo $sql;
		// exit;


				$result  = mysql_query($sql,$connect);

				if (!$result) {
					throw new Exception("등록 실패하였습니다.", "9990");
				}
				$RES['CODE'] = "0000";
				$RES['MSG'] = "정상처리.";

			break;

			//Contract Step 4
			case "ContractStep4" :
				//AAP는 단계가 3단계여서 3단계 처리시 최종 완료 처리
				$cd_sale = trim(avoid_crack($_POST["cd_sale"]));
		//		$cd_tender = trim(avoid_crack($_POST["cd_tender"]));
				$ds_status_contract_step4 = "Y";
				$ds_status_contract_step5 = "Y";
				$nm_contract_final_date = date("Y-m-d");

				$sale_sql = "SELECT * FROM sale_master a WHERE cd_sale = '$cd_sale' LIMIT 1";
				$sale_res = mysql_query($sale_sql);
				$sale_col = mysql_fetch_array($sale_res);

				if(empty($sale_col['cd_sale'])) {
					throw new Exception("낙찰한 차량만 수정가능합니다.\n새로고침 후에 이용해 주세요", "9990");
				}
				if($sale_col['ds_status'] != "Z0") {
					throw new Exception("낙찰한 차량만 수정가능합니다.\n새로고침 후에 이용해 주세요", "9990");
				}

				$tender_sql = "SELECT * FROM tender_master a WHERE a.cd_sale = '".$cd_sale."' and cd_dealer = '$s_cd_dealer' and ds_delind ='N'  LIMIT 1";
				$tender_res = mysql_query($tender_sql);
				$tender_col = mysql_fetch_array($tender_res);

				if(empty($tender_col['cd_tender'])) {
					throw new Exception("낙찰한 차량만 수정가능합니다.\n새로고침 후에 이용해 주세요", "9990");
				}

				if($tender_col['ds_status'] != "Z0") {
					throw new Exception("낙찰한 차량만 수정가능합니다.\n새로고침 후에 이용해 주세요", "9990");
				}

				$aap_sql = "SELECT * FROM aap_master
									WHERE cd_dealer = '$s_cd_dealer' LIMIT 1";
				$aap_res = mysql_query($aap_sql);
				$aap = mysql_fetch_array($aap_res);

				if($aap['ds_type'] != "D1") {
					// AlertBack("부관리자만 입찰 수정 할 수 있습니다.");
					throw new Exception("부관리자만 입찰할 수 있습니다.", "9990");
				}

				if (is_uploaded_file($_FILES['nm_file_trading']['tmp_name'])) {
					if($_FILES['nm_file_trading']['size'] > 0 ){
						$upload_file_name_trading = upload($_FILES['nm_file_trading'],$upload_path."contract_step/".$cd_sale."_detail", 800, array('gif',  'jpeg', 'jpg','png','bmp' ,'ttif'));
						if($upload_file_name_trading==false){
							throw new Exception("첨부파일 업로드 실패 하였습니다.", "9990");
						}
					}
				}

				if (is_uploaded_file($_FILES['nm_file_performance']['tmp_name'])) {
					if($_FILES['nm_file_performance']['size'] > 0 ){
						$upload_file_name_performance = upload($_FILES['nm_file_performance'],$upload_path."contract_step/".$cd_sale."_detail", 800, array('gif',  'jpeg', 'jpg','png','bmp' ,'ttif'));
						if($upload_file_name_performance==false){
							throw new Exception("첨부파일 업로드 실패 하였습니다.", "9990");
						}
					}
				}

				if (is_uploaded_file($_FILES['nm_file_regist']['tmp_name'])) {
					if($_FILES['nm_file_regist']['size'] > 0 ){
						$upload_file_name_regist = upload($_FILES['nm_file_regist'],$upload_path."contract_step/".$cd_sale."_detail", 800, array('gif',  'jpeg', 'jpg','png','bmp' ,'ttif'));
						if($upload_file_name_regist==false){
							throw new Exception("첨부파일 업로드 실패 하였습니다.", "9990");
						}
					}
				}

				if (is_uploaded_file($_FILES['nm_file_postscript']['tmp_name'])) {
					if($_FILES['nm_file_postscript']['size'] > 0 ){
						$upload_file_name_postscript = upload($_FILES['nm_file_postscript'],$upload_path."contract_step/".$cd_sale."_detail", 800, array('gif',  'jpeg', 'jpg','png','bmp' ,'ttif'));
						if($upload_file_name_postscript==false){
							throw new Exception("첨부파일 업로드 실패 하였습니다.", "9990");
						}
					}
				}


				$sql="UPDATE sale_master SET
							nm_contract_final_date = '$nm_contract_final_date'
							, ds_status_contract_step4 = '$ds_status_contract_step4'
							, nm_file_trading = case when '$upload_file_name_trading' = '' then nm_file_trading else '$upload_file_name_trading' end
							, nm_file_performance = case when '$upload_file_name_performance' = '' then nm_file_performance else '$upload_file_name_performance' end
							, nm_file_regist = case when '$upload_file_name_regist' = '' then nm_file_regist else '$upload_file_name_regist' end
							, nm_file_postscript = case when '$upload_file_name_postscript' = '' then nm_file_postscript else '$upload_file_name_postscript' end
							, dt_update = now()
							, nm_update = '$s_cd_dealerid'
						WHERE  cd_sale = $cd_sale";
						//, ds_status = case when ds_status_contract = 'Z0' and ds_status_contract_step1 = 'Y' and ds_status_contract_step2 = 'Y' and ds_status_contract_step3 = 'Y' and ds_status_contract_step4 = 'Y' then 'ZS' else ds_status end
						//, ds_status_contract_step5 = '$ds_status_contract_step5'
				// echo $sql;
				// exit;
				$result  = mysql_query($sql,$connect);

				if (!$result) {
					throw new Exception("등록 실패하였습니다.", "9990");
				}

				// if($_SERVER['REMOTE_ADDR'] == '220.86.24.199') {

					$sale_sql = "SELECT s.*
									, c.nm_number
									, c.nm_mileage
									, c.nm_regdate_yyyy
									, c.nm_regdate_mm
									, b.nm_model
									, d.nm_brand
									, aap.nm_hp as aap_nm_hp
									, s.nm_hp as user_nm_hp
									, sa.nm_hp as sa_nm_hp
									FROM sale_master s
									INNER JOIN car_master c on (c.cd_car = s.cd_car)
									LEFT OUTER JOIN car_model b on (c.cd_model = b.cd_model)
									LEFT OUTER JOIN car_brand d on (c.cd_brand = d.cd_brand)
									LEFT OUTER JOIN aap_master aap on aap.cd_dealer = s.cd_aap_dealer
									LEFT OUTER JOIN sa_master sa on sa.cd_user = s.cd_user
										WHERE s.cd_sale = '$cd_sale'
									LIMIT 1";
					// echo $sale_sql;
					// exit;
					$sale_res = mysql_query($sale_sql);
					$sale_col = mysql_fetch_array($sale_res);
					// print_r($sale_col);
					// exit;
					$tender_sql = "SELECT *
									FROM tender_master c
										WHERE cd_sale = '$cd_sale'
											AND ds_status = 'Z0'
									LIMIT 1";
					// echo $sale_sql;
					// exit;
					$tender_res = mysql_query($tender_sql);
					$tender_col = mysql_fetch_array($tender_res);

					// print_r($tender_col);
					// exit;

					if($sale_col['is_staff'] == "Y") {
						$recieve_nm_hp	= $sale_col['sa_nm_hp'];
					}else {
						$recieve_nm_hp	= $sale_col['user_nm_hp'];
					}

					# SMS 발송
					# 1. SA or 사용자에게
					$aligo = new Aligo();
					$aligo->getToken();

					$ALIGO_DATA = array();
					$ALIGO_DATA['car_brand'] 		= $sale_col['nm_brand'];
					$ALIGO_DATA['car_model'] 		= $sale_col['nm_model'];
					$ALIGO_DATA['car_number'] 		= $sale_col['nm_number'];
					$ALIGO_DATA['nm_mileage'] 		= $sale_col['nm_mileage'];
					$ALIGO_DATA['nm_regdate_yyyy'] 	= $sale_col['nm_regdate_yyyy'];
					$ALIGO_DATA['nm_regdate_mm'] 	= $sale_col['nm_regdate_mm'];
					$ALIGO_DATA['tender_price'] 	= $tender_col['nm_price'];
					$ALIGO_DATA['vat_price'] 		= $tender_col['nm_ex_vat_price'];
					$ALIGO_DATA['recv_phone'] 		= $recieve_nm_hp;

					$response = $aligo->send_aap_sell_complete_to_sa($ALIGO_DATA);
					unset($ALIGO_DATA);

					if($response['code'] != "0") {
						// echo $response['message'];
					}

					# 2. 지정 AAP
					//SA 가 올린 매물에만 존재하므로
					if($sale_col['is_staff'] == "Y") {
						$ALIGO_DATA = array();
						$ALIGO_DATA['car_brand'] 		= $sale_col['nm_brand'];
						$ALIGO_DATA['car_model'] 		= $sale_col['nm_model'];
						$ALIGO_DATA['car_number'] 		= $sale_col['nm_number'];
						$ALIGO_DATA['nm_mileage'] 		= $sale_col['nm_mileage'];
						$ALIGO_DATA['nm_regdate_yyyy'] 	= $sale_col['nm_regdate_yyyy'];
						$ALIGO_DATA['nm_regdate_mm'] 	= $sale_col['nm_regdate_mm'];
						$ALIGO_DATA['tender_price'] 	= $tender_col['nm_price'];
						$ALIGO_DATA['vat_price'] 		= $tender_col['nm_ex_vat_price'];
						$ALIGO_DATA['recv_phone'] 		= $sale_col['aap_nm_hp'];

						$response = $aligo->send_aap_sell_complete_to_choice_aap($ALIGO_DATA);
						unset($ALIGO_DATA);

						if($response['code'] != "0") {
							// echo $response['message'];
						}
					}


					# 3. 관리자에게
					foreach($admin_phone as $phone) {
						if(!empty($phone)) {
							$ALIGO_DATA = array();
							$ALIGO_DATA['car_brand'] 		= $sale_col['nm_brand'];
							$ALIGO_DATA['car_model'] 		= $sale_col['nm_model'];
							$ALIGO_DATA['car_number'] 		= $sale_col['nm_number'];
							$ALIGO_DATA['nm_mileage'] 		= $sale_col['nm_mileage'];
							$ALIGO_DATA['nm_regdate_yyyy'] 	= $sale_col['nm_regdate_yyyy'];
							$ALIGO_DATA['nm_regdate_mm'] 	= $sale_col['nm_regdate_mm'];
							$ALIGO_DATA['tender_price'] 	= $tender_col['nm_price'];
							$ALIGO_DATA['vat_price'] 		= $tender_col['nm_ex_vat_price'];
							$ALIGO_DATA['recv_phone'] 		= $phone;

							$response = $aligo->send_aap_sell_complete_to_choice_admin($ALIGO_DATA);
							unset($ALIGO_DATA);
						}
					}
				// }

				$RES['CODE'] = "0000";
				$RES['MSG'] = "정상처리.";

			break;

			//거래연기 -> 거래실패 처리
			case "updateFail" :

				$cd_sale 				= trim(avoid_crack($_POST["cd_sale"]));


				$tender_sql = "SELECT count(*) as cnt FROM tender_master a WHERE a.cd_sale = '".$cd_sale."' and cd_dealer = '$s_cd_dealer' and ds_delind ='N' AND ds_status = 'Z0' LIMIT 1";
				$tender_res = mysql_query($tender_sql);
				$tender_col = mysql_fetch_array($tender_res);

				if($tender_col['cnt'] < 1) {
					throw new Exception("본인이 거래중인 차량만 유찰할 수 있습니다.", "9990");
				}

				$sale_sql = "SELECT *
								FROM sale_master s
								WHERE cd_sale = '$cd_sale'
								LIMIT 1";
				// echo $sale_sql;
				// exit;
				$sale_res = mysql_query($sale_sql);
				$sale_col = mysql_fetch_array($sale_res);

				if(empty($sale_col['cd_sale'])) {
					throw new Exception("거래실패 가능한 차량이 아닙니다.\n새로고침 후에 이용해 주세요", "9990");
				}
				if($sale_col['ds_status'] != "Z0") {
					throw new Exception("거래실패 가능한 차량이 아닙니다.\n새로고침 후에 이용해 주세요", "9990");
				}

				if($sale_col['ds_status_contract'] != "B0") {
					throw new Exception("거래실패 가능한 차량이 아닙니다.\n새로고침 후에 이용해 주세요", "9990");
				}

				$aap_sql = "SELECT * FROM aap_master
									WHERE cd_dealer = '$s_cd_dealer' LIMIT 1";
				$aap_res = mysql_query($aap_sql);
				$aap = mysql_fetch_array($aap_res);

				if($aap['ds_type'] != "D1") {
					// AlertBack("부관리자만 입찰 수정 할 수 있습니다.");
					throw new Exception("부관리자만 유찰할 수 있습니다.", "9990");
				}


				$sql="update sale_master set
							ds_status_contract = 'C0'
							, dt_fail = now()
							, dt_update = now()
							, nm_update = '$s_cd_dealerid'
						WHERE cd_sale = '".$cd_sale."' ";
				// echo $sql;
				// exit;
				$result  = mysql_query($sql,$connect);
				if (!$result) {
					throw new Exception("거래실패처리에 실패하였습니다.", "9990");
				}

				$RES['CODE'] = "0000";
				$RES['MSG'] = "정상처리.";

				// if ($result) {
				// 	AlertRedirect("낙찰하기 성공하였습니다.","sell_view.php?cd_sale=$cd_sale&ds_status_sale=Z0&ds_status=Z0");
				//
				//  }else{
				// 	AlertRedirect("낙찰하기 실패하였습니다.","sell_view.php?cd_sale=$cd_sale&ds_status_sale=Z0&ds_status=Z0");
				//  }
			break;

			//거래연기 -> 거래재개 처리
			case "updateUnderway" :

				$cd_sale 				= trim(avoid_crack($_POST["cd_sale"]));


				$tender_sql = "SELECT count(*) as cnt FROM tender_master a WHERE a.cd_sale = '".$cd_sale."' and cd_dealer = '$s_cd_dealer' and ds_delind ='N' AND ds_status = 'Z0' LIMIT 1";
				$tender_res = mysql_query($tender_sql);
				$tender_col = mysql_fetch_array($tender_res);

				if($tender_col['cnt'] < 1) {
					throw new Exception("본인이 거래중인 차량만 유찰할 수 있습니다.", "9990");
				}

				$sale_sql = "SELECT *
								FROM sale_master s
								WHERE cd_sale = '$cd_sale'
								LIMIT 1";
				// echo $sale_sql;
				// exit;
				$sale_res = mysql_query($sale_sql);
				$sale_col = mysql_fetch_array($sale_res);

				if(empty($sale_col['cd_sale'])) {
					throw new Exception("거래재개 가능한 차량이 아닙니다.\n새로고침 후에 이용해 주세요", "9990");
				}
				if($sale_col['ds_status'] != "Z0") {
					throw new Exception("거래재개 가능한 차량이 아닙니다.\n새로고침 후에 이용해 주세요", "9990");
				}

				if($sale_col['ds_status_contract'] != "B0") {
					throw new Exception("거래재개 가능한 차량이 아닙니다.\n새로고침 후에 이용해 주세요", "9990");
				}

				$aap_sql = "SELECT * FROM aap_master
									WHERE cd_dealer = '$s_cd_dealer' LIMIT 1";
				$aap_res = mysql_query($aap_sql);
				$aap = mysql_fetch_array($aap_res);

				if($aap['ds_type'] != "D1") {
					// AlertBack("부관리자만 입찰 수정 할 수 있습니다.");
					throw new Exception("부관리자만 유찰할 수 있습니다.", "9990");
				}


				$sql="update sale_master set
							ds_status_contract = ''
							, dt_fail = now()
							, dt_update = now()
							, nm_update = '$s_cd_dealerid'
						WHERE cd_sale = '".$cd_sale."' ";
				// echo $sql;
				// exit;
				$result  = mysql_query($sql,$connect);
				if (!$result) {
					throw new Exception("거래재개처리에 실패하였습니다.", "9990");
				}

				$RES['CODE'] = "0000";
				$RES['MSG'] = "정상처리.";

				// if ($result) {
				// 	AlertRedirect("낙찰하기 성공하였습니다.","sell_view.php?cd_sale=$cd_sale&ds_status_sale=Z0&ds_status=Z0");
				//
				//  }else{
				// 	AlertRedirect("낙찰하기 실패하였습니다.","sell_view.php?cd_sale=$cd_sale&ds_status_sale=Z0&ds_status=Z0");
				//  }
			break;

		    case "ContractStepAll":
				exit;
		        $nm_contract_date = trim(avoid_crack($_POST["nm_contract_date"]));
				$nm_price_final = trim(avoid_crack($_POST["nm_price_final"]));

				$table_name = " sale_master";
				$_whereis = "  cd_sale = '".$cd_sale."' ";
				$col = $dbCon->selectDAO(" nm_name, nm_hp, device_uuid, device_os, is_staff, cd_user, ds_aap_confirm ", $table_name, $_whereis);
				//SA직원이 올린 매물과 사용자가 올린 매물의 DB 처리가 달라 분기처리
				if($col['is_staff'] == 'Y') {

					// 다른 AAP 직원이 이미 매입하기 신청 했다면
					if($col['ds_aap_confirm'] != "A0") {
						AlertBack("이미 다른 AAP직원이 매입요청한 상태라 매입할 수 없습니다.");
					}

					//tender master 의 모든 입찰자 기본 상태로 변경
					$sql="update tender_master
							set
								ds_status = 'A0'
								, dt_update = now()
								, nm_update = '$_SESSION[s_cd_dealerid]'
							WHERE  cd_sale = '$cd_sale'";
					$result  = $dbCon->query($sql);
					// echo $sql.'<br/>';

					$sql="update sale_master
							set
								ds_status = 'Z0'
								, nm_price_final = '$nm_price_final'

								, ds_aap_confirm = 'B0'
								, dt_success = now()
								, dt_update = now()
								, nm_update = '$s_cd_dealerid'
							WHERE  cd_sale = '$cd_sale'";

							// , ds_aap_status = 'Z0'
							// ds_status_contract = 'Z0'
							// , ds_status = 'ZS'
							// , ds_aap_status = 'ZS'
							// , nm_contract_date = '$nm_contract_date'
							// , nm_contract_cont_final = '$nm_contract_cont_final'
							// , ds_status_contract_step1 = 'Y'
							// , ds_status_contract_step2 = 'Y'
							// , ds_status_contract_step3 = 'Y'
					// echo $sql;
					// exit;
					$result  = $dbCon->query($sql);

					//tender master 의 본인 낙찰 상태로 변경
					$sql="update tender_master
							set
								ds_status = 'Z0'
								, nm_price = '$nm_price_final'
								, dt_update = now()
								, nm_update = '$_SESSION[s_cd_dealerid]'
							WHERE  cd_sale = '$cd_sale' and cd_dealer = '$s_cd_dealer' ";
					// echo $sql;
					$result  = $dbCon->query($sql);
					// exit;

				}
				//일반 사용자
				else {
					$sql="update sale_master
			                set
			                    nm_price_final = '$nm_price_final'
								, ds_aap_confirm = 'B0'
			                    , dt_update = now()
			                    , nm_update = '$_SESSION[s_cd_dealerid]'
			                WHERE  cd_sale = $cd_sale";
							// ds_status_contract = 'Z0'
							// , ds_status = 'ZS'
							// , ds_aap_status = 'ZS'
							// , nm_contract_date = '$nm_contract_date'
							// , nm_contract_cont_final = '$nm_contract_cont_final'
							// , ds_status_contract_step1 = 'Y'
							// , ds_status_contract_step2 = 'Y'
							// , ds_status_contract_step3 = 'Y'
			    // echo $sql;
			    // exit;
			        $result  = $dbCon->query($sql);

					$sql="update tender_master
			                set
			                    nm_price = '$nm_price_final'
			                    , dt_update = now()
			                    , nm_update = '$_SESSION[s_cd_dealerid]'
			                WHERE  cd_sale = $cd_sale and cd_dealer = '$s_cd_dealer' ";
					$result  = $dbCon->query($sql);
				}

		        if ($result) {


					// AlertRedirect("등록 되었습니다.","aap_tender_list.php?cd_sale=$cd_sale&ds_status=F0&ds_aap_status=Z0");
					AlertRedirect("등록 되었습니다.","aap_tender_list.php?cd_sale=$cd_sale&ds_status=Z0&ds_aap_status=Z1");
					// AlertRedirect("등록 되었습니다.","aap_tender_view.php?cd_sale=$cd_sale&ds_status=ZS&ds_aap_status=ZS");
				}else{
					AlertBack("등록 실패하였습니다.");
					// AlertRedirect("등록 실패하였습니다.","aap_tender_view.php?cd_sale=$cd_sale&ds_status=Z0&ds_aap_status=Z0");
				}
		        break;

		    case "ContractReset":
				exit;
		        $sql="update sale_master
		                set
		                    ds_status_contract = ''
		                    , ds_status_contract_step1 = ''
		                    , ds_status_contract_step2 = ''
		                    , ds_status_contract_step3 = ''
							, ds_status_contract_step4 = NULL
							, ds_status_contract_step5 = NULL
							, nm_contract_date1 = NULL
							, nm_contract_cont1 = NULL
							, nm_contract_price1 = NULL
							, nm_contract_date2 = NULL
							, nm_contract_cont2 = NULL
							, nm_contract_date3 = NULL
							, nm_contract_cont3 = NULL
							, nm_contract_date4 = NULL
							, nm_contract_cont4 = NULL
							, nm_contract_date5 = NULL
							, nm_contract_cont5 = NULL
		                    , nm_price_final = ''
		                    , nm_price = ''
		                    , nm_contract_fail_reason = ''
		                    , nm_contract_date = ''
		                    , nm_contract_cont_final = ''
		                    , dt_update = now()
		                    , ds_status = 'E0'
							, ds_aap_status='E0'
		                    , ds_dealer_type  = 'B0'
		                    , nm_update = '$s_cd_dealerid'
							, nm_file_chk1 = NULL
							, nm_file_chk2 = NULL
							, nm_file_chk3 = NULL
							, nm_file_chk4 = NULL
							, nm_file_chk5 = NULL
							, nm_file_trading = NULL
							, nm_file_performance = NULL
							, nm_cont_tender_error = NULL
		                WHERE  cd_sale = $cd_sale";

				$result  = mysql_query($sql,$connect);

				$sql="delete from tender_master
		                WHERE  cd_sale = $cd_sale
							and cd_dealer = '$s_cd_dealer' ";

				$result  = mysql_query($sql,$connect);
		    // echo $sql;
		    // exit;
		        $result  = $dbCon->query($sql);
		        if ($result) {
		            AlertRedirect("등록 되었습니다.","aap_tender_list.php?ds_status=E0&ds_aap_status=E0");
		        }else{
					AlertBack("등록 실패하였습니다.");
		            // AlertRedirect("등록 실패하였습니다.","aap_tender_list.php?ds_status=E0");
		        }
		        break;
























			case "ContactStep1":
			exit;
				$sql="UPDATE sale_master SET
							ds_status_contract_step1 = 'Y'
							, dt_update = now()
							, nm_update = '$cd_userid'
						WHERE  cd_sale = $cd_sale";
						// echo $sql;
						// exit;
				// $result  = mysql_query($sql,$connect);

				if (!$result) {
					throw new Exception("등록 실패하였습니다.", "9990");
				}
				$RES['CODE'] = "0000";
				$RES['MSG'] = "정상처리.";
				break;
			case "ContactStep2":
			exit;
				$sql = "UPDATE sale_master SET
							ds_status_contract_step2 = 'Y'
							, nm_contract_date = '$nm_contract_date'
							, dt_update = now()
							, nm_update = '$cd_userid'
						WHERE  cd_sale = $cd_sale";
				echo $sql;
				exit;
				$result  = mysql_query($sql,$connect);

				if (!$result) {
					throw new Exception("등록 실패하였습니다.", "9990");
				}

				$RES['CODE'] = "0000";
				$RES['MSG'] = "정상처리.";


				break;
			case "ContactStep3":
			exit;
				$sql="update sale_master
						set ds_status_contract_step3 = 'Y'
							, nm_contract_date3 = '$nm_contract_date3_sale'
							, nm_contract_cont3 = '$nm_contract_cont3_sale'
							, nm_contract_price3 = '$nm_contract_price3_sale'
							, dt_update = now()
							, nm_update = '$cd_userid'
						WHERE  cd_sale = $cd_sale";

				// $result  = mysql_query($sql,$connect);
			// echo $sql;
			// exit;
				$result  = $dbCon->query($sql);

				$s_nm_name = $_SESSION['s_nm_name'];


				$sql="update tender_master
						set nm_contract_insert_date3 = '".time()."'
							, nm_contract_date3 = '$nm_contract_date3_sale'
							, nm_contract_cont3 = '$nm_contract_cont3_sale'
							, nm_contract_price3 = '$nm_contract_price3_sale'
							, dt_update = now()
							, nm_update = '$cd_userid'
						WHERE  cd_tender = $cd_tender";
				// echo $sql;
				// exit;
				// $result  = mysql_query($sql,$connect);
				$result  = $dbCon->query($sql);
				if ($result) {

					$table_name = " car_master a
									inner join sale_master s on s.cd_car = a.cd_car
									left outer join car_model b on (a.cd_model = b.cd_model)
									left outer join car_grade c on (a.cd_grade = c.cd_grade)
									left outer join car_brand d on (a.cd_brand = d.cd_brand)
									left outer join car_model_sub e on (a.cd_model_sub = e.cd_model_sub)";
					$_whereis = "  s.cd_sale = '".$cd_sale."' ";
					$col = $dbCon->selectDAO(" b.nm_model, c.nm_grade, d.nm_brand, e.nm_model_sub, s.nm_hp, s.nm_name", $table_name, $_whereis);

					AlertRedirect("등록 되었습니다.","aap_tender_list.php?ds_status=F0&ds_aap_status=Z0&cd_sale=$cd_sale");
				}else{
					AlertBack("등록 실패하였습니다.");
					// AlertRedirect("등록 실패하였습니다.","aap_tender_list.php?ds_status=E0");
				}
				break;
			case "ContactStep4":
			exit;
				$sql="update sale_master
						set ds_status_contract_step4 = 'Y'
							, nm_contract_date4 = '$nm_contract_date4_sale'
							, nm_contract_cont4 = '$nm_contract_cont4_sale'
							, nm_contract_price4 = '$nm_contract_price4_sale'
							, dt_update = now()
							, nm_update = '$cd_userid'
						WHERE  cd_sale = $cd_sale";

				// $result  = mysql_query($sql,$connect);
			// echo $sql;
			// exit;
				$result  = $dbCon->query($sql);

				$s_nm_name = $_SESSION['s_nm_name'];

				$sql="update tender_master
						set nm_contract_insert_date4 = '".time()."'
							, nm_contract_date4 = '$nm_contract_date4_sale'
							, nm_contract_cont4 = '$nm_contract_cont4_sale'
							, nm_contract_price4 = '$nm_contract_price4_sale'
							, dt_update = now()
							, nm_update = '$cd_userid'
						WHERE  cd_tender = $cd_tender";
				// echo $sql;
				// exit;
				// $result  = mysql_query($sql,$connect);
				$result  = $dbCon->query($sql);
				if ($result) {

					$table_name = " car_master a
									inner join sale_master s on s.cd_car = a.cd_car
									left outer join car_model b on (a.cd_model = b.cd_model)
									left outer join car_grade c on (a.cd_grade = c.cd_grade)
									left outer join car_brand d on (a.cd_brand = d.cd_brand)
									left outer join car_model_sub e on (a.cd_model_sub = e.cd_model_sub)";
					$_whereis = "  s.cd_sale = '".$cd_sale."' ";
					$col = $dbCon->selectDAO(" b.nm_model, c.nm_grade, d.nm_brand, e.nm_model_sub, s.nm_hp, s.nm_name", $table_name, $_whereis);


					AlertRedirect("등록 되었습니다.","aap_tender_list.php?ds_status=F0&ds_aap_status=Z0&cd_sale=$cd_sale");
				}else{
					AlertBack("등록 실패하였습니다.");
					// AlertRedirect("등록 실패하였습니다.","aap_tender_list.php?ds_status=E0");
				}
				break;
			case "ContactStep5":
			exit;
				$sql="update sale_master
						set ds_status_contract_step5 = 'Y'
							, nm_contract_date5 = '$nm_contract_date5_sale'
							, nm_contract_cont5 = '$nm_contract_cont5_sale'
							, nm_contract_price5 = '$nm_contract_price5_sale'
							, dt_update = now()
							, nm_update = '$cd_userid'
						WHERE  cd_sale = $cd_sale";

				// $result  = mysql_query($sql,$connect);
			// echo $sql;
			// exit;
				$result  = $dbCon->query($sql);

				$s_nm_name = $_SESSION['s_nm_name'];

				$sql="update tender_master
						set nm_contract_insert_date5 = '".time()."'
							, nm_contract_date5 = '$nm_contract_date5_sale'
							, nm_contract_cont5 = '$nm_contract_cont5_sale'
							, nm_contract_price5 = '$nm_contract_price5_sale'
							, dt_update = now()
							, nm_update = '$cd_userid'
						WHERE  cd_tender = $cd_tender";
				// echo $sql;
				// exit;
				// $result  = mysql_query($sql,$connect);
				$result  = $dbCon->query($sql);

				if ($result) {

					$table_name = " car_master a
									inner join sale_master s on s.cd_car = a.cd_car
									left outer join car_model b on (a.cd_model = b.cd_model)
									left outer join car_grade c on (a.cd_grade = c.cd_grade)
									left outer join car_brand d on (a.cd_brand = d.cd_brand)
									left outer join car_model_sub e on (a.cd_model_sub = e.cd_model_sub)";
					$_whereis = "  s.cd_sale = '".$cd_sale."' ";
					$col = $dbCon->selectDAO(" b.nm_model, c.nm_grade, d.nm_brand, e.nm_model_sub, s.nm_hp, s.nm_name", $table_name, $_whereis);

					AlertRedirect("등록 되었습니다.","aap_tender_list.php?ds_status=F0&ds_aap_status=Z0&cd_sale=$cd_sale");
				}else{
					AlertBack("등록 실패하였습니다.");
					// AlertRedirect("등록 실패하였습니다.","aap_tender_list.php?ds_status=E0");
				}
				break;

			//낙찰하기 Nomember
			case "TenderSuccessNomember" :
exit;
				$cd_sale = trim(avoid_crack($_POST["cd_sale"]));
				$cd_tender = trim(avoid_crack($_POST["cd_tender"]));
				$nm_price = trim(avoid_crack($_POST["nm_price"]));

				$nm_name = trim(avoid_crack($_POST["nm_name"]));
				$nm_hp = trim(avoid_crack($_POST["nm_hp"]));
				$nm_number = trim(avoid_crack($_POST["nm_number"]));

				$sql="update tender_master
						set
							ds_status = 'Z0'
							, dt_update = now()
							, nm_update = '$cd_userid'
						WHERE  cd_tender = $cd_tender";

				$result  = mysql_query($sql,$connect);


				$sql="update sale_master
						set
							ds_status = 'Z0'
							, nm_price = '$nm_price'
							, dt_update = now()
							, nm_update = '$cd_userid'
						WHERE  cd_sale = $cd_sale";

				$result  = mysql_query($sql,$connect);

				if ($result) {
					AlertRedirect("낙찰하기 성공하였습니다.","/sell/sell_view_nomember.php?nm_name=$nm_name&nm_hp=$nm_hp&nm_number=$nm_number&ds_status_sale=Z0&ds_status=Z0");

				 }else{
					AlertRedirect("낙찰하기 실패하였습니다.","/sell/sell_view_nomember.php?nm_name=$nm_name&nm_hp=$nm_hp&nm_number=$nm_number&ds_status_sale=Z0&ds_status=Z0");
				 }
			break;




			//후기쓰기
			case "WritePostscript" :
exit;
				$cd_sale = trim(avoid_crack($_POST["cd_sale"]));
				$nm_score_postscript = trim(avoid_crack($_POST["nm_score_postscript"]));
				$nm_cont_postscript = trim(avoid_crack($_POST["nm_cont_postscript"]));

				$sql="update sale_master
						set
							nm_score_postscript = '$nm_score_postscript'
							, nm_cont_postscript = '$nm_cont_postscript'
							, dt_update = now()
							, nm_update = '$cd_userid'
						WHERE  cd_sale = $cd_sale";

				$result  = $dbCon->query($sql);

				if ($result) {
					AlertRedirect("등록 되었습니다.","sell_view2.php?cd_sale=$cd_sale");
				}else{
					AlertRedirect("등록 실패하였습니다.","sell_view2.php?cd_sale=$cd_sale");
				}
			break;

			//후기쓰기	Nomember
			case "WritePostscriptNomember" :
exit;
				$cd_sale = trim(avoid_crack($_POST["cd_sale"]));
				$nm_score_postscript = trim(avoid_crack($_POST["nm_score_postscript"]));
				$nm_cont_postscript = trim(avoid_crack($_POST["nm_cont_postscript"]));

				$nm_name = trim(avoid_crack($_POST["nm_name"]));
				$nm_hp = trim(avoid_crack($_POST["nm_hp"]));
				$nm_number = trim(avoid_crack($_POST["nm_number"]));

				$sql="update sale_master
						set
							nm_score_postscript = '$nm_score_postscript'
							, nm_cont_postscript = '$nm_cont_postscript'
							, dt_update = now()
							, nm_update = '$cd_userid'
						WHERE  cd_sale = $cd_sale";

				$result  = $dbCon->query($sql);

				if ($result) {
					AlertRedirect("등록 성공하였습니다.","/sell/sell_view_nomember.php?nm_name=$nm_name&nm_hp=$nm_hp&nm_number=$nm_number&ds_status_sale=Z0&ds_status=Z0");

				 }else{
					AlertRedirect("등록 실패하였습니다.","/sell/sell_view_nomember.php?nm_name=$nm_name&nm_hp=$nm_hp&nm_number=$nm_number&ds_status_sale=Z0&ds_status=Z0");
				 }
			break;

			//Contract Step Error
			case "ContractStepError" :
exit;
				$cd_sale = trim(avoid_crack($_POST["cd_sale"]));
		//		$cd_tender = trim(avoid_crack($_POST["cd_tender"]));
				$nm_contract_fail_reason = trim(avoid_crack($_POST["nm_contract_fail_reason"]));
				$nm_cont_tender_error = trim(avoid_crack($_POST["nm_cont_tender_error"]));
				// $ds_status_contract_step1 = "N";
		        //, ds_status_contract_step1 = '$ds_status_contract_step1'

				//해당 딜러 fail_cnt = 1
				$sql = "update tender_master set
							ds_status = 'ZE'
							, dt_update = now()
							, nm_update = '$s_cd_dealerid'
						where cd_sale = '".$cd_sale."'";
							//cd_dealer = '$s_cd_dealer'
				// echo $sql;
				$result  = $dbCon->query($sql);

				// $add_query = " , ds_status = 'ZE' ";
				$sql="update sale_master
						set
							ds_status = 'ZE'
							, ds_aap_status = 'ZE'
							, ds_status_contract = 'C0'
							, nm_contract_fail_reason = '$nm_cont_tender_error'
							, dt_update = now()
							, nm_update = '$cd_userid'
						WHERE  cd_sale = $cd_sale";

				$result  = $dbCon->query($sql);

				if ($result) {
					AlertRedirect("등록 되었습니다.","aap_tender_list.php?cd_sale=$cd_sale&ds_status=ZE&ds_aap_status=ZE");
					// AlertRedirect("등록 되었습니다.","aap_tender_view.php?cd_sale=$cd_sale&ds_status=ZE&ds_aap_status=ZE");
				}else{
					AlertBack("등록 실패하였습니다.");
					// AlertRedirect("등록 실패하였습니다.","aap_tender_list.php?cd_sale=$cd_sale&ds_status=Z0&ds_aap_status=Z0");
				}
			break;


			default :
				AlertBack("지정되지않은 요청입니다");
			break;
		}
	}catch(Exception $e){
		$RES['CODE'] = $e->getCode();
		$RES['MSG'] = $e->getMessage();
	}
	@mysql_close($connect);

	echo json_encode($RES);
	exit;
?>
