<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");  

if(!isset($_SESSION["level"]) || $_SESSION["level"]>5) {
	sleep(1);
	header("Location:" . $WebSite . "login/login_form.php"); 
	exit;
}   

include $_SERVER['DOCUMENT_ROOT'] . '/load_header.php';

// 첫 화면 표시 문구
$title_message = '발주처 주소록'; 
 ?>
 
<title> <?=$title_message?> </title>
</head>

<body>	
	 
<?php

$option = isset($_REQUEST['option']) ? $_REQUEST['option'] : '';  
// 담당자 추가하면 option=add
$search = isset($_REQUEST['search']) ? $_REQUEST['search'] : '';  
$mode = isset($_REQUEST['mode']) ? $_REQUEST['mode'] : '';  
$header = isset($_REQUEST['header']) ? $_REQUEST['header'] : '';  
  
$tablename = 'phonebook';
  	  
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();
    
$num = isset($_REQUEST["num"]) ? $_REQUEST["num"] : 0;


// 수정일 경우
if($num>0)
{	
     
		try{
		 $sql = "select * from ". $DB . "." . $tablename . " where num=?";
		 $stmh = $pdo->prepare($sql);  
		 $stmh->bindValue(1, $num, PDO::PARAM_STR);      
		 $stmh->execute();            
		  
		 $row = $stmh->fetch(PDO::FETCH_ASSOC); 	 
			include '_row.php';

		 }catch (PDOException $Exception) {
		   print "오류: ".$Exception->getMessage();
		 }      	
			 

	if($option !=='add')
	  {
		 $mode = 'update';
	  }
	  else
	  {
		$mode = 'insert';		 	
		$manager_name = '';
		$contact_info = '010-';	
		$represent = '';  // 대표자가 아닌 경우 직원추가인 경우 해당됨
		$title_message = '업체 담당자 추가화면 '; 
		
		// 부모코드 넣어줌
		$parentnum = $num;
		$secondordnum = $num;

	  }		 
		 
}
else
{
	include '_request.php';
	
	$mode = 'insert';
	$representative_name = $search;
	$manager_name = $search;
	$phone = '010-';	
	$represent = '대표코드';  // 대표코드
	$registdate = date('Y-m-d');  // 현재일자 기록
} 
?>	


<form id="board_form" name="board_form" method="post" enctype="multipart/form-data">			 

	<input type="hidden" id="mode" name="mode" value="<?=$mode?>">             
	<input type="hidden" id="num" name="num" value=<?=$num?> > 	
	<input type="hidden" id="mode" name="mode" value=<?=$mode?> > 
	<input type="hidden" id="tablename" name="tablename" value=<?=$tablename?> > 	
	<input type="hidden" id="update_log" name="update_log" value=<?=$update_log?> > 		
	<input type="hidden" id="parentnum" name="parentnum" value=<?=$parentnum?> > 	
	<input type="hidden" id="header" name="header" value="<?=$header?>" > 		
	<input type="hidden" id="represent" name="represent" value="<?=$represent?>" > 		
	<input type="hidden" id="registdate" name="registdate" value="<?=$registdate?>" > 		


