<?php

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


$mode 		= trim($_POST["mode"]);
$cd_procid 	= trim($_SESSION["admin_cd_userid"]);


switch($mode) {

	//입찰 금액 수정
	case "changePrice":
		$RES = array('CODE'=>'9999', 'MSG'=>'');
		try {
			$cd_sale 	= trim($_POST["cd_sale"]);
			$cd_tender 	= trim($_POST["cd_tender"]);
			$nm_price 	= trim($_POST["nm_price"]);
			$nm_ex_vat_price 	= trim($_POST["nm_ex_vat_price"]);
			$nm_manager_price 	= trim($_POST["nm_manager_price"]);


			$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);
			// print_r($sale_col);

			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;
			}

			// exit;
			$sql="UPDATE tender_master set
					nm_price = '$nm_price'
					, nm_commission = '$commission'
					, nm_ex_vat_price = '$nm_ex_vat_price'
					, nm_manager_price = '$nm_manager_price'
					, dt_update = now()
					, nm_update = '$cd_procid'
				where cd_tender = '$cd_tender'";
			// echo $sql;
			// exit;

			// $result  = mysql_query($connect, $sql);
			$result  = mysql_query($sql,$connect);
			if(!$result) {
				throw new Exception("저장에 실패 하였습니다.", "9990");
			}

			$DATAS = array();

			$RES['CODE'] 	= "0000";
			$RES['MSG'] 	= "저장 되었습니다.";
			$RES['DATAS'] 	= $DATAS;
		}catch(Exception $e){
			$RES['CODE'] = $e->getCode();
			$RES['MSG'] = $e->getMessage();
		}
		echo json_encode($RES);
		exit;

	break;

	//관리자 낙찰하기
	case "changeTender":

		$RES = array('CODE'=>'9999', 'MSG'=>'');
		try {
			$cd_sale 	= trim($_POST["cd_sale"]);
			$cd_tender 	= trim($_POST["cd_tender"]);


			// 낙찰 내역 확인
			// $tender_sql = "SELECT t.*
			// 				FROM tender_master t
			// 				WHERE t.cd_sale = '".$cd_sale."'
			// 					AND t.cd_tender = '$cd_tender'
			// 					and ds_status = 'Z0' and ds_delind = 'N'
			// 				LIMIT 1 ";
			// // echo $tender_sql;
			// // exit;
			// $tender_res = mysql_query($connect, $tender_sql);
			// $tender_row = mysql_fetch_assoc($tender_res);
			//
			// print_r($tender_row);
			// exit;
			//현재 낙찰된 내역 초기화
			// if (!empty($tender_row['cd_tender'])) {
				// $cd_tender_old = $tender_row['cd_tender'];
				$sql="UPDATE tender_master set
						ds_status = 'A0'
						, dt_update = now()
						, nm_update = '$cd_procid'
					where cd_sale = '$cd_sale'
						AND ds_status = 'Z0' ";
				// echo $sql;
				// exit;
				$result  = mysql_query($sql,$connect);

				if(!$result) {
					throw new Exception("기존 낙찰자 초기화에 실패 했습니다.", "9990");
				}
			// }
			//낙찰자 업데이트
			$sql="UPDATE tender_master set
					ds_status = 'Z0'
					, dt_update = now()
					, nm_update = '$cd_procid'
				where cd_tender = '$cd_tender'";

			$result  = mysql_query($sql,$connect);
			if(!$result) {
				throw new Exception("낙찰자 선정에 실패 했습니다.", "9990");
			}

			//매물 정보 업데이트
			$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.nm_price = b.nm_price
						, a.ds_status_contract = ''
						, a.ds_status_contract_step1 = 'Y'
						, a.dt_update = now()
						, a.nm_update = '$cd_procid'
						, a.dt_success = now()
					";
// 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.*
								, b.nm_model
								, d.nm_brand
								, aap.nm_hp as aap_nm_hp
								, s.is_staff as is_staff
								, 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'
										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($_SERVER['REMOTE_ADDR'] == '220.86.24.199') {
				// 	echo 'a';
				// 	exit;
				// }

				// print_r($sale_col['cd_sale']);
				// exit;
				if(!empty($sale_col['cd_sale'])) {
					$aligo = new Aligo();
					$aligo->getToken();


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

					# 1. 낙찰 AAP에게


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


					$response = $aligo->send_admin_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_ex_vat_price'];
					$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. 등록자(사용자 or SA)에게 발송
					if($sale_col['is_staff'] == "Y") {
						# 등록자 SA에게 발송

						$ALIGO_DATA = array();
						$ALIGO_DATA['car_brand'] 	= $sale_col['nm_brand'];
						$ALIGO_DATA['car_model'] 	= $sale_col['nm_model'];
						$ALIGO_DATA['price'] 		= $tender['nm_ex_vat_price'];
						$ALIGO_DATA['recv_phone'] 	= $sale_col['sa_nm_hp'];
						// print_r($ALIGO_DATA);
						// exit;
						$response = $aligo->send_admin_sell_complete_to_sa($ALIGO_DATA);
						// print_r($response);
						// exit;
					}else {
						# 등록자 사용자에게 발송

						$ALIGO_DATA = array();
						$ALIGO_DATA['car_brand'] 	= $sale_col['nm_brand'];
						$ALIGO_DATA['car_model'] 	= $sale_col['nm_model'];
						$ALIGO_DATA['price'] 		= $tender['nm_ex_vat_price'];
						$ALIGO_DATA['recv_phone'] 	= $sale_col['user_nm_hp'];
						// print_r($ALIGO_DATA);
						// exit;
						$response = $aligo->send_admin_sell_complete_to_user($ALIGO_DATA);
						// print_r($response);
						// exit;
					}

					# 4. 관리자에게
					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);
						}
					}
				}
			// }

			$DATAS = array();

			$RES['CODE'] 	= "0000";
			$RES['MSG'] 	= "저장 되었습니다.";
			$RES['DATAS'] 	= $DATAS;
		}catch(Exception $e){
			$RES['CODE'] = $e->getCode();
			$RES['MSG'] = $e->getMessage();
		}
		echo json_encode($RES);
		exit;

	break;



	//거래연기 초기화
	case "resetDelay":

		$RES = array('CODE'=>'9999', 'MSG'=>'');
		try {
			$cd_sale 	= trim($_POST["cd_sale"]);
			$cd_tender 	= trim($_POST["cd_tender"]);

			$sql="UPDATE tender_master set
					ds_delind = 'Y'
					, dt_update = now()
					, nm_update = '$cd_procid'
				where cd_tender = '$cd_tender' ";
			// echo $sql;
			// exit;
			$result  = mysql_query($sql,$connect);

			if(!$result) {
				throw new Exception("초기화에 실패 했습니다.", "9990");
			}

			//입찰시간이 지났을거니깐 승인일도 초기화
			$sql="UPDATE sale_master set
					ds_status = 'E0'
					, dt_approve = now()
					, ds_status_contract = ''
					, ds_status_contract_step1 = ''
					, ds_status_contract_step2 = ''
					, ds_status_contract_step3 = ''
					, ds_status_contract_step4 = ''
					, ds_status_contract_step5 = ''
					, nm_file_chk1 = ''
					, nm_file_chk2 = ''
					, nm_file_chk3 = ''
					, nm_file_chk4 = ''
					, nm_file_chk5 = ''
					, nm_contract_fail_reason = ''
					, nm_cont_tender_error = ''
					, nm_contract_date = ''
					, nm_price_final = ''
					, nm_contract_final_date = ''
					, dt_update = now()
					, nm_update = '$cd_procid'
				where cd_sale = '$cd_sale' ";
			// echo $sql;
			// exit;
			$result  = mysql_query($sql,$connect);

			if(!$result) {
				throw new Exception("초기화에 실패 했습니다.", "9990");
			}


			$DATAS = array();

			$RES['CODE'] 	= "0000";
			$RES['MSG'] 	= "저장 되었습니다.";
			$RES['DATAS'] 	= $DATAS;
		}catch(Exception $e){
			$RES['CODE'] = $e->getCode();
			$RES['MSG'] = $e->getMessage();
		}
		echo json_encode($RES);
		exit;

	break;


	//거래실패 초기화
	case "resetFail":

		$RES = array('CODE'=>'9999', 'MSG'=>'');
		try {
			$cd_sale 	= trim($_POST["cd_sale"]);
			$cd_tender 	= trim($_POST["cd_tender"]);


			$sql="UPDATE tender_master set
					ds_delind = 'Y'
					, dt_update = now()
					, nm_update = '$cd_procid'
				where cd_tender = '$cd_tender' ";
			// echo $sql;
			// exit;
			$result  = mysql_query($sql,$connect);

			if(!$result) {
				throw new Exception("초기화에 실패 했습니다.", "9990");
			}

			//입찰시간이 지났을거니깐 승인일도 초기화
			$sql="UPDATE sale_master set
					ds_status = 'E0'
					, dt_approve = now()
					, ds_status_contract = ''
					, ds_status_contract_step1 = ''
					, ds_status_contract_step2 = ''
					, ds_status_contract_step3 = ''
					, ds_status_contract_step4 = ''
					, ds_status_contract_step5 = ''
					, nm_file_chk1 = ''
					, nm_file_chk2 = ''
					, nm_file_chk3 = ''
					, nm_file_chk4 = ''
					, nm_file_chk5 = ''
					, nm_contract_fail_reason = ''
					, nm_cont_tender_error = ''
					, nm_contract_date = ''
					, nm_price_final = ''
					, nm_contract_final_date = ''
					, dt_update = now()
					, nm_update = '$cd_procid'
				where cd_sale = '$cd_sale' ";
			// echo $sql;
			// exit;
			$result  = mysql_query($sql,$connect);

			if(!$result) {
				throw new Exception("초기화에 실패 했습니다.", "9990");
			}


			$DATAS = array();

			$RES['CODE'] 	= "0000";
			$RES['MSG'] 	= "저장 되었습니다.";
			$RES['DATAS'] 	= $DATAS;
		}catch(Exception $e){
			$RES['CODE'] = $e->getCode();
			$RES['MSG'] = $e->getMessage();
		}
		echo json_encode($RES);
		exit;

	break;


	//유찰 초기화
	case "resetDrop":

		$RES = array('CODE'=>'9999', 'MSG'=>'');
		try {
			$cd_sale 	= trim($_POST["cd_sale"]);
			$cd_tender 	= trim($_POST["cd_tender"]);


			$sql="UPDATE tender_master set
					ds_delind = 'Y'
					, dt_update = now()
					, nm_update = '$cd_procid'
				where cd_tender = '$cd_tender' ";
			// echo $sql;
			// exit;
			$result  = mysql_query($sql,$connect);

			if(!$result) {
				throw new Exception("초기화에 실패 했습니다.", "9990");
			}

			//입찰시간이 지났을거니깐 승인일도 초기화
			$sql="UPDATE sale_master set
					ds_status = 'E0'
					, dt_approve = now()
					, ds_status_contract = ''
					, ds_status_contract_step1 = ''
					, ds_status_contract_step2 = ''
					, ds_status_contract_step3 = ''
					, ds_status_contract_step4 = ''
					, ds_status_contract_step5 = ''
					, nm_file_chk1 = ''
					, nm_file_chk2 = ''
					, nm_file_chk3 = ''
					, nm_file_chk4 = ''
					, nm_file_chk5 = ''
					, nm_contract_fail_reason = ''
					, nm_cont_tender_error = ''
					, nm_contract_date = ''
					, nm_price_final = ''
					, nm_contract_final_date = ''
					, dt_update = now()
					, nm_update = '$cd_procid'
				where cd_sale = '$cd_sale' ";
			// echo $sql;
			// exit;
			$result  = mysql_query($sql,$connect);

			if(!$result) {
				throw new Exception("초기화에 실패 했습니다.", "9990");
			}


			$DATAS = array();

			$RES['CODE'] 	= "0000";
			$RES['MSG'] 	= "저장 되었습니다.";
			$RES['DATAS'] 	= $DATAS;
		}catch(Exception $e){
			$RES['CODE'] = $e->getCode();
			$RES['MSG'] = $e->getMessage();
		}
		echo json_encode($RES);
		exit;

	break;


	//매물 유찰하기
	case "dropSale":

		$RES = array('CODE'=>'9999', 'MSG'=>'');
		try {
			$cd_sale 				= trim($_POST["cd_sale"]);
			$nm_cont_tender_error 	= trim($_POST["nm_cont_tender_error"]);

			$sale_sql = "SELECT s.*
							, b.nm_model
							, d.nm_brand
							, aap.nm_hp as aap_nm_hp
							, s.is_staff as is_staff
							, 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'
									AND s.ds_delind = 'N'
							LIMIT 1";
			// echo $sale_sql;
			// exit;
			$sale_res = mysql_query($sale_sql);
			$sale_col = mysql_fetch_array($sale_res);
			// print_r($sale_col);

			// $sale_col['ds_status'] = 'B0';
			if($sale_col['ds_status'] != "E0") {
				throw new Exception("입찰중 상태에서만 유찰시킬수 있습니다.", "9990");
			}

			$nm_cont_tender_error = '관리자에 의한 유찰처리';
			$sql = "update sale_master set
						ds_status = 'ZE'
						, nm_cont_tender_error = '$nm_cont_tender_error'
						, dt_update = now()
						, nm_update = '$cd_procid'
					where cd_sale = '".$cd_sale."'";


			// echo $sql;
			// exit;
			$result  = mysql_query($sql,$connect);

			if(!$result) {
				throw new Exception("유찰에 실패 했습니다.", "9990");
			}

			$DATAS = array();

			$RES['CODE'] 	= "0000";
			$RES['MSG'] 	= "저장 되었습니다.";
			$RES['DATAS'] 	= $DATAS;
		}catch(Exception $e){
			$RES['CODE'] = $e->getCode();
			$RES['MSG'] = $e->getMessage();
		}
		echo json_encode($RES);
		exit;


		break;

	//입찰자 삭제
	case "deleteTender":

		$RES = array('CODE'=>'9999', 'MSG'=>'');
		try {
			$cd_sale 	= trim($_POST["cd_sale"]);
			$cd_tender 	= trim($_POST["cd_tender"]);


			$sql="UPDATE tender_master set
					ds_delind = 'Y'
					, dt_update = now()
					, nm_update = '$cd_procid'
				where cd_tender = '$cd_tender' ";
				// echo $sql;
				// exit;
			$result  = mysql_query($sql,$connect);

			if(!$result) {
				throw new Exception("삭제에 실패 했습니다.", "9990");
			}

			$DATAS = array();

			$RES['CODE'] 	= "0000";
			$RES['MSG'] 	= "정상처리";
			$RES['DATAS'] 	= $DATAS;
		}catch(Exception $e){
			$RES['CODE'] = $e->getCode();
			$RES['MSG'] = $e->getMessage();
		}
		echo json_encode($RES);
		exit;

	break;


	//입찰시간 초기화
	case "resetTime":
		$RES = array('CODE'=>'9999', 'MSG'=>'');
		try {
			$cd_sale 		= trim($_POST["cd_sale"]);

			// 경매정보 확인
			$table_name = "sale_master";
			$_whereis = " cd_sale = '". $cd_sale . "' and ds_delind = 'N' ";

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

			if(empty($row['cd_sale'])) {
				throw new Exception("존재하지 않은 매물입니다.", "9990");
			}

			if($row['ds_status'] != "E0") {
				throw new Exception("입찰중 차량만 초기화 할 수 있습니다.", "9990");
			}

			$sql="UPDATE sale_master set
					dt_approve = now()
					, dt_update = now()
					, nm_update = '$cd_procid'
				where cd_sale = '$cd_sale' ";
				// echo $sql;
				// exit;
			$result  = mysql_query($sql,$connect);

			if(!$result) {
				throw new Exception("초기화에 실패 했습니다.", "9990");
			}

			$DATAS = array();

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

		}catch(Exception $e){
			$RES['CODE'] = $e->getCode();
			$RES['MSG'] = $e->getMessage();
		}
		echo json_encode($RES);
		exit;

	break;

	//입찰시간 및 입찰 내역 초기화
	case "resetTimeHistory":


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

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

			// 경매정보 확인
			$table_name = " sale_master s inner join car_master c on (c.cd_car = s.cd_car ) ";
			$_whereis = " s.cd_sale = '". $cd_sale . "' and s.ds_delind = 'N' ";

			$row = $dbCon->selectDAO("s.*, c.cd_car, c.nm_number", $table_name, $_whereis);

			if(empty($row['cd_sale'])) {
				throw new Exception("존재하지 않은 매물입니다.", "9990");
			}
			if($row['ds_status'] != "E0") {
				throw new Exception("입찰중 차량만 초기화 할 수 있습니다.", "9990");
			}

			//현재 경매 입찰 시간 초기화 내역 초기화
			//카 히스토리 갱신
			// include_once($_SERVER['DOCUMENT_ROOT']."/common/lib/class.carhistory.php");

			$sql="UPDATE sale_master set
					dt_approve = now()
					, dt_update = now()
					, nm_update = '$cd_procid'
				where cd_sale = '$cd_sale' ";

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

			if(!$result) {
				throw new Exception("입찰시간 초기화에 실패 했습니다.", "9990");
			}

			$sql="UPDATE tender_master set
					ds_delind = 'Y'
					, dt_update = now()
					, nm_update = '$cd_procid'
				where cd_sale = '$cd_sale'";
			$result  = mysql_query($sql,$connect);

			if(!$result) {
				throw new Exception("입찰내역 초기화에 실패 했습니다.", "9990");
			}

			$DATAS = array();

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

		}catch(Exception $e){
			$RES['CODE'] = $e->getCode();
			$RES['MSG'] = $e->getMessage();
		}
		echo json_encode($RES);
		exit;



	break;



	//차량정보 수정
	case "changeCarInfo":
		$RES = array('CODE'=>'9999', 'MSG'=>'');
		try {
			$cd_model  			= trim(avoid_crack($_POST["modify_cd_model"]));
			$cd_model_sub  		= trim(avoid_crack($_POST["modify_cd_model_sub"]));
			$cd_grade  			= trim(avoid_crack($_POST["modify_cd_grade"]));
			$cd_brand  			= trim(avoid_crack($_POST["modify_cd_brand"]));
			$cd_category  		= trim(avoid_crack($_POST["modify_cd_category"]));
			$ds_year  			= trim(avoid_crack($_POST["modify_ds_year"]));
			$nm_mileage  		= trim(avoid_crack($_POST["modify_nm_mileage"]));
			$ds_transmission  	= trim(avoid_crack($_POST["modify_ds_transmission"]));
			$ds_oil  			= trim(avoid_crack($_POST["modify_ds_oil"]));
			$nm_gearbox  		= trim(avoid_crack($_POST["modify_nm_gearbox"]));
			$ds_accident  		= trim(avoid_crack($_POST["modify_ds_accident"]));
			$nm_cont_accident  	= trim(avoid_crack($_POST["modify_nm_cont_accident"]));
			$nm_regdate  		= trim(avoid_crack($_POST["modify_nm_regdate"]));
			$nm_price  			= trim(avoid_crack($_POST["modify_nm_price"]));
			$nm_name  			= trim(avoid_crack($_POST["modify_nm_name"]));
			$nm_hp  			= trim(avoid_crack($_POST["modify_nm_hp"]));
			$nm_color 			= trim(avoid_crack($_POST["modify_nm_color"]));
			$nm_incolor 		= trim(avoid_crack($_POST["modify_nm_incolor"]));
			$nm_cc 				= trim(avoid_crack($_POST["modify_nm_cc"]));
			$nm_number 			= trim(avoid_crack($_POST["modify_nm_number"]));
			$nm_cha_number 		= trim(avoid_crack($_POST["modify_nm_cha_number"]));
			$ds_collateral 		= trim(avoid_crack($_POST["modify_ds_collateral"]));
			$nm_able_contact 	= trim(avoid_crack($_POST["modify_nm_able_contact"]));

			$ds_area 			= trim(avoid_crack($_POST["modify_ds_area"]));

			$nm_able_contact 	= trim(avoid_crack($_POST["modify_nm_able_contact"]));

			$nm_regdate_yyyy  	= trim(avoid_crack($_POST["modify_nm_regdate_yyyy"]));
			$nm_regdate_mm  	= trim(avoid_crack($_POST["modify_nm_regdate_mm"]));
			$nm_regdate_dd  	= trim(avoid_crack($_POST["modify_nm_regdate_dd"]));

			$ds_sale_period		= trim(avoid_crack($_POST["modify_ds_sale_period"]));
			$cd_aap_dealer		= trim(avoid_crack($_POST["modify_cd_aap_dealer"]));
			$add_img_delete  	= isset($_POST["add_img_delete"]) ? $_POST["add_img_delete"] : array();


			$ds_tradein  		= trim(avoid_crack($_POST["modify_ds_tradein"]));
			$ds_buy_method  	= trim(avoid_crack($_POST["modify_ds_buy_method"]));
			$ds_auction_time  	= trim(avoid_crack($_POST["modify_ds_auction_time"]));


			$nm_cont 			= addslashes($_POST["modify_nm_cont"]);
			$nm_desc 			= addslashes($_POST["modify_nm_desc"]);
			$nm_guide 			= addslashes($_POST["modify_nm_guide"]);
			$nm_cont_pac 		= addslashes($_POST["modify_nm_cont_pac"]);

			$nm_cont_return 		= addslashes($_POST["modify_nm_cont_return"]);


			$ds_accident_check = addslashes($_POST["modify_ds_accident_check"]);
			$ds_damage_check = addslashes($_POST["modify_ds_damage_check"]);


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



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

			//모델명을 입력하면 모델 테이블에 데이터 등록 후 차량 정보에 반영
			if(!empty($modify_cd_model_text)) {

				$ins_model_sql = "INSERT INTO car_model SET
									cd_category = '$cd_category'
									, cd_brand = '$cd_brand'
									, nm_model = '$modify_cd_model_text'
									, ds_status = 'A0'
									, dt_insert = now()
									, nm_insert = '$cd_procid'
									, dt_update = now()
									, nm_update = '$cd_procid'
									, ds_delind = 'N'
				";


				$ins_model_res  = mysql_query($ins_model_sql,$connect);
				$cd_model  = mysql_insert_id();
				//
				// echo $cd_model;
				// exit;
			}



			$upload_path = $_SERVER['DOCUMENT_ROOT'].UPLOAD_PATH_CAR;

			// $cd_sale = '00991';
			//차량정보
			$sale_sql = "SELECT s.*
							FROM sale_master s
							INNER JOIN car_master c ON c.cd_car = s.cd_car
							WHERE s.cd_sale = '".$cd_sale."'
								AND s.ds_delind = 'N'
							LIMIT 1 ";
			// echo $sale_sql;
			// exit;
			// $sale_res = mysql_query($connect, $sale_sql);

			$sale_res  = mysql_query($sale_sql,$connect);

			$sale_row = mysql_fetch_assoc($sale_res);

			if(empty($sale_row['cd_sale'])) {
				throw new Exception("판매중인 차량이 아닙니다.\n새로고침후에 이용해 주세요.", "9990");
			}

			// $sale_row['ds_status'] = 'Z0';
			// if($sale_row['ds_status'] != "F0") {
			// 	throw new Exception("차량 정보수정은 판매중인 차량만 가능합니다.", "9990");
			// }

			//제조사
			// $car_brand_sql = "SELECT cd_category, nm_brand FROM car_brand m WHERE m.cd_brand = '".$cd_brand."' LIMIT 1 ";
			// $car_brand_res = mysql_query($connect, $car_brand_sql);
			// $car_brand_row = mysql_fetch_assoc($car_brand_res);
			//
			// //모델
			// $car_model_sql = "SELECT nm_model FROM car_model m WHERE m.cd_model = '".$cd_model."' LIMIT 1 ";
			// $car_model_res = mysql_query($connect, $car_model_sql);
			// $car_model_row = mysql_fetch_assoc($car_model_res);
			//
			// //세부모델
			// $car_model_sub_sql = "SELECT nm_model_sub FROM car_model_sub m WHERE m.cd_model_sub = '".$cd_model_sub."' LIMIT 1 ";
			// $car_model_sub_res = mysql_query($connect, $car_model_sub_sql);
			// $car_model_sub_row = mysql_fetch_assoc($car_model_sub_res);
			//
			// //등급
			// $car_grade_sql = "SELECT nm_grade FROM car_grade m WHERE m.cd_grade = '".$cd_grade."' LIMIT 1 ";
			// $car_grade_res = mysql_query($connect, $car_grade_sql);
			// $car_grade_row = mysql_fetch_assoc($car_grade_res);


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

			//추가사진 파일 삭제가 있다면
			if(count($add_img_delete) > 0) {
				foreach($add_img_delete as $cd_file) {
					$delete_sql = "DELETE FROM car_file WHERE cd_file='$cd_file'";
					// echo $delete_sql;
					// echo $delete_sql.'<br/>';
					mysql_query($delete_sql, $connect);
				}
			}
			// echo 'a';
			// exit;


			# 1. 매물정보 업데이트
			// nm_price_exp	= '$sale_master[nm_price_exp]',
			// nm_price_used	= '$sale_master[nm_price_used]',
			//
			//
			// ds_status 		= '$ds_status',
			// ds_area_user 	= '',

			// print_r($_POST);
			// exit;
			$sql="UPDATE sale_master SET
						ds_area 			= '$ds_area'
						, nm_name			= '$nm_name'
						, nm_hp				= '$nm_hp'
						, ds_sale_period	= '$ds_sale_period'
						, cd_aap_dealer		= '$cd_aap_dealer'
						, ds_tradein		= '$ds_tradein'
						, ds_buy_method		= '$ds_buy_method'
						, ds_auction_time	= '$ds_auction_time'
						, nm_cont_return	= '$nm_cont_return'
						, dt_update			= now()
						, nm_update			= '$cd_procid'
					WHERE  cd_sale = '$cd_sale' ";
			// echo $sql;
			// exit;
			// print_r($_POST);
			// exit;

			// $result  = mysql_query($connect, $sql);
			$result  = mysql_query($sql,$connect);
			if(!$result) {
				throw new Exception("저장에 실패 하였습니다.", "9980");
			}

			# 2. 차량정보 업데이트
			//사고유무가 사고가 아니면 사유는 공백으로
			// if($ds_accident != "A0") {
			// 	$nm_cont_accident = "";
			// }
			//차량 검색시 사용할 컬럼
			// $nm_tag = $car_brand_row['nm_brand'].' '.$car_model_row['nm_model'].' '.$car_model_sub_row['nm_model_sub'].' '.$car_grade_row['nm_grade'];

			$sql="UPDATE car_master SET
						cd_model 			= '$cd_model'
						,cd_brand 			= '$cd_brand'
						,ds_year 			= '$ds_year'
						,nm_mileage 		= '$nm_mileage'
						,ds_transmission 	= '$ds_transmission'
						,ds_oil 			= '$ds_oil'
						,nm_color 			= '$nm_color'
						,ds_accident 		= '$ds_accident'
						, ds_accident_check = '$ds_accident_check'
						, ds_damage_check = '$ds_damage_check'
						,nm_name 			= '$nm_name'
						,nm_number 			= '$nm_number'
						,nm_cc 				= '$nm_cc'
						,nm_guide			= '$nm_guide'
						,nm_cont_pac		= '$nm_cont_pac'
						,nm_regdate_yyyy 	= '$nm_regdate_yyyy'
						,nm_regdate_mm 		= '$nm_regdate_mm'
						,nm_regdate_dd 		= '$nm_regdate_dd'
						,ds_open			= 'Y'
						,dt_update 			= now()
						,nm_update 			= '$cd_procid'
					WHERE  cd_car = '{$sale_row['cd_car']}' ";
			// echo $sql;
			// exit;





			// $result  = mysql_query($connect, $sql);
			$result  = mysql_query($sql,$connect);
			if(!$result) {
				throw new Exception("저장에 실패 하였습니다.", "9990");
			}


			//중고차 시세가 있을 경우 만원 단위로 변환
			// if(!empty($nm_price_used)) {
			// 	$nm_price_used = substr($nm_price_used, 0, strlen($nm_price_used)-4);
			// }

			//sale_mater 에 등록될 변수들은 세션에 담는다
			// $sale_master = array(
			// 	"nm_price_exp" 		=> $nm_price_exp,			//차량 희망가
			// 	"nm_able_contact" 	=> $nm_able_contact,		//연락 가능시간
			// 	"nm_price_used" 	=> $nm_price_used,		//중고 시세가
			// );

			# 3. 차량 이미지 변경

			$file_sql = "";
			if(count($_FILES) > 0) {



				$upload_path =  $upload_path.$cd_car."_main/";
				$upload_path_ratio =  $upload_path."ratio/";
				// $upload_path =  $upload_path.$cd_car."_detail/";
				// $upload_path_ratio =  $upload_path."";
				// print_r($_FILES);
				// exit;
				// echo $upload_path;
				// exit;
				//차량전면 이미지 첨부파일 업로드
				$upload_image_info = _upload_car_image($upload_path, $upload_path_ratio, 'modify_nm_file_front', 500, true);
				if($upload_image_info['result'] == false) {
					throw new Exception("첨부파일 업로드 실패 하였습니다.", "9979");
				}
				// print_r($upload_image_info);
				// exit;
				//차량전면 이미지
				if(!empty($upload_image_info['filename'])) {
					$file_sql.= " , nm_file_front = '".$upload_image_info['filename']."' ";
				}

				//운전석 측면 첨부파일 업로드
				$upload_image_info = _upload_car_image($upload_path, $upload_path_ratio, 'modify_nm_file_side1', 500, true);
				if($upload_image_info['result'] == false) {
					throw new Exception("첨부파일 업로드 실패 하였습니다.", "9979");
				}
				//운전석 측면 이미지
				if(!empty($upload_image_info['filename'])) {
					$file_sql.= " , nm_file_side1 = '".$upload_image_info['filename']."' ";
				}

				//조수석 측면 첨부파일 업로드
				$upload_image_info = _upload_car_image($upload_path, $upload_path_ratio, 'modify_nm_file_side2', 500, true);
				if($upload_image_info['result'] == false) {
					throw new Exception("첨부파일 업로드 실패 하였습니다.", "9979");
				}
				//조수석 측면 이미지
				if(!empty($upload_image_info['filename'])) {
					$file_sql.= " , nm_file_side2 = '".$upload_image_info['filename']."' ";
				}

				//차량 후면 첨부파일 업로드
				$upload_image_info = _upload_car_image($upload_path, $upload_path_ratio, 'modify_nm_file_back', 500, true);
				if($upload_image_info['result'] == false) {
					throw new Exception("첨부파일 업로드 실패 하였습니다.", "9979");
				}
				//차량 후면 이미지
				if(!empty($upload_image_info['filename'])) {
					$file_sql.= " , nm_file_back = '".$upload_image_info['filename']."' ";
				}

				//계기판 첨부파일 업로드
				$upload_image_info = _upload_car_image($upload_path, $upload_path_ratio, 'modify_nm_file_dashboard', 500, true);
				if($upload_image_info['result'] == false) {
					throw new Exception("첨부파일 업로드 실패 하였습니다.", "9979");
				}
				//계기판 이미지
				if(!empty($upload_image_info['filename'])) {
					$file_sql.= " , nm_file_dashboard = '".$upload_image_info['filename']."' ";
				}

				if(!empty($file_sql)) {
					//ds_status : 'A0' = 입력중, 'B0' = '입력완료', ...
					$sql="UPDATE car_master SET
								dt_update = now()
								, nm_update = '$cd_procid'
								$file_sql
							WHERE  cd_car = '$cd_car' ";
					// echo $sql;
					// exit;
					// $result  = mysql_query($connect, $sql);
					$result  = mysql_query($sql,$connect);
					if(!$result) {
						throw new Exception("저장에 실패 하였습니다.", "9991");
					}
				}
				# 3.1 차량 추가이미지 변경
				if(isset($_FILES['modify_upload_file']) && count($_FILES['modify_upload_file']) > 0) {
					$upload_files = array();
					for($i=0; $i < 10; $i++) {
						$file_name 		= "";
						$file_type 		= "";
						$file_tmp_name 	= "";
						$file_error 	= "";
						$file_size 		= "";

						//등록된 파일만
						if(isset($_FILES['modify_upload_file']['name'][$i])) {
							$file_name 		= $_FILES['modify_upload_file']['name'][$i];
							$file_type 		= $_FILES['modify_upload_file']['type'][$i];
							$file_tmp_name 	= $_FILES['modify_upload_file']['tmp_name'][$i];
							$file_error 	= $_FILES['modify_upload_file']['error'][$i];
							$file_size 		= $_FILES['modify_upload_file']['size'][$i];
						}


						$upload_files['name'][] 	= $file_name;
						$upload_files['type'][] 	= $file_type;
						$upload_files['tmp_name'][]	= $file_tmp_name;
						$upload_files['error'][] 	= $file_error;
						$upload_files['size'][] 	= $file_size;
					}

					$_FILES['file'] = $upload_files;
				}

				//추가 이미지 등록
				if(isset($_FILES['file']) && count($_FILES['file']) > 0) {
					$file_result = fnSetAdminCarImgCreate($cd_car, $connect);
					if(!$file_result) {
						throw new Exception("파일 업로드에 실패 하였습니다.", "9991");
					}
				}
			}

			//사진 삭제 또는 추가사진을 업로드 한 경우 재정렬
			if((isset($_FILES['modify_upload_file']) && count($_FILES['modify_upload_file']) > 0) || count($add_img_delete) > 0) {
				//순서 재정렬
				$add_file_sql = "SELECT * FROM car_file WHERE cd_car = '$cd_car' and ds_delind='N' Order by no_sort asc,  cd_car ASC ";
				// echo $add_file_sql;
				// $add_file_res = mysql_query($connect, $add_file_sql);
				$add_file_res  = mysql_query($add_file_sql,$connect);
				$sort=0;
				while($imgs = mysql_fetch_array($add_file_res)) {
					$update_sql = "UPDATE car_file SET
									no_sort = '{$sort}'
									WHERE cd_file = '{$imgs['cd_file']}'
					";
					// echo $update_sql.'<br/>';
					// mysql_query($connect, $update_sql);
					$result  = mysql_query($update_sql,$connect);

					$sort++;
				}
			}

			$DATAS = array();

			$RES['CODE'] 	= "0000";
			$RES['MSG'] 	= "저장 되었습니다.";
			$RES['DATAS'] 	= $DATAS;
		}catch(Exception $e){
			$RES['CODE'] = $e->getCode();
			$RES['MSG'] = $e->getMessage();
		}
		echo json_encode($RES);
		exit;
		break;

	//차량 삭제
	case 'deleteCar':
		$RES = array('CODE'=>'9999', 'MSG'=>'');
		try {

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


			if(empty($cd_sale)) {
				throw new Exception("차량 정보가 넘어오지 않았습니다.", "9990");
			}

			$sql="UPDATE sale_master SET
						ds_delind		= 'Y'
						,dt_update 		= now()
						,nm_update 		= '$cd_procid'
					WHERE  cd_sale = '$cd_sale' ";
			// echo $sql;
			// exit;

			// $result  = mysql_query($connect, $sql);
			$result  = mysql_query($sql,$connect);
			if(!$result) {
				throw new Exception("저장에 실패 하였습니다.", "9990");
			}

			$DATAS = array();

			$RES['CODE'] 	= "0000";
			$RES['MSG'] 	= "저장 되었습니다.";
			$RES['DATAS'] 	= $DATAS;
		}catch(Exception $e){
			$RES['CODE'] = $e->getCode();
			$RES['MSG'] = $e->getMessage();
		}
		echo json_encode($RES);
		exit;
		break;

	// //주행거리 수정
	// case "changeCarInfo":
	//
	// 	$cd_userid = trim($_SESSION["admin_cd_userid"]);
	// 	$cd_car = trim($_POST["cd_car"]);
	// 	$cd_sale = trim($_POST["cd_sale"]);
	// 	$nm_mileage = trim($_POST["nm_mileage"]);
	// 	$cd_grade = trim($_POST["cd_grade"]);
	// 	$ds_area = trim($_POST["ds_area"]);
	// 	$ds_accident = trim($_POST["ds_accident"]);
	// 	$nm_guide = trim($_POST["nm_guide"]);
	// 	$nm_cont_accident = trim($_POST["nm_cont_accident"]);
	//
	// 	// 경매정보 확인
	// 	$table_name = "sale_master";
	// 	$_whereis = " cd_sale = '". $cd_sale . "' and ds_delind = 'N' ";
	//
	// 	$sale = $dbCon->selectDAO("*", $table_name, $_whereis);
	// 	//현재 경매 정보가 있을 경우만
	// 	if (empty($sale['cd_sale'])) {
	// 		echo("F");
	// 		exit;
	// 	}
	//
	// 	switch($sale['ds_status']) {
	// 		case "A0":
	// 		case "B0":
	// 		case "C0":
	// 		case "D0":
	// 		case "E0":
	// 		case "F0":
	// 		case "G0":
	// 			break;
	// 		default:
	// 			echo("W");
	// 			exit;
	// 			break;
	// 	}
	//
	// 	// 차량정보 확인
	// 	$table_name = "car_master";
	// 	$_whereis = " cd_car = '". $cd_car . "' and ds_delind = 'N' ";
	//
	// 	$car = $dbCon->selectDAO("*", $table_name, $_whereis);
	// 	//현재 차량 정보가 있을 경우만
	// 	if ($car['cd_car']) {
	// 		$sql="UPDATE car_master set
	// 				nm_mileage = '$nm_mileage'
	// 				, nm_guide = '$nm_guide'
	// 				, cd_grade = '$cd_grade'
	// 				, ds_accident = '$ds_accident'
	// 				, nm_cont_accident = '$nm_cont_accident'
	// 				, dt_update = now()
	// 				, nm_update = '$cd_userid'
	// 			where cd_car = '$cd_car' ";
	// 			// echo $sql;
	// 			// exit;
	//
	// 		$result  = mysql_query($sql,$connect);
	//
	// 		if ($result) {
	// 			$sql="UPDATE sale_master set
	// 				ds_area = '$ds_area'
	// 				, dt_update = now()
	// 				, nm_update = '$cd_userid'
	// 			where cd_sale = '$cd_sale' ";
	// 			// echo $sql;
	// 			// exit;
	// 			$result1  = mysql_query($sql,$connect);
	// 			if ($result1) {
	// 				echo("Y");
	// 				exit;
	// 			}else {
	// 				echo("N");
	// 				exit;
	// 			}
	//
	// 		}else{
	// 			echo("N");
	// 			exit;
	// 		}
	// 	}else {
	// 		echo("F");
	// 		exit;
	// 	}
	//
	// break;

	case "ContractStep2" :
		$RES = array('CODE'=>'9999', 'MSG'=>'');
		try {
			$cd_sale 			= trim(avoid_crack($_POST["cd_sale"]));
			$nm_contract_date 	= trim(avoid_crack($_POST["nm_contract_date"]));
			$ds_status_contract_step2 = "Y";

			if(empty($cd_sale)) {
				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 = '$cd_procid'
					WHERE  cd_sale = $cd_sale";
			// echo $sql;
			// exit;
			$result  = mysql_query($sql,$connect);

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

			$DATAS = array();

			$RES['CODE'] 	= "0000";
			$RES['MSG'] = "정상처리.";
			$RES['DATAS'] 	= $DATAS;
		}catch(Exception $e){
			$RES['CODE'] = $e->getCode();
			$RES['MSG'] = $e->getMessage();
		}
		echo json_encode($RES);
		exit;
	break;

	//Contract Step 3
	case "ContractStep3" :

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

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

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


			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 = '$cd_procid'
						$add_delay_sql
						$add_fail_sql
						$add_query
					WHERE  cd_sale = $cd_sale";
		// if($_SERVER['REMOTE_ADDR'] == '220.86.24.199') {
		// 	echo $sql;
		// 	exit;
		// }


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

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

			$DATAS = array();

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

		}catch(Exception $e){
			$RES['CODE'] = $e->getCode();
			$RES['MSG'] = $e->getMessage();
		}
		echo json_encode($RES);
		exit;



	break;
	//검차 결과 /계약상황 입력하기
	//상사이전증
	case "ContractStep4" :

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

			$cd_sale 			= trim(avoid_crack($_POST["cd_sale"]));
			$cd_userid 			= trim($_SESSION["admin_cd_userid"]);
			$ds_status_contract_step4 = "Y";


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

			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
						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 = '$cd_procid'
					WHERE  cd_sale = $cd_sale";
			// echo $sql;
			// exit;
			// if($_SERVER['REMOTE_ADDR'] == '220.86.24.199') {
			// 	echo $sql;
			// 	exit;
			// }
			$result  = mysql_query($sql,$connect);

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

			$DATAS = array();

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

		}catch(Exception $e){
			$RES['CODE'] = $e->getCode();
			$RES['MSG'] = $e->getMessage();
		}
		echo json_encode($RES);
		exit;

	break;

	//거래완료 강제 처리
	case "ContractStep5" :
		$RES = array('CODE'=>'9999', 'MSG'=>'');
		try {
			$cd_sale 				= trim(avoid_crack($_POST["cd_sale"]));
			// $nm_contract_final_date = trim(avoid_crack($_POST["nm_contract_final_date"]));
			$dt_end 				= trim(avoid_crack($_POST["dt_end"]));
			$ds_status_contract_step5 = 'Y';

			if(empty($cd_sale)) {
				throw new Exception("차량 정보가 넘어오지 않았습니다.", "9990");
			}


			$sql="update sale_master set
						ds_status = 'ZS'
						, dt_end = '$dt_end'
						, ds_status_contract_step5 = '$ds_status_contract_step5'
						, dt_update = now()
						, nm_update = '$cd_procid'
					WHERE  cd_sale = $cd_sale";
			// echo $sql;
			// exit;
			$result  = mysql_query($sql,$connect);

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

			$DATAS = array();

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

		}catch(Exception $e){
			$RES['CODE'] = $e->getCode();
			$RES['MSG'] = $e->getMessage();
		}
		echo json_encode($RES);
		exit;
		//
		// $cd_sale = trim(avoid_crack($_POST["cd_sale"]));
		// $nm_contract_date = trim(avoid_crack($_POST["nm_contract_force_date"]));
		// $cd_userid = trim($_SESSION["admin_cd_userid"]);
		//
		// $sql="update sale_master
		// 		set
		// 			ds_status = 'ZS'
		// 			, nm_contract_date = '$nm_contract_date'
		// 			, dt_update = now()
		// 			, nm_update = '$cd_procid'
		// 		WHERE  cd_sale = $cd_sale";
		// // echo $sql;
		// // exit;
		// $result  = $dbCon->query($sql);
		//
		// if ($result) {
		// 	AlertRedirect("등록 되었습니다.","buy_view.php?list_url=$list_url&ds_status_sale=$ds_status_sale&cd_sale=$cd_sale&ds_status_contract_sale=$ds_status_contract_sale&ds_status_contract_step1_sale=$ds_status_contract_step1_sale&ListPageNo=$ListPageNo");
		// }else{
		// 	AlertBack("등록 실패하였습니다.");
		// }
	break;

	//거래완료일 변경
	case "ContractStep5Modify" :
		exit;
		// $cd_sale = trim(avoid_crack($_POST["cd_sale"]));
		// $nm_contract_date = trim(avoid_crack($_POST["nm_contract_force_date"]));
		// $cd_userid = trim($_SESSION["admin_cd_userid"]);
		//
		// $sql="update sale_master
		// 		set
		// 			nm_contract_date = '$nm_contract_date'
		// 			, dt_update = now()
		// 			, nm_update = '$cd_userid'
		// 		WHERE  cd_sale = $cd_sale";
		// // echo $sql;
		// // exit;
		// $result  = $dbCon->query($sql);
		//
		// if ($result) {
		// 	AlertRedirect("변경 되었습니다.","buy_view.php?list_url=$list_url&ds_status_sale=$ds_status_sale&cd_sale=$cd_sale&ds_status_contract_sale=$ds_status_contract_sale&ds_status_contract_step1_sale=$ds_status_contract_step1_sale&ListPageNo=$ListPageNo");
		// }else{
		// 	AlertBack("변경 실패하였습니다.");
		// }
	break;





	//상사이전증, 성능지, 거래후기 사진 수정
	case "ContractStep4Modify" :

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

			$cd_sale 			= trim(avoid_crack($_POST["cd_sale"]));
			$cd_userid 			= trim($_SESSION["admin_cd_userid"]);
			$ds_status_contract_step4 = "Y";


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

			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_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 = '$cd_procid'
					WHERE  cd_sale = $cd_sale";
			// echo $sql;
			// exit;
			//
			// if($_SERVER['REMOTE_ADDR'] == '220.86.24.199') {
			// 	echo $sql;
			// 	exit;
			// }
			$result  = mysql_query($sql,$connect);

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

			$DATAS = array();

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

		}catch(Exception $e){
			$RES['CODE'] = $e->getCode();
			$RES['MSG'] = $e->getMessage();
		}
		echo json_encode($RES);
		exit;

	break;



	//차량 필수 사진 변경
	case "CarImageModify" :
		exit;
		// $cd_car = trim(avoid_crack($_POST["cd_car"]));
		// $cd_sale = trim(avoid_crack($_POST["cd_sale"]));
		//
		// $cd_userid = trim($_SESSION["admin_cd_userid"]);
		//
		// $upload_path = $_SERVER['DOCUMENT_ROOT'].UPLOAD_PATH_CAR;
		// $upload_path_ratio =  $upload_path."nm_file_main/ratio/";
		//
		// // print_r($_POST);
		// // print_r($_FILES);
		// // exit;
		//
		// if (is_uploaded_file($_FILES['nm_file_front']['tmp_name'])) {
		// 	if($_FILES['nm_file_front']['size'] > 0 ){
		// 		$upload_file_front_name = upload($_FILES['nm_file_front'],$upload_path."nm_file_main/", 500, array('gif',  'jpeg', 'jpg','png','bmp' ,'ttif'));
		//
		// 		if($upload_file_front_name==false){
		// 			AlertBack("첨부파일 업로드 실패 하였습니다.");
		// 			die();
		// 		}
		//
		// 		$thumb_front = array(
		// 					'o_path' => $upload_path.'nm_file_main/'.$upload_file_front_name, 'n_path' => $upload_path_ratio.$upload_file_front_name,
		// 					'mode' => 'ratio', 'width' => CAR_THUM_WIDTH, 'height' => CAR_THUM_HEIGHT, 'preview_yn' => 'N','o_name' =>$upload_file_front_name
		// 				);
		// 		$thumb_front = getThumb($thumb_front);
		// 	}
		// }
		//
		// if (is_uploaded_file($_FILES['nm_file_back']['tmp_name'])) {
		// 	if($_FILES['nm_file_back']['size'] > 0 ){
		// 		$upload_file_back_name = upload($_FILES['nm_file_back'],$upload_path."nm_file_main/", 500, array('gif',  'jpeg', 'jpg','png','bmp' ,'ttif'));
		//
		// 		if($upload_file_back_name==false){
		// 			AlertBack("첨부파일 업로드 실패 하였습니다.");
		// 			die();
		// 		}
		//
		// 		$thumb_back = array(
		// 					'o_path' => $upload_path.'nm_file_main/'.$upload_file_back_name, 'n_path' => $upload_path_ratio.$upload_file_back_name,
		// 					'mode' => 'ratio', 'width' => CAR_THUM_WIDTH, 'height' => CAR_THUM_HEIGHT, 'preview_yn' => 'N','o_name' =>$upload_file_back_name
		// 				);
		// 		$thumb_back = getThumb($thumb_back);
		// 	}
		// }
		//
		// if (is_uploaded_file($_FILES['nm_file_side1']['tmp_name'])) {
		// 	if($_FILES['nm_file_side1']['size'] > 0 ){
		// 		$upload_file_side1_name = upload($_FILES['nm_file_side1'],$upload_path."nm_file_main/", 500, array('gif',  'jpeg', 'jpg','png','bmp' ,'ttif'));
		//
		// 		if($upload_file_side1_name==false){
		// 			AlertBack("첨부파일 업로드 실패 하였습니다.");
		// 			die();
		// 		}
		//
		// 		$thumb_side1 = array(
		// 					'o_path' => $upload_path.'nm_file_main/'.$upload_file_side1_name, 'n_path' => $upload_path_ratio.$upload_file_side1_name,
		// 					'mode' => 'ratio', 'width' => CAR_THUM_WIDTH, 'height' => CAR_THUM_HEIGHT, 'preview_yn' => 'N','o_name' =>$upload_file_side1_name
		// 				);
		// 		$thumb_side1 = getThumb($thumb_side1);
		// 	}
		// }
		//
		// if (is_uploaded_file($_FILES['nm_file_side2']['tmp_name'])) {
		// 	if($_FILES['nm_file_side2']['size'] > 0 ){
		// 		$upload_file_side2_name = upload($_FILES['nm_file_side2'],$upload_path."nm_file_main/", 500, array('gif',  'jpeg', 'jpg','png','bmp' ,'ttif'));
		//
		// 		if($upload_file_side2_name==false){
		// 			AlertBack("첨부파일 업로드 실패 하였습니다.");
		// 			die();
		// 		}
		//
		// 		$thumb_side2 = array(
		// 					'o_path' => $upload_path.'nm_file_main/'.$upload_file_side2_name, 'n_path' => $upload_path_ratio.$upload_file_side2_name,
		// 					'mode' => 'ratio', 'width' => CAR_THUM_WIDTH, 'height' => CAR_THUM_HEIGHT, 'preview_yn' => 'N','o_name' =>$upload_file_side2_name
		// 				);
		// 		$thumb_side2 = getThumb($thumb_side2);
		// 	}
		// }
		//
		// if (is_uploaded_file($_FILES['nm_file_dashboard']['tmp_name'])) {
		// 	if($_FILES['nm_file_dashboard']['size'] > 0 ){
		// 		$upload_file_dashboard_name = upload($_FILES['nm_file_dashboard'],$upload_path."nm_file_main/", 500, array('gif',  'jpeg', 'jpg','png','bmp' ,'ttif'));
		//
		// 		if($upload_file_dashboard_name==false){
		// 			AlertBack("첨부파일 업로드 실패 하였습니다.");
		// 			die();
		// 		}
		//
		// 		$thumb_dashboard = array(
		// 					'o_path' => $upload_path.'nm_file_main/'.$upload_file_dashboard_name, 'n_path' => $upload_path_ratio.$upload_file_dashboard_name,
		// 					'mode' => 'ratio', 'width' => CAR_THUM_WIDTH, 'height' => CAR_THUM_HEIGHT, 'preview_yn' => 'N','o_name' =>$upload_file_dashboard_name
		// 				);
		// 		$thumb_dashboard = getThumb($thumb_dashboard);
		// 	}
		// }
		//
		// //nm_file_front,nm_file_back,nm_file_side1,nm_file_side2,nm_file_dashboard,nm_file_act,nm_recommend
		// //ds_status : 'A0' = 입력중, 'B0' = '입력완료', ...
		// $sql="update car_master
		// 		set
		// 			  nm_file_front = case when '$upload_file_front_name' = '' then nm_file_front else '$upload_file_front_name' end
		// 			, nm_file_back = case when '$upload_file_back_name' = '' then nm_file_back else '$upload_file_back_name' end
		// 			, nm_file_side1 = case when '$upload_file_side1_name' = '' then nm_file_side1 else '$upload_file_side1_name' end
		// 			, nm_file_side2 = case when '$upload_file_side2_name' = '' then nm_file_side2 else '$upload_file_side2_name' end
		// 			, nm_file_dashboard = case when '$upload_file_dashboard_name' = '' then nm_file_dashboard else '$upload_file_dashboard_name' end
		// 			, dt_update = now()
		// 			, nm_update = '$cd_userid'
		// 		WHERE  cd_car = $cd_car";
		// // echo $sql;
		// // exit;
		// $result  = $dbCon->query($sql);
		//
		// if ($result) {
		// 	echo "200";
		// 	// AlertRedirect("등록 되었습니다.","buy_view.php?list_url=$list_url&ds_status_sale=$ds_status_sale&cd_sale=$cd_sale&ds_status_contract_sale=$ds_status_contract_sale&ds_status_contract_step1_sale=$ds_status_contract_step1_sale&ListPageNo=$ListPageNo");
		// }else{
		// 	echo "999";
		// 	// AlertBack("등록 실패하였습니다.");
		// }

	break;




	//낙찰리스트, 진행중리스트 SMS 발송처리
	case "tenderSmsSend":
		$RES = array('CODE'=>'9999', 'MSG'=>'');
		try {

			$cd_userid = trim($_SESSION["admin_cd_userid"]);
			$cd_sale = trim($_POST["cd_sale"]);
			$cd_tender = trim($_POST["cd_tender"]);
			$ds_status = trim($_POST["ds_status"]);


			if(empty($cd_sale)) {
				throw new Exception("차량 정보가 넘어오지 않았습니다.", "9990");
			}
			if(empty($cd_tender)) {
				throw new Exception("차량 낙찰자 정보가 넘어오지 않았습니다.", "9990");
			}
			if(empty($ds_status)) {
				throw new Exception("SMS상태 정보가 넘어오지 않았습니다.", "9990");
			}


			$tender_sms_sql = "SELECT * FROM tender_sms_master t WHERE t.cd_sale = '". $cd_sale . "' and t.cd_tender = '$cd_tender' and t.depth = 1 and ds_send_status = 'Z0' and ds_status = '$ds_status' LIMIT 1";
			// echo $tender_sms_sql;
			// exit;
			$tender_sms_res  = mysql_query($tender_sms_sql,$connect);
			$tender_sms_col = mysql_fetch_array($tender_sms_res);

			// print_r($tender_sms_col);

			if (!empty($tender_sms_col['cd_tender_sms'])) {
				throw new Exception("이미 SMS 1차 발송된 상태입니다.", "5555");
			}

			//상태별 메시지
			// $sms_msg = array(
			// 	'Z0' => "“낙찰중 페이지 {CAR_INFO} 거래 진행처리 진행 부탁드립니다. {PERIOD}일이내 미처리시 입찰이 정지 됩니다.”",
			// 	'Z1' => "“진행중 페이지 {CAR_INFO} 거래 진행처리 진행 부탁드립니다. {PERIOD}일이내 미처리시 입찰이 정지 됩니다.”",
			// );
			$sms_msg = tender_sms_msg();
			//단계별 일수
			$sms_period = tender_sms_period();
			// 경매정보 확인
			// 입찰정보에서 넘어온 cd_tender로 다시 한번 tender_master검사
			$sale_sql = "SELECT
									a.*
									, b.nm_model
									, d.nm_brand
									, getCode('car_master','ds_type',a.ds_type) as nm_type
									, getCode('car_master','ds_open',a.ds_open) as nm_open
									, getCode('car_master','ds_sales',a.ds_sales) as nm_sales
									, getCode('car_master','ds_transmission',a.ds_transmission) as nm_transmission
									, getCode('member_master','ds_area',s.ds_area) as nm_area
									, getCode('sale_master','ds_status',s.ds_status) as nm_status
									, s.cd_sale
									, f.cd_tender cd_tender
									, f.nm_hp tender_nm_hp
									FROM sale_master s
										inner join car_master a on (s.cd_car = a.cd_car)
										left outer join car_model b on (a.cd_model = b.cd_model)
										left outer join car_brand d on (a.cd_brand = d.cd_brand)
										inner join tender_master f on (s.cd_sale = f.cd_sale and f.ds_status = 'Z0' and f.ds_delind = 'N'  and f.cd_tender = '$cd_tender')
									where s.cd_sale = '". $cd_sale . "' and s.ds_delind = 'N' LIMIT 1";
			// echo $sale_sql;
			// exit;
			$sale_res = mysql_query($sale_sql, $connect);

			$sale_col = mysql_fetch_array($sale_res);

			//현재 경매 정보가 있을 경우만
			if (empty($sale_col['cd_sale'])) {
				throw new Exception("경매정보가 없습니다.새로고침 후 이용해 주세요.", "5555");
				// echo("F");
				// exit;
			}

			//1차 발송 내용 치환
			$depth = 1;
			$car_info = $sale_col['nm_brand']." ".$sale_col['nm_model'].", ".$sale_col['nm_number'];
			$nm_content = str_replace("{CAR_INFO}", $car_info, $sms_msg[$ds_status]);
			$nm_content = str_replace("{PERIOD}", $sms_period[$depth], $nm_content);
			// 낙찰중 페이지 Kia 봉고Ⅲ 플러스냉동차, 서울85바3080 거래 진행처리 진행 부탁드립니다. 5일이내 미처리시 입찰이 정지 됩니다.

			switch($ds_status) {
				//낙찰 리스트에서 넘어옴
				case 'Z0':
					$tender_update_column = " ds_complete_depth = '1'";
					break;
				//진행중 리스트에서 넘어옴
				case 'Z1':
					$tender_update_column = " ds_underway_depth = '1'";
					break;
				//진행중 리스트에서 넘어옴
				default:
					throw new Exception("정상적인 접근이 아닙니다.", "9999");
					// echo("N");
					// exit;
					break;
			}

			$aligo = new Aligo();
			$aligo->getToken();


			//낙찰, 리스트 SMS 단계 업데이트
			$tender_sql="UPDATE tender_master SET
						$tender_update_column
						, dt_update = now()
						, nm_update = '$cd_userid'
					WHERE  cd_sale = $cd_sale and cd_tender = '$cd_tender' ";
			// echo $tender_sql;
			// exit;
			$tender_res  = mysql_query($tender_sql,$connect);
			if (!$tender_res) {
				throw new Exception("낙찰자 정보 변경에 실패했습니다.", "9980");
				// echo("N");
				// exit;
			}

			$cur_date = date("Y-m-d H:i:s");

			//ds_send_status = 발송상태 발송완료
			//ds_lock_status = 락처리 필요없음
			//1ㅊㅏ 발송 데이터

			$DATA = array();
			$DATA['cd_sale'] 		= $cd_sale;
			$DATA['cd_tender'] 		= $cd_tender;
			$DATA['tender_nm_hp'] 	= $sale_col['tender_nm_hp'];
			$DATA['depth'] 			= $depth;
			$DATA['ds_send_status'] = 'Z0';
			$DATA['nm_content'] 	= $nm_content;
			$DATA['ds_status'] 		= $ds_status;
			$DATA['dt_send'] 		= $cur_date;
			$DATA['cd_userid'] 		= $cd_userid;

			$result = insert_tender_sms($connect, $DATA);
			//
			if (!$result) {
				throw new Exception("1차 SMS 등록에 실패했습니다.", "9981");
			}

			# 1차 SMS는 바로 발송
			$ALIGO_DATA = array();
			$ALIGO_DATA['message'] 		= $nm_content;
			$ALIGO_DATA['recv_phone'] 	= $sale_col['tender_nm_hp'];
			switch($ds_status) {
				//낙찰 리스트에서 넘어옴
				case 'Z0':
					$response = $aligo->send_admin_delay_complete_to_aap($ALIGO_DATA);
					break;
				//진행중 리스트에서 넘어옴
				case 'Z1':
					$response = $aligo->send_admin_delay_underway_to_aap($ALIGO_DATA);
					// print_r($response);
					// exit;
					break;
			}

			unset($ALIGO_DATA);

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


			//2차 발송 내용 치환
			$depth = 2;
			$nm_content = str_replace("{CAR_INFO}", $car_info, $sms_msg[$ds_status]);
			$nm_content = str_replace("{PERIOD}", $sms_period[$depth], $nm_content);
			//2단계 발송 데이터 등록
			// $send_date = date("Y-m-d H:i:s", strtotime($cur_date. ' + 5 day'));
			//2차는 5일후에 발송이 되야 하므로
			$send_date = date("Y-m-d H:i:s", strtotime($cur_date. ' + '.($sms_period[1]).' day'));

			$DATA = array();
			$DATA['cd_sale'] 		= $cd_sale;
			$DATA['cd_tender'] 		= $cd_tender;
			$DATA['tender_nm_hp'] 	= $sale_col['tender_nm_hp'];
			$DATA['depth'] 			= $depth;
			$DATA['ds_send_status'] = 'A0';
			$DATA['nm_content'] 	= $nm_content;
			$DATA['ds_status'] 		= $ds_status;
			$DATA['dt_send'] 		= $send_date;
			$DATA['cd_userid'] 		= $cd_userid;

			$result = insert_tender_sms($connect, $DATA);
			if (!$result) {
				throw new Exception("2차 SMS 등록에 실패했습니다.", "9981");
			}

			$DATAS = array();

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


			// $result  = mysql_query($sql,$connect);
			//
			// if(!$result) {
			// 	throw new Exception("저장에 실패 하였습니다.", "9990");
			// }

			$DATAS = array();

			$RES['CODE'] 	= "0000";
			$RES['MSG'] = "정상처리.";
			$RES['DATAS'] 	= $DATAS;
		}catch(Exception $e){
			$RES['CODE'] = $e->getCode();
			$RES['MSG'] = $e->getMessage();
		}
		echo json_encode($RES);
		exit;


		// $cd_userid = trim($_SESSION["admin_cd_userid"]);
		// $cd_sale = trim($_POST["cd_sale"]);
		// $cd_tender = trim($_POST["cd_tender"]);
		// $ds_status = trim($_POST["ds_status"]);
		//
		// // 이미 1차 발송한 건을 검사
		// $table_name = "tender_sms_master t ";
		// $_whereis = " t.cd_sale = '". $cd_sale . "' and t.cd_tender = '$cd_tender' and t.depth = 1 and ds_send_status = 'Z0' and ds_status = '$ds_status' ";
		//
		// $sms = $dbCon->selectDAO("t.*", $table_name, $_whereis);
		// if (!empty($sms['cd_tender_sms'])) {
		// 	echo("E");
		// 	exit;
		// }
		// //상태별 메시지
		// $sms_msg = tender_sms_msg();
		// //단계별 일수
		// $sms_period = tender_sms_period();
		// // 경매정보 확인
		// // 입찰정보에서 넘어온 cd_tender로 다시 한번 tender_master검사
		// $r = mysql_query("SELECT
		// 						a.*
		// 						, b.nm_model
		// 						, c.nm_grade
		// 						, d.nm_brand
		// 						, e.nm_model_sub
		// 						, getCode('car_master','ds_type',a.ds_type) as nm_type
		// 						, getCode('car_master','ds_open',a.ds_open) as nm_open
		// 						, getCode('car_master','ds_sales',a.ds_sales) as nm_sales
		// 						, getCode('car_master','ds_transmission',a.ds_transmission) as nm_transmission
		// 						, getCode('member_master','ds_area',s.ds_area) as nm_area
		// 						, getCode('sale_master','ds_status',s.ds_status) as nm_status
		// 						, s.cd_sale
		// 						, f.cd_tender cd_tender
		// 						, f.nm_hp tender_nm_hp
		// 						FROM sale_master s
		// 							inner join car_master a 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)
		// 							inner join tender_master f on (s.cd_sale = f.cd_sale and f.ds_status = 'Z0' and f.ds_delind = 'N'  and f.cd_tender = '$cd_tender')
		// 						where s.cd_sale = '". $cd_sale . "' and s.ds_delind = 'N' LIMIT 1");
		//
		// $sale = mysql_fetch_array($r);
		//
		// //현재 경매 정보가 있을 경우만
		// if (empty($sale['cd_sale'])) {
		// 	echo("F");
		// 	exit;
		// }
		//
		//
		//
		// //1차 발송 내용 치환
		// $depth = 1;
		// $car_info = $sale[nm_brand]." ".$sale[nm_model].", ".$sale[nm_number];
		// $nm_content = str_replace("{CAR_INFO}", $car_info, $sms_msg[$ds_status]);
		// $nm_content = str_replace("{PERIOD}", $sms_period[$depth], $nm_content);
		//
		// switch($ds_status) {
		// 	//낙찰 리스트에서 넘어옴
		// 	case 'Z0':
		// 		$tender_update_column = " ds_complete_depth = '1'";
		// 		break;
		// 	//진행중 리스트에서 넘어옴
		// 	case 'Z1':
		// 		$tender_update_column = " ds_underway_depth = '1'";
		// 		break;
		// 	//진행중 리스트에서 넘어옴
		// 	default:
		// 		echo("N");
		// 		exit;
		// 		break;
		// }
		//
		// // $biztalk = new Biztalk();
		// // $biztalk->getToken();
		//
		//
		// //낙찰, 리스트 SMS 단계 업데이트
		// $sql="update tender_master set
		// 			$tender_update_column
		// 			, dt_update = now()
		// 			, nm_update = '$cd_userid'
		// 		WHERE  cd_sale = $cd_sale and cd_tender = '$cd_tender' ";
		//
		// $result  = mysql_query($sql,$connect);
		// if (!$result) {
		// 	echo("N");
		// 	exit;
		// }
		//
		//
		// $cur_date = date("Y-m-d H:i:s");
		//
		// //ds_send_status = 발송상태 발송완료
		// //ds_lock_status = 락처리 필요없음
		// //1ㅊㅏ 발송 데이터
		//
		// $DATA = array();
		// $DATA['cd_sale'] 		= $cd_sale;
		// $DATA['cd_tender'] 		= $cd_tender;
		// $DATA['tender_nm_hp'] 	= $sale[tender_nm_hp];
		// $DATA['depth'] 			= $depth;
		// $DATA['ds_send_status'] = 'Z0';
		// $DATA['nm_content'] 	= $nm_content;
		// $DATA['ds_status'] 		= $ds_status;
		// $DATA['dt_send'] 		= $cur_date;
		// $DATA['cd_userid'] 		= $cd_userid;
		//
		// $result = insert_tender_sms($DATA);
		//
		// if ($result) {
		//
		// 	$SMS_DATA = array();
		// 	$SMS_DATA['message']    = $nm_content;        //발신 메시지 내용 (공백 포함2345 1000자로 제한) 가변 영역이 있을 경우 해당 가변 영역의 내용도 실제 보낼 내용으로 치환 되어야 한다.
		// 	$SMS_DATA['recipient']  = $sale[tender_nm_hp];                     //	수신자
		// 	$SMS_DATA['senderKey']  = '4856a5e128f9289082c884d066f1df198cbb1165';                     //	카카오 발신 프로필 키
		// 	$SMS_DATA['tmpltCode']  = 'tender_sms';                     //	메시지 템플릿 코드
		// 	$SMS_DATA['resMethod']  = 'PUSH';                     //	메시지 템플릿 코드
		//
		// 	// $SMS_DATA['debug'] = "Y";                     //	디버그
		//
		// 	// print_r($SMS_DATA);
		// 	// exit;
		//
		// 	// $send_reuslt = $biztalk->sendSms($SMS_DATA);
		// 	// unset($SMS_DATA);
		//
		//
		// 	//2차 발송 내용 치환
		// 	$depth = 2;
		// 	$nm_content = str_replace("{CAR_INFO}", $car_info, $sms_msg[$ds_status]);
		// 	$nm_content = str_replace("{PERIOD}", $sms_period[$depth], $nm_content);
		// 	//2단계 발송 데이터 등록
		// 	// $send_date = date("Y-m-d H:i:s", strtotime($cur_date. ' + 5 day'));
		// 	//2차는 5일후에 발송이 되야 하므로
		// 	$send_date = date("Y-m-d H:i:s", strtotime($cur_date. ' + '.($sms_period[1]).' day'));
		//
		// 	$DATA = array();
		// 	$DATA['cd_sale'] 		= $cd_sale;
		// 	$DATA['cd_tender'] 		= $cd_tender;
		// 	$DATA['tender_nm_hp'] 	= $sale[tender_nm_hp];
		// 	$DATA['depth'] 			= $depth;
		// 	$DATA['ds_send_status'] = 'A0';
		// 	$DATA['nm_content'] 	= $nm_content;
		// 	$DATA['ds_status'] 		= $ds_status;
		// 	$DATA['dt_send'] 		= $send_date;
		// 	$DATA['cd_userid'] 		= $cd_userid;
		//
		// 	$result = insert_tender_sms($DATA);
		//
		// 	$result  = mysql_query($sql,$connect);
		// 	if ($result) {
		// 		echo("Y");
		// 		exit;
		// 	}else {
		// 		echo("N");
		// 		exit;
		// 	}
		// }else{
		// 	echo("N");
		// 	exit;
		// }

	break;
	//낙찰리스트, 진행중 리스트 입찰 락 해제
	case "tenderSmsUnlock":

		$RES = array('CODE'=>'9999', 'MSG'=>'');
		try {
			$cd_userid = trim($_SESSION["admin_cd_userid"]);
			$cd_tender = trim($_POST["cd_tender"]);

			if(empty($cd_tender)) {
				throw new Exception("차량 정보가 넘어오지 않았습니다.", "9990");
			}


			// 이미 1차 발송한 건을 검사
			$tender_sql = "SELECT * FROM tender_master t WHERE t.cd_tender = '$cd_tender'  LIMIT 1";
			// echo $tender_sql;
			// exit;
			$tender_res  = mysql_query($tender_sql,$connect);
			$tender_col = mysql_fetch_array($tender_res);

			if (empty($tender_col['cd_tender'])) {
				throw new Exception("낙찰자 정보가 없습니다.새로고침후에 이용해주세요", "9990");
			}
			if ($tender_col['ds_lock_status'] != "A0") {
				throw new Exception("이미 해제된 건입니다.", "5555");
			}

			//차량 락 해제
			$sql="update tender_master set
						ds_lock_status = 'Z0'
						, dt_lock = NULL
						, dt_update = now()
						, nm_update = '$cd_userid'
					WHERE  cd_tender = '$cd_tender' ";
			// echo $sql;
			// exit;
			$result  = mysql_query($sql,$connect);

			if(!$result) {
				throw new Exception("락 해제에 실패 하였습니다.", "9990");
			}

			$DATAS = array();

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

		}catch(Exception $e){
			$RES['CODE'] = $e->getCode();
			$RES['MSG'] = $e->getMessage();
		}
		echo json_encode($RES);
		exit;



	break;




	//관리자 반려
	case 'Return':
		$RES = array('CODE'=>'9999', 'MSG'=>'');
		try {
			$cd_userid 		= trim($_SESSION["admin_cd_userid"]);
			$cd_sale 		= trim($_POST["cd_sale"]);
			$nm_cont_return = $_POST['nm_cont_return'];

			if(!$_POST) {
				throw new Exception("정상적인 접근이 아닙니다.", "9999");
			}
			if(empty($cd_sale)) {
				throw new Exception("매물정보가 없습니다.", "9998");
			}
			if(empty($nm_cont_return)) {
				throw new Exception("반려사유가 없습니다.", "9998");
			}

			// 매물 내역 확인
			$sale_sql = "SELECT s.*
							FROM sale_master s
							WHERE s.cd_sale = '".$cd_sale."'
								AND ds_delind = 'N'
							LIMIT 1 ";
			// echo $tender_sql;
			// exit;
			$sale_res  = mysql_query($sale_sql,$connect);
			$sale_row = mysql_fetch_assoc($sale_res);

			if(empty($sale_row['cd_sale'])) {
				throw new Exception("매물정보가 없습니다.", "9998");
			}

			$check_status = array("B0");
			if(!in_array($sale_row['ds_status'], $check_status)) {
				throw new Exception("매물상태가 [입찰대기]인 경우에만 반려 가능합니다.\n새로고침 후에 이용해 주세요", "9998");
			}



			$sql="UPDATE sale_master SET
						nm_cont_return = '$nm_cont_return'
						, ds_status = 'D0'
						, 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");
			}


			$DATAS = array();

			$RES['CODE'] 	= "0000";
			$RES['MSG'] 	= "저장 되었습니다.";
			$RES['DATAS'] 	= $DATAS;

		}catch(Exception $e){
			$RES['CODE'] = $e->getCode();
			$RES['MSG'] = $e->getMessage();
		}
		echo json_encode($RES);
		exit;

		break;

	//내차 팔기 승인 -> Confirm
	case "Confirm":
		$RES = array('CODE'=>'9999', 'MSG'=>'');
		try {
			$cd_sale 	= trim($_POST["cd_sale"]);
			// $ds_aap_dealer = trim(avoid_crack($_POST["ds_aap_dealer"]));

			if(!$_POST) {
				throw new Exception("정상적인 접근이 아닙니다.", "9999");
			}
			if(empty($cd_sale)) {
				throw new Exception("매물정보가 없습니다.", "9998");
			}

			// 매물 내역 확인
			$sale_sql = "SELECT s.*
							, c.nm_number
							, b.nm_model
							, d.nm_brand
							, s.nm_hp as user_phone
							, sa.nm_hp as sa_phone
							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 sa_master sa on sa.cd_user = s.cd_user
							WHERE s.cd_sale = '".$cd_sale."'
								AND s.ds_delind = 'N'
							LIMIT 1 ";
			// echo $tender_sql;
			// exit;
			$sale_res  = mysql_query($sale_sql,$connect);
			$sale_row = mysql_fetch_assoc($sale_res);
			// print_r($sale_row);
			// exit;

			if(empty($sale_row['cd_sale'])) {
				throw new Exception("매물정보가 없습니다.", "9998");
			}

			$check_status = array("B0", "D0");
			if(!in_array($sale_row['ds_status'], $check_status)) {
				throw new Exception("매물상태가 [입찰대기, 반려]인 경우에만 승인 가능합니다.\n새로고침 후에 이용해 주세요", "9998");
			}



			$sql="UPDATE sale_master SET
						ds_status = 'E0'
						, ds_aap_status = 'E0'
						, dt_approve = now()
						, dt_update = now()
						, nm_update = '$cd_procid'
					WHERE  cd_sale = $cd_sale";
			// echo $sql;
			// exit;

			$result  = mysql_query($sql,$connect);
			if(!$result) {
				throw new Exception("저장에 실패 하였습니다.", "9990");
			}

			// $table_name = " car_master a
			// 				inner join sale_master f on (a.cd_car = f.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 = "  f.cd_sale = '".$cd_sale."' ";
			// $col = $dbCon->selectDAO(" a.cd_brand, a.cd_model, a.cd_grade, b.nm_model, c.nm_grade, d.nm_brand, e.nm_model_sub, f.nm_hp, f.nm_name, a.nm_mileage, f.ds_area, f.ds_area_user, a.nm_regdate_yyyy , a.nm_regdate_mm, a.ds_year", $table_name, $_whereis);
			// //해당 딜러 매칭은 ds_area_user : 사용자가 지정한 판매 희망지역으로 설정
			//
			// $nm_regdate_full = substr($col['ds_year'], 2, 2).'MY';
			// $contents = $col['nm_brand'].' '.$col['nm_model'].' '.$col['nm_grade'].' '.$col['nm_mileage'].'km';
			// $contents = $col['nm_model'].' '.$nm_regdate_full;
			//
			// $sql = "INSERT INTO sale_master_standby ( cd_brand, ds_area, cd_model, cd_grade, nm_mileage, contents)
			//         SELECT '$col[cd_brand]', '$col[ds_area]', '$col[cd_model]', '$col[cd_grade]', '$nm_regdate_full', '$contents' FROM dual
			//             WHERE not EXISTS
			//             (
			//                 SELECT cd_brand, ds_area, cd_model, cd_grade, nm_mileage
			//                     FROM sale_master_standby
			//                         WHERE cd_brand = '$col[cd_brand]'
			//                             and ds_area = '$col[ds_area]'
			//                             and cd_model = '$col[cd_model]'
			//                             and cd_grade = '$col[cd_grade]'
			//                             and nm_mileage = '$nm_regdate_full'
			//             )
			// ";
			// mysql_query($sql);

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

			//SA일 경우
			if($sale_row['is_staff'] == 'Y') {


				// if($_SERVER['REMOTE_ADDR'] == '220.86.24.199') {
					# 1.1 SA 등록자에게 발송
					$ALIGO_DATA = array();
					$ALIGO_DATA['car_brand'] 	= $sale_row['nm_brand'];
					$ALIGO_DATA['car_model'] 	= $sale_row['nm_model'];
					$ALIGO_DATA['recv_phone'] 	= $sale_row['sa_phone'];

					// $response = $aligo->send_admin_sell_confirm_to_sa($ALIGO_DATA);
					// unset($ALIGO_DATA);
					//
					// if($response['code'] != "0") {
					// 	// echo $response['message'];
					// }


					# 1.2 SA 등록일 경우 지정 AAP에게
					$aap_sql = "SELECT aap.*
									FROM aap_master aap
										WHERE cd_dealer = '{$sale_row['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;

					if(!empty($aap_col['cd_dealer'])) {
						$ALIGO_DATA = array();
						$ALIGO_DATA['car_brand'] 	= $sale_row['nm_brand'];
						$ALIGO_DATA['car_model'] 	= $sale_row['nm_model'];
						// $ALIGO_DATA['car_number'] 	= $car_col['nm_number'];
						$ALIGO_DATA['recv_phone'] 	= $aap_col['nm_hp'];
						// $ALIGO_DATA['sa_name'] 		= $sa_col['nm_name'];
						// $ALIGO_DATA['sa_area'] 		= $sa_col['nm_branch'];

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

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

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

				// }
				// exit;

			}
			else {
				$ALIGO_DATA = array();
				$ALIGO_DATA['car_brand'] 	= $sale_row['nm_brand'];
				$ALIGO_DATA['car_model'] 	= $sale_row['nm_model'];
				$ALIGO_DATA['recv_phone'] 	= $sale_row['user_phone'];


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

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





			# 3. 모든  AAP에게
			//관리자 승인시 aap, aap 부관리자에게 SMS 발송 로직 추가
			// if($_SERVER['REMOTE_ADDR'] == '220.86.24.199') {

				// $aligo = new Aligo();
				$aligo->getHourToken();
				// exit;
				//개발용 조건절
				// $alim_aap_add_sql = " AND cd_dealer in (1,2)";
				$alim_aap_add_sql = " ";
				$alim_aap_sql = "select * from aap_master am
									where ds_delind = 'N'
										AND nm_hp > ''
										AND ds_status = 'Z0'
										$alim_aap_add_sql
									group by nm_hp
				";

				$alim_aap_res = mysql_query($alim_aap_sql, $connect);

				while($alim_aap_col = mysql_fetch_array($alim_aap_res)) {
					$ALIGO_DATA = array();
					$ALIGO_DATA['recv_phone'] 	= $alim_aap_col['nm_hp'];
					// print_r($ALIGO_DATA);

					$response = $aligo->send_admin_sell_confirm_to_aap($ALIGO_DATA);
					unset($ALIGO_DATA);
				}
				// echo $alim_aap_sql;
				// exit;
			// }


			$DATAS = array();

			$RES['CODE'] 	= "0000";
			$RES['MSG'] 	= "저장 되었습니다.";
			$RES['DATAS'] 	= $DATAS;
		}catch(Exception $e){
			$RES['CODE'] = $e->getCode();
			$RES['MSG'] = $e->getMessage();
		}
		echo json_encode($RES);
		exit;

	break;
	default :
		AlertRedirect("지정되지않은 요청입니다","/index.php");
	break;
}


function fnSetAdminCarImgCreate($cd_car,$connect){
	// print_r($_FILES);
	// exit;
	$upload_path = $_SERVER['DOCUMENT_ROOT'].UPLOAD_PATH_CAR.$cd_car."_detail/";
	$blnResult = true;
	$cd_userid =  $_SESSION['admin_cd_userid'];

	//먼지 모르겟는데 더
	$sql = "delete from car_file  where cd_car='$cd_car' and  nm_mime=''";

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

	$maxVal = mysql_result(mysql_query("select ifnull(max(no_sort),0)+1 from car_file  Where ds_delind='N' and cd_car = '$cd_car'", $connect),0,0);
	if($maxVal==""){$maxVal=1;}
	for($k = 0; $k<count($_FILES["file"]['size']);$k++){

		if (is_uploaded_file($_FILES['file']['tmp_name'][$k])) {

			if($_FILES['file']['size'][$k] > 0 ){
				$fileObj = array();
				$fileObj["tmp_name"] = $_FILES["file"]["tmp_name"][$k];
				$fileObj["name"] = $_FILES["file"]["name"][$k];
				$fileObj["error"] = $_FILES["file"]["error"][$k];
				$fileObj["size"] = $_FILES["file"]["size"][$k];
				$fileObj["type"] =  $_FILES["file"]["type"][$k];

				$upload_path =  $_SERVER['DOCUMENT_ROOT'].UPLOAD_PATH_CAR.$cd_car."_detail/";

				$upload_file_name = upload($fileObj,$upload_path, 500, array('gif',  'jpeg', 'jpg','png','bmp' ,'ttif'));

				// if(file_exists($upload_path.$upload_file_name) && is_file($upload_path.$upload_file_name)) {
				// 	create_watermark($upload_path.$upload_file_name);
				// }

				$thumb1 = array(
							'o_path' => $upload_path.$upload_file_name, 'n_path' => $upload_path.'ratio_'.$upload_file_name,
							'mode' => 'ratio', 'width' => CAR_THUM_WIDTH, 'height' => CAR_THUM_HEIGHT, 'preview_yn' => 'N','o_name' =>'ratio_'.$upload_file_name
						);
				$thumb1 = getThumb($thumb1);

				if(empty($thumb1['fileName']))		$thumb1['fileName'] = '';
				// $upload_file_name = $thumb1['fileName'];
				$nm_size = $_FILES['file']['size'][$k];
				$nm_mime = $_FILES['file']['type'][$k];

				if($upload_file_name=="" || $nm_mime==""){
					$blnResult =  false;
				}else{
					if($k == 0 ){

						$upload_path2 = $_SERVER['DOCUMENT_ROOT'].UPLOAD_PATH_CAR.$cd_car."_detail/";
						$upload_file_list_name = upload($fileObj,$upload_path2, 500, array('gif',  'jpeg', 'jpg','png','bmp' ,'ttif'));

						$thumb2 = array(
							'o_path' => $upload_path2.$upload_file_list_name, 'n_path' => $upload_path2.'ratio_'.$upload_file_list_name,
							'mode' => 'ratio', 'width' => CAR_THUM2_WIDTH, 'height' => CAR_THUM2_HEIGHT, 'preview_yn' => 'N','o_name' =>'ratio_'.$upload_file_list_name
						);
						$thumb2 = getThumb($thumb2);

						if(empty($thumb2['fileName']))		$thumb2['fileName'] = '';
						$upload_file_list_name = $thumb2['fileName'];

						$sqlThum = "UPDATE car_master SET
										nm_file_main='$upload_file_list_name',
										nm_file_list = '$upload_file_list_name',
										nm_update = '$cd_userid',
										dt_update = now()
									WHERE cd_car='$cd_car'";
						// echo $sqlThum;
						// exit;
						$mainResult  = mysql_query($sqlThum, $connect);
					}

					if($nm_mime!=="" && $blnResult){
						//기존에 있을지 모르니 지우기
						$sql = "delete from car_file  where cd_car='$cd_car' and no_sort = '$k'";
						$result  = mysql_query($sql, $connect);

						$sql = "INSERT INTO car_file SET
									cd_car		= '$cd_car',
									nm_file		= '$upload_file_name',
									nm_size		= '$nm_size',
									nm_mime		= '$nm_mime',
									ds_type		= '',
									no_sort 	= '$k',
									dt_insert	= now(),
									nm_insert	= '$cd_userid',
									dt_update	= now(),
									nm_update	= '$cd_userid',
									ds_delind	= 'N'
						";
						// echo $sql;
						// exit;
						$blnResult  = mysql_query($sql, $connect);

						// $blnResult  = mysql_query($connect, $sql);
						$maxVal++;



					}
				}
				$upload_file_name = "";
			}
		}
	}



	return $blnResult;
}

mysql_close($connect);
?>
