<?php
	include $_SERVER['DOCUMENT_ROOT'].'/common/lib/comm.php';
	include $_SERVER['DOCUMENT_ROOT'].'/common/auth_chk_m.php';

	$nav_title = "차량 판매 > 추가 사진 정보 입력";
	$HEADER_LOC = 'main';

	$mode 		= $_REQUEST['mode'];

	$s_cd_sale 	= $_SESSION['s_cd_sale'];
	$s_cd_car 	= $_SESSION['s_cd_car'];

	$ds_cate = $_REQUEST['ds_cate'];

//	Auth -> Step 단계에 따른 정상적인 요청 체크
	if($mode != "Step4" || $mode == null)
		AlertBack("지정되지 않은 요청입니다.");


	if(!$ds_cate) $ds_cate='A0';
	$ds_model_cate= $ds_cate;

	$add_img = array();

	if($s_cd_car !="" || $s_cd_car != null){

		$sql ="SELECT a.*, s.nm_recommend
			FROM car_master a left outer join sale_master s on ( a.cd_car = s.cd_car )
			WHERE  a.cd_car='$s_cd_car' AND a.ds_delind='N'";

		$col=mysql_fetch_array(mysql_query($sql));

		if (!empty($col['cd_car'])){

			$cd_car = $col['cd_car'];

			$upload_file_main_name = $col['nm_file_main'];
			$upload_file_list_name = $col['nm_file_list'];

			$nm_file_front = $col['nm_file_front'];
			$nm_file_back = $col['nm_file_back'];
			$nm_file_side1 = $col['nm_file_side1'];
			$nm_file_side2 = $col['nm_file_side2'];
			$nm_file_dashboard = $col['nm_file_dashboard'];
			$nm_recommend = $col['nm_recommend'];

			$r = mysql_query("SELECT * FROM car_file WHERE cd_car = '$cd_car' and ds_type='' and ds_delind='N' Order by no_sort asc ,  cd_car ASC ");
			$car_img_i=1;
			while($imgs = mysql_fetch_array($r)) {
				$add_img[] = UPLOAD_PATH_CAR.$imgs['cd_car']."_detail/".$imgs['nm_file'];
			}

		}else{
			AlertBack("게시물을 가져오지 못하였습니다.");
		}
		$PageNo = $PageNo;
//		$mode = "Update";
	}else{
//		$mode="Add";
	}

	if ($mode=="Add"){
//		$cd_userid = $_SESSION[admin_cd_userid];
	}

	if($ds_open==""){$ds_open="Y";}
	if($cd_category==""){$cd_category="1";}

//	등록 중이던 Session s_cd_car 삭제하여 새로운 차량 등록하도록 한다.
//	$_SESSION['s_cd_sale'] = null;
	// $_SESSION['s_cd_car'] = null;

?>

<?php include("../inc/inc_header.php"); ?>


<main class="pb60">
	<section>
		<div class="sub--top--visual">
			<div class="contents--inner">
				<h2>차량 판매하기</h2>
				<p>이차조아에서는 사고 이력 조회 후 최고가 내차를 판매할 수 있습니다.</p>
			</div>
		</div>
	</section>


	<section class="mt35">
		<form id="frmForm" name="frmForm" method="post" action="proc.php" enctype="multipart/form-data">
		<input type="hidden" name="mode" id="mode" value="<?=$mode?>"/>

		<div class="options--wrapper">
			<h2>사진 입력<span class="astc--text ty2">(추가 사진)</span></h2>
			<div class="pic--add--wrap">
				<?php
					for($i=0, $j=1; $i < 5; $i++, $j++) {
						$tmp_add_img = "";
						if(!empty($add_img[$i])) {
							$tmp_add_img = "background-image:url('".$add_img[$i]."');";
						}
				?>
					<div class="add--box addition--box">
						<div class="thumb--wrap">
							<div class="thumb"></div>
						</div>
						<div class="desc">
							<input type="file" hidden name="upload_file[<?=$i?>]" id="nm_file_0<?=$j?>" class="upload-hidden" onchange="viewThumb(<?=$i?>,this)" accept="image/*">
							<label class="add--btn" for="nm_file_0<?=$j?>">사진 등록</label>
						</div>
					</div>

				<?php } ?>



			</div>
		</div>
	</section>

	<div class="btn--wrapper car--btn--wrapper floating--btn">
		<button type='button' id='btn_write' class="next--btn">다음(차량 설명)<i class="next--ic"></i></button>
	</div>

	<!-- loading -->
	<div class="loading_wrap hide">
		<?php include("../../include/loading_dim.html") ?>
	</div>
	<!-- // loading -->