<div class="container-fluid" >					
	<div class="d-flex align-items-center justify-content-center" >
	<div class="card justify-content-center" >
		<div class="card-header text-center">
			<span class="text-center fs-5" > <?=$title_message?>  </span>								
		</div>
	<div class="card-body">                                
		<div class="row justify-content-center text-center">  
		<?php
		// 담당자 추가이면 추가 버튼 
		if($option !=='add')			
			{
		?>
		<div class="d-flex align-items-center"> 
			<span class="input-group-text badge bg-secondary text-white fw-bold fs-6" style="width:100px;"> CODE </span> &nbsp; &nbsp; 				
			<input type="text" class="form-control mt-1" style="width:100px;" id="secondordnum" name="secondordnum" value="<?=$secondordnum?>" readonly >						

			<span class="input-group-text badge bg-primary text-white fw-bold fs-6 ms-5 me-2" > 매입/매출 구분 </span> &nbsp; &nbsp; 				
			<div class="d-flex align-items-center">
				<div class="form-check form-check-inline me-3">
					<input class="form-check-input fs-6" type="radio" name="PurchaseSales" id="PurchaseSales_1" value="매입" <?php echo ($PurchaseSales == '매입') ? 'checked' : ''; ?> <?php echo ($mode == 'view') ? 'disabled' : ''; ?>>
					<label class="form-check-label fs-6" for="PurchaseSales_1">매입</label>
				</div>
				<div class="form-check form-check-inline">
					<input class="form-check-input fs-6" type="radio" name="PurchaseSales" id="PurchaseSales_2" value="매출" <?php echo ($PurchaseSales == '매출') ? 'checked' : ''; ?> <?php echo ($mode == 'view') ? 'disabled' : ''; ?>>
					<label class="form-check-label fs-6" for="PurchaseSales_2">매출</label>
				</div>
				<div class="form-check form-check-inline">
					<input class="form-check-input fs-6" type="radio" name="PurchaseSales" id="PurchaseSales_3" value="매입매출" <?php echo ($PurchaseSales == '매입매출') ? 'checked' : ''; ?> <?php echo ($mode == 'view') ? 'disabled' : ''; ?>>
					<label class="form-check-label fs-6" for="PurchaseSales_3">매입매출</label>
				</div>
			</div>				
		</div>   
		 <?php } else { 
		   // 담당자 추가는 secondordnum 발주처 코드 넣어줘야 함.
		 ?>	
		<div class="d-flex align-items-center"> 
			<span class="input-group-text badge bg-secondary text-white fw-bold fs-6" style="width:100px;"> CODE </span> &nbsp; &nbsp; 				
			<input type="text" class="form-control mt-1" style="width:100px;" id="secondordnum" name="secondordnum" value="<?=$secondordnum?>" readonly >										
		</div>  
		 <?php } ?>			
			<div class="d-flex align-items-center justify-content-center ">
				<table class="table table-bordered" >
					<tbody>
						<tr>
							<td colspan="2" class="text-center fw-bold"  >거래처코드(사업자번호) </td>
							<td colspan="2" class="text-center" > 
								<input type="text" class="form-control" id="vendor_code" name="vendor_code" value="<?=$vendor_code?>"> 
							</td>		
						</tr>	
						<tr>
							<td class="text-center fw-bold" style="width:150px;" >거래처 명</td>
							<td class="text-center"> 
									<input type="text" class="form-control" id="vendor_name" name="vendor_name" style="width:250px;" value="<?=$vendor_name?>">    
							</td>				
							<td class="text-center fw-bold" style="width:170px;" >대표자 성함</td>
							<td class="text-center fw-bold" >
								<input type="text" class="form-control" id="representative_name" name="representative_name"  style="width:200px;" value="<?=$representative_name?>">  
							</td>
						</tr>							
							
						<tr>
							<td class="text-center fw-bold">주소</td>
							<td colspan="3" class="text-center"> 
								<input type="text" class="form-control" id="address" name="address" value="<?=$address?>">   							
						</tr>
						<tr>				
							<td  class="text-center fw-bold">업태</td>
							<td class="text-center"> 
								<input type="text" class="form-control" id="business_type" name="business_type" value="<?=$business_type?>">     
							</td>							
							<td class="text-center fw-bold" > 종목 </td>	
							<td class="text-center"> 
								<input type="text" class="form-control" id="item_type" name="item_type" value="<?=$item_type?>">  
							</td>																					
						</tr>
						<tr>				
							<td  class="text-center fw-bold">전화</td>
							<td class="text-center"> 
								<input type="text" class="form-control" id="phone" name="phone" value="<?=$phone?>">  
							</td>							
							<td class="text-center fw-bold" > 모바일 </td>	
							<td class="text-center"> 
								<input type="text" class="form-control" id="mobile" name="mobile" value="<?=$mobile?>"> 
							</td>																					
						</tr>
						<tr>				
							<td  class="text-center fw-bold">이메일</td>
							<td class="text-center"> 
								<input type="email" class="form-control" id="email" name="email" value="<?=$email?>">       
							</td>							
							<td class="text-center fw-bold" > 팩스 </td>	
							<td class="text-center"> 
								<input type="text" class="form-control" id="fax" name="fax" value="<?=$fax?>">    
							</td>																					
						</tr>
						<tr>				
							<td  class="text-center fw-bold">담당자명</td>
							<td class="text-center"> 
								<input type="text" class="form-control" id="manager_name" name="manager_name" value="<?=$manager_name?>">       
							</td>							
							<td class="text-center fw-bold" > 담당자Tel </td>	
							<td class="text-center"> 
								<input type="text" class="form-control" id="contact_info" name="contact_info" value="<?=$contact_info?>">      
							</td>																					
						</tr>
							
						<tr>
							<td class="text-center fw-bold">비고</td>
							<td colspan="3" class="text-center"> 
								<textarea class="form-control" id="note" name="note"><?=$note?></textarea>    							
						</tr>						
						
					</tbody>
				</table>   
			</div>		 

		<?php 
		  if($represent =='대표코드') { ?>			
			<div class="d-flex justify-content-center">    
				 <table class="table table-bordered w-80" style="padding:2px!important;">
						 <thead class="table-primary">
							<tr>
								<th colspan="4" class="text-center" > 발주처 설정</th>								
							</tr>
							<tr>
								<th class="text-center" > ID</th>
								<th class="text-center" > Password </th>
								<th class="text-center  text-secondary" > 매입 결제일 </th>								
								<th class="text-center  text-primary" > 매출 결제일 </th>								
							</tr>
						</thead>
							<tbody>
								<tr>
									<td class="text-center w-25">										
											<input type="text" id="pid" name="pid" value="<?= $pid ?>"  class="form-control text-center noborder" >
									</td>
									<td class="text-center w-25">										
											<input type="text" id="ppw" name="ppw" value="<?= $ppw ?>"  class="form-control text-center " >
									</td>	
									<td class="text-center align-middle w-25">
										<div class="d-flex align-items-center justify-content-center">											
											<select id="secondordpaydate" name="secondordpaydate" class="form-select text-center w-auto" style="font-size:0.8rem;height:32px;">
												<option value="당월말" <?= $secondordpaydate == '당월말' ? 'selected' : '' ?>>당월말</option>
												<option value="익월말" <?= $secondordpaydate == '익월말' ? 'selected' : '' ?>>익월말</option>
												<option value="없음" <?= $secondordpaydate == '없음' ? 'selected' : '' ?>>없음</option>
												<?php if($secondordpaydate && !in_array($secondordpaydate, ['당월말', '익월말', '없음'])): ?>
												<option value="<?= $secondordpaydate ?>" selected><?= $secondordpaydate ?></option>
												<?php endif; ?>
											</select>
										</div>
									</td>																					
									<td class="text-center align-middle w-25">
										<div class="d-flex align-items-center justify-content-center">
											매월 &nbsp; <input type="text" id="paydate" name="paydate" value="<?= $paydate ?>"  class="form-control text-end w60px" > &nbsp; (일)
										</div>
									</td>																					
								</tr>
							</tbody>

					</table>                                        
			</div>  
			<div class="d-flex justify-content-center">    
				 <table class="table table-bordered w-85" style="padding:2px!important;">
					<thead class="table-danger">
						<tr>								
							<th colspan="4" class="text-center" > 악성 채권</th>
						</tr>
						<tr>								
							<th class="text-center  "> 악성 채권 여부</th>
							<th class="text-center  " > 채권 금액 </th>
							<th class="text-center  " > 접수일 </th>
							<th class="text-center  " > 종료일 </th>
						</tr>
					</thead>
						<tbody>
							<tr>								
								<td class="text-center">                                        
									<input type="checkbox" id="baddebt" name="baddebt" value="1" 
										class="form-check-input text-center" 
										<?= ($baddebt === '1') ? 'checked' : '' ?>>
								</td>
								<td class="text-center ">
									<input type="text" id="debtAmount" name="debtAmount" value="<?= $debtAmount ?>" class="form-control text-end" oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/\B(?=(\d{3})+(?!\d))/g, ',')" >
								</td>	
									<!-- write.php 에서 date 필드를 출력하는 부분 예시 -->
									<?php
									// 만약 fixdate 가 "0000-00-00" 이면 공백으로 처리
									$fix = ($fixdate === '0000-00-00') ? '' : $fixdate;
									$end = ($enddate === '0000-00-00') ? '' : $enddate;
									?>

								<td class="text-center ">
									<input type="date" id="fixdate" name="fixdate" value="<?= htmlspecialchars($fix) ?>" class="form-control text-center"  >
								</td>	
								<td class="text-center ">										
									<input type="date" id="enddate" name="enddate" value="<?= htmlspecialchars($end) ?>"  class="form-control text-center"  >
								</td>												
							</tr>
						</tbody>
					</table>                                        
			</div>  
			<div class="d-flex justify-content-center">    
				<table class="table table-bordered w-85" style="padding:2px!important;">
					<thead class="table-danger">							
					<tr>
						<th class="text-center">악성채권 추심 진행내역</th>
					</tr>
					</thead>
					<tbody>
					<tr>	
						<td class="text-center text-primary fw-bold">
						<div class="d-flex align-items-center justify-content-center">
							<textarea id="progress_memo" name="progress_memo" class="form-control text-start autosize-textarea" style="height:80px;"><?= $progress_memo ?></textarea>
						</div>
						</td>				
					</tr>
					</tbody>
				</table>                                        
			</div>
		  <?php } ?>					 		
	</div>
	<div class="d-flex justify-content-center">
		<button type="button" id="saveBtn"  class="btn btn-dark btn-sm me-3">
			<ion-icon name="save-outline"></ion-icon> 저장 
		</button>	
		<button type="button"  id="closeBtn" class="btn btn-outline-dark btn-sm me-2">
			<ion-icon name="close-circle-outline"></ion-icon> Close
		</button>
		</div>
	</div>
		</div>
	</div>
