<?php

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

	//관리자 변경으로 휴대폰이 바뀌는 경우가 생김
	//각 페이지에서 관리되던 전화번호를 /common/lib/comm.php에서 관리하게 변경
	// $admin_phone = "010-4813-2508";		//SMS 전달 받을 관리자 번호

	$table_name = "sa_master";

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

	$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"]));
	$ds_usertype  = trim(avoid_crack($_POST["ds_usertype"]));
	$ds_level  = trim(avoid_crack($_POST["ds_level"]));
	$nm_company  = trim(avoid_crack($_POST["nm_company"]));
	$nm_name  = trim(avoid_crack($_POST["nm_name"]));
	$nm_birth  = trim(avoid_crack($_POST["nm_birth"]));
	$nm_tel_01  = trim(avoid_crack($_POST["nm_tel_01"]));
	$nm_tel_02  = trim(avoid_crack($_POST["nm_tel_02"]));
	$nm_tel_03  = trim(avoid_crack($_POST["nm_tel_03"]));
	$nm_hp_01  = trim(avoid_crack($_POST["nm_hp_01"]));
	$nm_hp_02  = trim(avoid_crack($_POST["nm_hp_02"]));
	$nm_hp_03  = trim(avoid_crack($_POST["nm_hp_03"]));
	$nm_fax_01  = trim(avoid_crack($_POST["nm_fax_01"]));
	$nm_fax_02  = trim(avoid_crack($_POST["nm_fax_02"]));
	$nm_fax_03  = trim(avoid_crack($_POST["nm_fax_03"]));
	$nm_email  = trim(avoid_crack($_POST["nm_email"]));
	$nm_email_01  = trim(avoid_crack($_POST["nm_email1"]));
	$nm_email_02  = trim(avoid_crack($_POST["nm_email2"]));
	$nm_zip  = trim(avoid_crack($_POST["nm_zip"]));
	$nm_addr  = trim(avoid_crack($_POST["nm_addr"]));
	$nm_addr_sub  = trim(avoid_crack($_POST["nm_addr_sub"]));
	$nm_etc_01  = trim(avoid_crack($_POST["nm_etc_01"]));
	$nm_etc_02  = trim(avoid_crack($_POST["nm_etc_02"]));
	$nm_etc_03  = trim(avoid_crack($_POST["nm_etc_03"]));
	$ds_status  = trim(avoid_crack($_POST["ds_status"]));
	$nm_company_biz  = trim(avoid_crack($_POST["nm_company_biz"]));
	$nm_name_biz  = trim(avoid_crack($_POST["nm_name_biz"]));
	$nm_no_biz  = trim(avoid_crack($_POST["nm_no_biz"]));
	$nm_date_biz  = trim(avoid_crack($_POST["nm_date_biz"]));
	$nm_type_biz  = trim(avoid_crack($_POST["nm_type_biz"]));
	$nm_condition_biz  = trim(avoid_crack($_POST["nm_condition_biz"]));
	$nm_tel_biz_01  = trim(avoid_crack($_POST["nm_tel_biz_01"]));
	$nm_tel_biz_02  = trim(avoid_crack($_POST["nm_tel_biz_02"]));
	$nm_tel_biz_03  = trim(avoid_crack($_POST["nm_tel_biz_03"]));
	$nm_hp_biz_01  = trim(avoid_crack($_POST["nm_hp_biz_01"]));
	$nm_hp_biz_02  = trim(avoid_crack($_POST["nm_hp_biz_02"]));
	$nm_hp_biz_03  = trim(avoid_crack($_POST["nm_hp_biz_03"]));
	$nm_fax_biz_01  = trim(avoid_crack($_POST["nm_fax_biz_01"]));
	$nm_fax_biz_02  = trim(avoid_crack($_POST["nm_fax_biz_02"]));
	$nm_fax_biz_03  = trim(avoid_crack($_POST["nm_fax_biz_03"]));
	$nm_email_biz  = trim(avoid_crack($_POST["nm_email_biz"]));
	$nm_zip_biz  = trim(avoid_crack($_POST["nm_zip_biz"]));
	$nm_addr_biz  = trim(avoid_crack($_POST["nm_addr_biz"]));
	$nm_addr_sub_biz  = trim(avoid_crack($_POST["nm_addr_sub_biz"]));
	$ds_company_bp1 = trim(avoid_crack($_POST["ds_company_bp1"]));
	$ds_branch1 = trim(avoid_crack($_POST["ds_branch1"]));
	$ds_company_bp2 = trim(avoid_crack($_POST["ds_company_bp2"]));
	$ds_branch2 = trim(avoid_crack($_POST["ds_branch2"]));
	$ds_company_bp3 = trim(avoid_crack($_POST["ds_company_bp3"]));
	$ds_branch3 = trim(avoid_crack($_POST["ds_branch3"]));

	$ds_company_bp = trim(avoid_crack($_POST["ds_company_bp"]));
	$ds_branch = trim(avoid_crack($_POST["ds_branch"]));