</main>


<script>

	function form_data(){
		var sdata = new FormData();
		$("#frmForm input, #frmForm select, #frmForm textarea").each(function(idx, item){
			var _inputName = $(this).attr("name");
			var _inputVale = $(this).val();
			var _inputType = $(this).attr("type");

			if(_inputType == "radio" || _inputType == "checkbox"){
				console.log(_inputName);
				console.log(_inputVale);
				_inputVale = $("[name="+_inputName+"]:checked").val();
				if($(this).prop("checked")){
					sdata.append(_inputName, _inputVale);
				}
			}else{
				sdata.append(_inputName, _inputVale);
			}
		});

		$("#frmForm input[type=file]").each(function() {
			var input_name = $(this).attr("name");
			var input_value = $(this)[0].files[0];
			sdata.append(input_name, input_value);
		});

		return sdata;
	}

	function viewThumb(seq, arg){
		if($(arg).val() == "") {
			$(arg).closest("div.add--box").find(".thumb").css({"background":"#f7f7f9 url('/design/staff/assets/img/pic_ic.svg') no-repeat center"});
		}
		if (arg.files && arg.files[0])
		{
			var reader = new FileReader();

			reader.onload = function (e) {
				$(arg).closest("div.add--box").find(".thumb").css({"background":"url('"+e.target.result+"') no-repeat center"});
			}
			reader.readAsDataURL(arg.files[0]);
		}
	}

	$(document).ready(function() {
		$("#btn_write").bind("click",function(){
			var custom_opts = {
				title : '',
				btn_close_show : false,
			}

			var uploaded_cnt = <?=count($add_img)?>;
			$("input[type=file]").each(function() {
				if($(this).val()) {
					uploaded_cnt++;
				};
			});

			if(uploaded_cnt == 0) {
				custom_opts.title = '추가 사진을 등록하지 않고 정보를 등록하시겠습니까?';
			}else {
				custom_opts.title = '정보를 등록하시겠습니까?';
			}

			custom_modal_confirm(custom_opts, function(confirm) {
				if(confirm) {
					custom_modal_confirm_close();

					$(".loading_wrap").removeClass("hide");
					// $("#frmForm").submit();

					$("#btn_write").hide();
					var data = form_data();

					$.ajax({
						url : 'proc.php',
						type: 'POST',
						dataType : 'json',
						data: data,
						processData: false,
				        contentType: false,
						success: function(res) {
							$("#btn_write").show();

							custom_modal_confirm_close();

							$(".loading_wrap").addClass("hide");

							if(res.CODE != "0000") {
								//세션이 없어지면 내차 팔기 초기 화면으로 이동
								if(res.CODE == "8888") {
									alert(res.MSG);
									window.location.replace(res.DATAS.URL);
									return false;
								}
								custom_opts.title = res.MSG;
								custom_modal_alert(custom_opts);
								return false;
							}
							link("sell_step5.php?mode=Step5");
							// window.location.href = res.DATAS.URL;
							return false;
						},
						error:function(request,status,error){
							$(".loading_wrap").addClass("hide");

							$("#btn_write").show();

							custom_modal_confirm_close();

							alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
						}
					});

			  }else {
				  $("#btn_write").show();
				  return false;
			  }
			});
		});



	});
</script>

<?php include("../inc/inc_bottom.php"); ?>

<?php
mysql_close($connect);
?>