</div>


</form>


<!-- 페이지로딩 -->
<script>
// 페이지 로딩
$(document).ready(function(){	
    var loader = document.getElementById('loadingOverlay');
    loader.style.display = 'none';
});
</script>
	 
<script>

ajaxRequest_write = null;
/* ESC 키 누를시 팝업 닫기 */
// $(document).keydown(function(e){
		// //keyCode 구 브라우저, which 현재 브라우저
		// var code = e.keyCode || e.which;
		
		// if (code == 27) { // 27은 ESC 키번호
			// self.close();
		// }
// });

$(document).ready(function(){	  
	 
	// 창닫기 버튼
	$("#closeBtn").on("click", function() {
		self.close();
	});	


	$("#saveBtn").on("click", function() {
    if (ajaxRequest_write) ajaxRequest_write.abort();
    ajaxRequest_write = $.ajax({
        url: "/phonebook/process.php",
        type: "POST",
        dataType: "json",
        data: $("#board_form").serialize(),
		success: function(res) {
    console.log("AJAX 응답:", res);
    if (!res.success) {
      return alert("저장에 실패했습니다.");
    }

    // 부모창 DataTable 인스턴스
    var dt = opener.dataTable;

    // 기존에 같은 num 이 있으면 삭제
    var selector = 'tr[data-num="' + res.num + '"]';
    var $existing = opener.$(selector);
    if ($existing.length) {
        dt.row($existing).remove();
    }

    // HTML 문자열 → DOM 노드 변환
    // 문자열 맨 앞뒤 공백 제거 후 parse
    var trimmed = res.rowHtml.trim();
    var $parsed = $( trimmed );        // jQuery 객체
    var newRowNode = $parsed.get(0);   // HTMLTableRowElement

    if (!newRowNode || newRowNode.nodeName !== 'TR') {
        console.error("새 행 파싱 실패:", newRowNode);
        return;
    }

    // DataTables 에 추가하고 redraw(false)
    dt.row.add(newRowNode).draw(false);

    // 알림 및 팝업 닫기
    Toastify({ text:"저장완료", duration:3000, close:true,
               gravity:"top", position:"center", backgroundColor:"#4fbe87" })
      .showToast();
    setTimeout(function(){ self.close(); }, 500);
},
        error: function(jqxhr, status, error) {
            console.log(jqxhr, status, error);
        }
    });
});

	
	
});	  // end of ready	
</script>

<script>
// 자동 높이 조절 함수
function autoResizeTextarea(el) {
  el.style.height = 'auto'; // 초기화
  el.style.height = el.scrollHeight + 'px'; // 실제 내용에 맞게 높이 설정
}

// 초기 실행 및 이벤트 바인딩
document.addEventListener('DOMContentLoaded', function() {
  const textareas = document.querySelectorAll('.autosize-textarea');
  textareas.forEach(function(textarea) {
    autoResizeTextarea(textarea); // 페이지 로드시 자동 적용
    textarea.addEventListener('input', function() {
      autoResizeTextarea(this); // 입력시 자동 조절
    });
  });
});
</script>

</body>
</html>