//	$nm_area  = trim(avoid_crack($_POST["nm_area"]));
if ($mode == "Update"){
	// $nm_area  = trim(avoid_crack(implode(",",$_POST["nm_area"])));
}else{
	$nm_area  = trim(avoid_crack($_POST["nm_area"]));
}
	$nm_title  = trim(avoid_crack($_POST["nm_title"]));
	$nm_file  = trim(avoid_crack($_POST["nm_file"]));
	$nm_etc  = trim(avoid_crack($_POST["nm_etc"]));
	$dt_insert  = trim(avoid_crack($_POST["dt_insert"]));
	$nm_insert  = trim(avoid_crack($_POST["nm_insert"]));
	$dt_update  = trim(avoid_crack($_POST["dt_update"]));
	$nm_update  = trim(avoid_crack($_POST["nm_update"]));
	$ds_delind  = trim(avoid_crack($_POST["ds_delind"]));

	$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"]));

	$s_cd_user = $_SESSION['s_staff_user'];
	$s_cd_userid = $_SESSION['s_staff_userid'];
//	$cd_procid = $_SESSION[admin_cd_dealerid];


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

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

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

		switch($mode) {

			//낙찰하기 AAP
			case "TenderSuccessAAP" :

				$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.*
								, b.nm_model
								, d.nm_brand
								, aap.nm_hp as aap_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
									WHERE s.cd_sale = '$cd_sale'
										AND s.is_staff = 'Y'
										AND s.cd_user = '{$_SESSION['s_staff_user']}'
										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");
				}

				// 낙찰 내역 확인
				$exist_sql = "SELECT * FROM tender_master WHERE cd_sale = '". $cd_sale . "' and ds_status = 'Z0' and ds_delind = 'N' LIMIT 1 ";
				$exist_result  = mysql_query($exist_sql,$connect);
				$exist_col = mysql_fetch_array($exist_result);

				//기존 낙찰된 내역 초기화
				if (!empty($exist_col['cd_tender'])) {
					$cd_tender_old = $exist_col['cd_tender'];

					//이건 다시 확인해 봐야함
					//기존 모든 낙찰자를 변경할지 어떨지
					// $sql="UPDATE tender_master set
					// 		ds_status = 'A0'
					// 		, dt_update = now()
					// 		, nm_update = '$s_cd_userid'
					// 	where cd_tender = '$cd_tender_old' ";
					//
					// $result  = mysql_query($sql,$connect);

					$sql="UPDATE tender_master set
							ds_status = 'A0'
							, dt_update = now()
							, nm_update = '$s_cd_userid'
						where cd_sale = '$cd_sale' ";

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

					if(!$result) {
						throw new Exception("낙찰에 실패 하였습니다.잠시후 다시 시도해 주세요.", "9990");
					}
				}


				//현재 낙찰자 변경
				$sql="UPDATE tender_master set
						ds_status = 'Z0'
						, dt_update = now()
						, nm_update = '$s_cd_userid'
					where cd_tender = '$cd_tender'";
				// echo $sql;
				// exit;
				$result  = mysql_query($sql,$connect);
				if(!$result) {
					throw new Exception("낙찰에 실패 하였습니다.잠시후 다시 시도해 주세요.", "9990");
				}

				//sale_master 변경

				$sql="update sale_master as a
							inner join tender_master as b
							on (
								a.cd_sale = b.cd_sale
								and b.cd_tender = $cd_tender
							)
						set
							a.ds_status = 'Z0'
							, a.dt_success = now()
							, a.nm_price = b.nm_price
							, a.dt_update = now()
							, a.nm_update = '$s_cd_userid'
						";
				//, a.ds_status_contract_step1 = 'Y'
				// echo $sql;
				// exit;
				$result  = mysql_query($sql,$connect);

				if(!$result) {
					throw new Exception("낙찰에 실패 하였습니다.잠시후 다시 시도해 주세요.", "9990");
				}


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

				# 1. 낙찰 AAP에게
				$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['price'] 		= $tender['nm_price'];
				$ALIGO_DATA['vat'] 			= $tender['nm_commission'];
				$ALIGO_DATA['recv_phone'] 	= $sale_col['aap_nm_hp'];

				// print_r($ALIGO_DATA);
				// exit;
				$response = $aligo->send_sa_sell_complete_to_aap($ALIGO_DATA);
				unset($ALIGO_DATA);

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

				# 2. 지정 AAP 에게
				$aap_sql = "SELECT aap.*
								FROM aap_master aap
									WHERE cd_dealer = '{$sale_col['cd_aap_dealer']}'
								LIMIT 1";
				// echo $aap_sql;
				// exit;
				$aap_res = mysql_query($aap_sql);
				$aap_col = mysql_fetch_array($aap_res);
				// print_r($aap_col);
				// exit;


				$ALIGO_DATA = array();
				$ALIGO_DATA['car_brand'] 	= $sale_col['nm_brand'];
				$ALIGO_DATA['car_model'] 	= $sale_col['nm_model'];
				$ALIGO_DATA['price'] 		= $tender['nm_price'];
				$ALIGO_DATA['vat'] 			= $tender['nm_commission'];
				$ALIGO_DATA['recv_phone'] 	= $aap_col['nm_hp'];

				// print_r($ALIGO_DATA);
				// exit;
				$response = $aligo->send_sa_sell_complete_to_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['price'] 		= $tender['nm_ex_vat_price'];
						$ALIGO_DATA['car_brand'] 	= $sale_col['nm_brand'];
						$ALIGO_DATA['car_model'] 	= $sale_col['nm_model'];
						$ALIGO_DATA['recv_phone'] 	= $phone;

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

				// print_r($response);
				// exit;

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

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

			break;

			//거래완료 유카로
			case "TenderEndAAP" :

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

				// $sql="UPDATE tender_master SET
				// 			ds_status = 'Z0'
				// 			, dt_update = now()
				// 			, nm_update = '$s_cd_userid'
				// 		WHERE  cd_tender = $cd_tender";
				//
				// $result  = mysql_query($sql,$connect);



				$sale_sql = "SELECT * FROM sale_master a WHERE cd_sale = '$cd_sale' AND cd_user = '$s_cd_user' AND is_staff = 'Y' 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");
				}
				if(!($sale_col['ds_status_contract_step1'] == "Y" && $sale_col['ds_status_contract_step2'] == "Y" && $sale_col['ds_status_contract_step3'] == "Y" && $sale_col['ds_status_contract_step4'] == "Y")) {
					throw new Exception("거래진행상황이 거래마무리까지 완료되어야 거래완료 처리할 수 있습니다.\n새로고침 후에 이용해 주세요", "9990");
				}

				$tender_sql = "SELECT * FROM tender_master a WHERE a.cd_sale = '".$cd_sale."' and ds_status = 'Z0' 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("낙찰된 AAP가 있을 경우에만 거래완료 처리할 수 있습니다.\n새로고침 후에 이용해 주세요", "9990");
				}

				$dt_end = date("Y-m-d");

				$sql="update sale_master set
							ds_status = 'ZS'
							, ds_aap_status = 'ZS'
							, ds_status_contract_step5 = 'Y'
							, dt_end = '$dt_end'
							, dt_update = now()
							, nm_update = '$s_cd_userid'
						WHERE  cd_sale = $cd_sale";
				// echo $sql;
				// exit;
						//, nm_price = '$nm_price'
				$result  = mysql_query($sql,$connect);
				if(!$result) {
					throw new Exception("거래완료 처리에 실패 하였습니다.잠시후 다시 시도해 주세요.", "9990");
				}

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

			break;





























			//입찰하기
			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_ds_type = $_SESSION['s_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'];

				$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) SELECT  cd_sale,  cd_user,  $s_cd_dealer cd_dealer,  $s_cd_dealer_p cd_dealer_p,  ds_type,  '$s_ds_type' ds_usertype,  '$s_nm_name' nm_name,  '' 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_dealer nm_insert,  now() dt_update,  $s_cd_dealer nm_update,  'N' ds_delind FROM sale_master where cd_sale = '".$cd_sale."'";

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

				if ($result) {
					AlertRedirect("입찰 되었습니다.","dealer_tender_view.php?cd_sale=$cd_sale&ds_status_sale=E0&ds_status=E0");

				 }else{
					AlertRedirect("입찰 실패하였습니다.","dealer_tender_view.php?cd_sale=$cd_sale&ds_status_sale=E0&ds_status=E0");
				 }
			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"]));


				// 낙찰 내역 확인
				$table_name = "tender_master";
				$_whereis = " cd_sale = '". $cd_sale . "' and ds_status = 'Z0' and ds_delind = 'N' ";

				$row = $dbCon->selectDAO("*", $table_name, $_whereis);

				//현재 낙찰된 내역 초기화
				if ($row['cd_tender']) {
					$cd_tender_old = $row['cd_tender'];
					$sql="UPDATE tender_master set
							ds_status = 'A0'
							, dt_update = now()
							, nm_update = '$s_cd_userid'
						where cd_tender = '$cd_tender_old' ";

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

					if ($result) {
					}else{
						echo("N");
						exit;
					}
				}



				$sql="UPDATE tender_master set
						ds_status = 'Z0'
						, dt_update = now()
						, nm_update = '$s_cd_userid'
					where cd_tender = '$cd_tender'";

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

				$sql="update sale_master as a
							inner join tender_master as b
							on (
								a.cd_sale = b.cd_sale
								and b.cd_tender = $cd_tender
							)
						set
							a.ds_status = 'Z0'
							, a.dt_success = now()
							, a.ds_status_contract_step1 = 'Y'
							, a.nm_price = b.nm_price
							, a.dt_update = now()
							, a.nm_update = '$s_cd_userid'
						";
				// echo $sql;
				// exit;
				$result  = mysql_query($sql,$connect);

				$table_name = " car_master a
								inner join sale_master f on (a.cd_car = f.cd_car)
								inner join tender_master t on (t.cd_sale = f.cd_sale and t.cd_tender = '$cd_tender' )
								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)
								left outer join ucaro_master u on (f.cd_ucaro_dealer = u.cd_dealer)
								left outer join sa_master sm on (sm.cd_user = f.cd_user) and f.is_staff = 'Y'";
				$_whereis = "  f.cd_sale = '".$cd_sale."' ";


				//유카로 직원 발송
				//SA 직원과 사용자가 등록한 건은 다르게 처리 한다.
				if($col['is_staff'] == 'Y') {
					$table_name = " sa_master ";
					$_whereis = " cd_user = '".$col[cd_user]."' ";
					$sa_master_info = $dbCon->selectDAO(" nm_hp as nm_hp, nm_name ",$table_name, $_whereis);
				}



				//유카로 직원이 원한 유카로 AAP 발송
				unset($SMS_DATA);

				//희망 SA 에게 메시지 추가 전송
				if($col['is_staff'] == 'Y') {
					$vat_price = "";
					if($col['auction_type'] == 'A') {
						$vat_price = $col[nm_orig_price];
					}
				}

				//신차 직원에게 추가 발송 & 매입상사가 입찰한 경우
				if($col[is_staff] == "Y" && $col[ds_dealer_type] == "B0") {

					$table_name = " sa_master ";
					$_whereis = " cd_user = '".$col[cd_user]."' ";
					$sa_master_info = $dbCon->selectDAO(" nm_hp as nm_hp, nm_name ",$table_name, $_whereis);

					$vat_price = "";
					if($col['auction_type'] == 'A') {
						$vat_price = $col[nm_orig_price];
					}else {
						$vat_price = $col[nm_price];
					}

				}

				if ($result) {
					AlertRedirect("낙찰하기 성공하였습니다.","staff_tender_list.php?cd_sale=$cd_sale&ds_status_sale=Z0&ds_status=Z0");

				 }else{
					 AlertBack("낙찰하기 실패하였습니다.");
					// AlertRedirect("낙찰하기 실패하였습니다.","staff_tender_view.php?cd_sale=$cd_sale&ds_status_sale=Z0&ds_status=Z0");
				 }

				// $sql="update tender_master
				// 		set
				// 			ds_status = 'Z0'
				// 			, dt_update = now()
				// 			, nm_update = '$s_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 = '$s_cd_userid'
				// 		WHERE  cd_sale = $cd_sale";
				//
				// $result  = mysql_query($sql,$connect);
				//
				// if ($result) {
				// 	AlertRedirect("낙찰하기 성공하였습니다.","staff_tender_list.php?cd_sale=$cd_sale&ds_status_sale=Z0&ds_status=Z0");
				// 	// AlertRedirect("낙찰하기 성공하였습니다.","staff_tender_view.php?cd_sale=$cd_sale&ds_status_sale=Z0&ds_status=Z0");
				//
				//  }else{
				// 	 AlertBack("낙찰하기 실패하였습니다.");
				// 	// AlertRedirect("낙찰하기 실패하였습니다.","staff_tender_view.php?cd_sale=$cd_sale&ds_status_sale=Z0&ds_status=Z0");
				//  }
			break;

			//낙찰하기 유카로
			case "TenderSuccessUcaro" :

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

				$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 = 'ZS'
							, ds_ucaro_status = 'ZS'
							, dt_success = now()
							, dt_update = now()
							, nm_update = '$cd_userid'
						WHERE  cd_sale = $cd_sale";
						//, nm_price = '$nm_price'
				$result  = mysql_query($sql,$connect);

				if ($result) {
					AlertRedirect("판매하기 성공하였습니다.","staff_tender_list.php?cd_sale=$cd_sale&ds_status_sale=ZS&ds_status=ZS");

				 }else{
					AlertBack("판매하기 실패하였습니다.");
				 }
			break;

			//낙찰하기
			case "TenderReset" :
				//재경매일 경우 기본 상태를 B0으로 옮기며 모든 데이터르 ㄹ초기화 한다
				//관리자의 승인이 다시 필요함
				$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_delind = 'Y'
				// 			, dt_update = now()
				// 			, nm_update = '$s_cd_userid'
				// 		WHERE  cd_sale = $cd_sale";

				$sql="delete from tender_master
						WHERE  cd_sale = $cd_sale";

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


				$sql="update sale_master
						set
							ds_status = 'B0'
							, nm_price = ''
							, ds_status_contract = NULL
							, nm_contract_date = NULL
							, nm_contract_cont_final = NULL
							, nm_contract_cont_final = NULL
							, nm_contract_fail_reason = NULL
							, ds_status_contract_step1 = NULL
							, ds_status_contract_step2 = NULL
							, ds_status_contract_step3 = NULL
							, ds_status_contract_step4 = NULL

							, 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
							, dt_approve = NULL
							, nm_price_final = ''
							, dt_update = now()
							, ds_dealer_type = NULL
							, nm_update = '$s_cd_userid'
						WHERE  cd_sale = $cd_sale";

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

				if ($result) {
					AlertRedirect("재판매 성공하였습니다.","staff_tender_list.php?ds_status=D0");
					// AlertRedirect("재판매 성공하였습니다.","staff_tender_list.php?ds_status_sale=E0");

				 }else{
					 AlertBack("재판매 실패하였습니다.");
					// AlertRedirect("재판매 실패하였습니다.","staff_tender_view.php?cd_sale=$cd_sale&ds_status_sale=ZE");
				 }
			break;



			//낙찰하기 Nomember
			case "TenderSuccessNomember" :

				$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 = '$s_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 = '$s_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;

			//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"]));

				$sql="update sale_master
						set
							ds_status_contract_step1 = '$ds_status_contract_step1'
							, dt_update = now()
							, nm_update = '$s_cd_userid'
						WHERE  cd_sale = $cd_sale";

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

				if ($result) {
					AlertRedirect("등록 되었습니다.","dealer_tender_view2.php?cd_sale=$cd_sale");
				}else{
					AlertRedirect("등록 실패하였습니다.","dealer_tender_view2.php?cd_sale=$cd_sale");
				}
			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";

				$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_userid'
						WHERE  cd_sale = $cd_sale";

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

				if ($result) {
					AlertRedirect("등록 되었습니다.","dealer_tender_view2.php?cd_sale=$cd_sale");
				}else{
					AlertRedirect("등록 실패하였습니다.","dealer_tender_view2.php?cd_sale=$cd_sale");
				}
			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";

				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){
							AlertBack("첨부파일 업로드 실패 하였습니다.");
							die();
						}
					}
				}

				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){
							AlertBack("첨부파일 업로드 실패 하였습니다.");
							die();
						}
					}
				}

				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){
							AlertBack("첨부파일 업로드 실패 하였습니다.");
							die();
						}
					}
				}

				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){
							AlertBack("첨부파일 업로드 실패 하였습니다.");
							die();
						}
					}
				}

				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){
							AlertBack("첨부파일 업로드 실패 하였습니다.");
							die();
						}
					}
				}

				$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_userid'
						WHERE  cd_sale = $cd_sale";
		//echo $sql;
		//exit;
				$result  = $dbCon->query($sql);

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

			//Contract Step 4
			case "ContractStep4" :

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

				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){
							AlertBack("첨부파일 업로드 실패 하였습니다.");
							die();
						}
					}
				}

				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){
							AlertBack("첨부파일 업로드 실패 하였습니다.");
							die();
						}
					}
				}

				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){
							AlertBack("첨부파일 업로드 실패 하였습니다.");
							die();
						}
					}
				}


				$sql="update sale_master
						set
							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_postscript = case when '$upload_file_name_postscript' = '' then nm_file_postscript else '$upload_file_name_postscript' end
							, 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
							, dt_update = now()
							, nm_update = '$s_cd_userid'
						WHERE  cd_sale = $cd_sale";

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

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

			//후기쓰기
			case "WritePostscript" :

				$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" :

				$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" :

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

				$sql="update sale_master
						set
							ds_status = 'ZE'
							, ds_status_contract_step1 = '$ds_status_contract_step1'
							, nm_cont_tender_error = '$nm_cont_tender_error'
							, dt_update = now()
							, nm_update = '$cd_userid'
						WHERE  cd_sale = $cd_sale";

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

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

			//삭제하기
			case "Delete" :

				$_fields = Array(
							"ds_delind"=>"Y",
							"dt_update" => now(),
							"nm_update" => $cd_procid
						);

				$result  = $dbCon->updateDAO($_fields,$table_name,"cd_dealer='".$cd_dealer."'");


				if ($result) {

					AlertRedirect("삭제 되었습니다.","list.php?PageNo=$PageNo");

				 }else{
					AlertRedirect("삭제 실패하였습니다.","list.php?PageNo=$PageNo");
				 }
			break;

			case "IdChk":

				$_whereis = "  cd_dealerid = '". $cd_dealerid . "'";

				$cnt = $dbCon->getOneDAO("count(*)",$table_name, $_whereis, 1);
				if($cnt==0) {
					echo("Y");
					exit;
				} else {
					echo("N");
					exit;
				}
			break;

			case "IdSearch":

				$_whereis = " ds_delind='N' And nm_name = '". $nm_name . "' AND nm_email = '". $nm_email . "'";

				$userid = $dbCon->getOneDAO("cd_dealerid",$table_name, $_whereis, 1);
				if($userid) {
					echo($userid);
					exit;
				} else {
					echo("");
					exit;
				}
			break;

			case "PwSearch":

				$_whereis = " ds_delind='N' And cd_dealerid = '".$cd_dealerid."' And nm_name = '". $nm_name . "' AND nm_email = '". $nm_email . "'";

				$userid = $dbCon->getOneDAO("cd_dealer",$table_name, $_whereis, 1);
				if($userid) {
					$new_passwd = generatePassword(8);

					$sqlPwd="UPDATE sa_master set nm_pass = password('".$new_passwd."')  where cd_dealer = '".$userid."'";
					$result  = $dbCon->query($sqlPwd);

					echo($new_passwd);
					exit;
				} else {
					echo("");
					exit;
				}
			break;

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

	echo json_encode($RES);
	exit;
?>
