<?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 = '모델별 BOM 생성'; 
?> 
<title> <?=$title_message?> </title>
<?php if($chkMobile==true) { ?>
<style>
  @media (max-width: 1000px) {
    body { font-size: 25px; }
    .form-control, .fw-bold, .table td, .table th { font-size: 25px; }
    button { font-size: 30px; }
    .modal-body, .modal-title { font-size: 30px; }
  }
</style>
<?php } ?>
</head>
<body>         
<?php
$mode = isset($_REQUEST['mode']) ? $_REQUEST['mode'] : '';  
$tablename = isset($_REQUEST['tablename']) ? $_REQUEST['tablename'] : '';  
$model_id = isset($_REQUEST["model_id"]) ? $_REQUEST["model_id"] : '';
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();

// 절곡판단가 등 비용 임시테이블
$tablename_tmp = 'price_bend'; 
try {
	// 최신 데이터를 가져오기 위해 ORDER BY와 LIMIT을 추가
	$sql = "SELECT * FROM {$DB}.$tablename_tmp where (is_deleted IS NULL or is_deleted = '0') ORDER BY num DESC LIMIT 1";
	$stmh = $pdo->prepare($sql); 
	$stmh->execute();
	$row = $stmh->fetch(PDO::FETCH_ASSOC);  // $row 배열로 DB 정보를 불러온다.     	   	
	$itemList = isset($row['itemList']) ? $row['itemList'] : [];
	$load_priceDate = $row['registedate'] ?? '';

	// itemList 문자열일 때만 json_decode 실행
	if (is_string($itemList)) {
		$itemList = json_decode($itemList, true);
	}

	// itemList 유효한 배열이 아닐 경우 빈 배열로 초기화
	if (!is_array($itemList)) {
		$itemList = [];
	}		
	
} catch (PDOException $Exception) {
	print "오류: ".$Exception->getMessage();
}

    
if($mode == 'copy')
{
	try {
		$sql = "SELECT * FROM ".$DB.".models WHERE model_id = ?";
		$stmh = $pdo->prepare($sql);  
		$stmh->bindValue(1, $model_id, PDO::PARAM_INT);      
		$stmh->execute();            
		$row = $stmh->fetch(PDO::FETCH_ASSOC);     
		include '_row.php';
	} catch (PDOException $Exception) {
		print "오류: ".$Exception->getMessage();
	}  
}
else {		
	if($model_id > 0) {    
		try {
			$sql = "SELECT * FROM ".$DB.".models WHERE model_id = ?";
			$stmh = $pdo->prepare($sql);  
			$stmh->bindValue(1, $model_id, PDO::PARAM_INT);      
			$stmh->execute();            
			$row = $stmh->fetch(PDO::FETCH_ASSOC);     
			include '_row.php';
		} catch (PDOException $Exception) {
			print "오류: ".$Exception->getMessage();
		}           
		$mode = 'modify';
	 } else {
		include '_request.php';
		$mode = 'insert';
	 }
 }
 
// 예: getCategoryByName($parentName) 함수가 존재하며,
// '절곡물'이라는 2단계 카테고리의 자식(3단계) 카테고리 이름 배열을 리턴한다.
$l3_list = getCategoryByName('스크린','절곡물');  // 자바스크립트에서 사용함
  
?>
<?php require_once($_SERVER['DOCUMENT_ROOT'] . '/common/modal.php'); ?>   

<form id="board_form" name="board_form" method="post" enctype="multipart/form-data">    
    <input type="hidden" id="model_id" name="model_id" value="<?= isset($row['model_id']) ? $row['model_id'] : '' ?>">
    <input type="hidden" id="mode" name="mode" value="<?= isset($mode) ? $mode : '' ?>">
    <input type="hidden" id="is_deleted" name="is_deleted" value="<?= isset($row['is_deleted']) ? $row['is_deleted'] : '0' ?>">
    <input type="hidden" id="searchtag" name="searchtag" value="<?= isset($row['model_name']) ? $row['model_name'].' '.$row['description'] : '' ?>">
    <input type="hidden" id="update_log" name="update_log" value="<?= isset($row['update_log']) ? $row['update_log'] : '' ?>">
    <input type="hidden" id="tablename" name="tablename" value="<?= isset($tablename) ? $tablename : '' ?>">      

<div class="container-fluid">    
    <div class="card justify-content-center mt-2 mb-5">
		<div class="card-header text-center">
		  <div class="d-flex justify-content-center align-items-center ">
			<span class="text-center fs-5 mx-3"><?=$title_message?></span>(id:<?=$model_id?>)
			<button type="button" class="btn btn-dark btn-sm mx-2"  onclick='location.reload();' > <i class="bi bi-arrow-clockwise"></i> </button>  
			
			<button id="expandAllBtn" type="button" class="btn btn-outline-dark btn-sm mx-2">
			  전체 펼치기
			</button>      
			<button type="button" id="saveBtn" class="btn btn-dark btn-sm mx-1">
			   <i class="bi bi-floppy-fill"></i> 저장
			</button>
			<?php if($model_id > 0 && $mode !== 'copy' ){ ?>
			  <button type="button" id="deleteBtn" class="btn btn-danger btn-sm mx-1">
				<i class="bi bi-trash"></i>  삭제 
			  </button>
			  <!-- 수정모드이면 복사 버튼도 보임 -->
			  <?php if($mode === 'modify'): ?>
				<button type="button" id="copyBtn" class="btn btn-secondary btn-sm mx-1">
				  <i class="bi bi-copy"></i> 복사
				</button>
			  <?php endif; ?>
			<?php } ?>
			<button type="button" id="closeBtn" class="btn btn-outline-dark btn-sm mx-1">
			    &times; 닫기
			</button>
		  </div>
		</div>		
        <div class="card-body">
		 <div class="d-flex justify-content-center">
            <table class="table table-bordered w-100">
                <tbody>
					<tr>
					  <td><label for="major_category">대분류</label></td>
					  <td>
						<select id="major_category" name="major_category"  class="form-select mx-1 w100px" style="font-size: 0.8rem; height: 32px;">
						  <option value="스크린" <?= (isset($row['major_category']) && $row['major_category'] == '스크린') ? 'selected' : '' ?>>스크린</option>
						  <option value="철재" <?= (isset($row['major_category']) && $row['major_category'] == '철재') ? 'selected' : '' ?>>철재</option>
						</select>
					  </td>          
					  <td><label for="model_name">모델명</label></td>
					  <td>
						<!-- 제품모델(KSS01 등) 선택 -->
						<?php  selectModel('model_name', $model_name);  ?>	
					  </td>					  
					   <td><label for="guiderail_type"> 가이드레일 형태 </label> </td>
						<td colspan="1">
							<select id="guiderail_type" name="guiderail_type" class="form-select mx-1 d-block w-auto" style="font-size: 0.8rem; height: 32px;">								
								<option value="">(레일형태)</option>
								<option value="벽면형" <?= (isset($guiderail_type) && $guiderail_type == '벽면형') ? 'selected' : '' ?>>벽면형</option>
								<option value="측면형" <?= (isset($guiderail_type) && $guiderail_type == '측면형') ? 'selected' : '' ?>>측면형</option>								
							</select>								
					   </td>	
					  <td><label for="finishing_type">마감타입</label></td>
					  <td>
						<select id="finishing_type" name="finishing_type"  class="form-select mx-1 w100px" style="font-size: 0.8rem; height: 32px;">
						  <option value="SUS마감" <?= (isset($row['finishing_type']) && $row['finishing_type'] == 'SUS마감') ? 'selected' : '' ?>>SUS마감</option>
						  <option value="EGI마감" <?= (isset($row['finishing_type']) && $row['finishing_type'] == 'EGI마감') ? 'selected' : '' ?>>EGI마감</option>
						</select>
					  </td>
					</tr>
                    <tr>
                        <td><label for="description">설명</label></td>
                        <td colspan="7">
                            <textarea id="description" name="description" class="form-control"  autocomplete="off" style="height:50px;" ><?= isset($row['description']) ? $row['description'] : '' ?></textarea>
                        </td>
                    </tr>
                </tbody>
            </table>
			</div>			
			<!-- 모델 상세 폼 하단에 부품 관리 섹션 추가 -->
			<div class="container-fluid mt-3">
				<div class="d-flex justify-content-center align-items-center mb-2">
				  <h5> 	<span class="mx-2"> 부품(2단계) 관리 </span>
						<button type="button" class="btn btn-outline-primary btn-sm" id="addPartBtn"> + 부품 추가</button>
				  </h5>
			    </div>
				<table class="table table-bordered" id="partsTable">			  
				<thead class="table-secondary">
				  <tr>
					<th class="text-center w50px">#</th>
					<th class="text-center w150px"> 중분류 부품명</th>
					<th class="text-center w150px">규격</th>
					<th class="text-center w50px">단위</th>
					<th class="text-center w50px">수량</th>
					<th class="text-center w80px">단가</th>
					<th class="text-center w150px">비고(메모)</th>
					<th class="text-center" style="width:150px;">행 추가/삭제, <i class="bi bi-caret-down"></i> 하위부품</th>
				  </tr>
				</thead>
				<tbody>
				  <?php
				  // 현재 모델에 속한 부품 데이터 로드 (2단계: parts 테이블)
				  $sql = "SELECT * FROM ".$DB.".parts WHERE model_id = ? AND is_deleted = 0 ORDER BY part_id ASC";
				  $stmt = $pdo->prepare($sql);
				  $stmt->execute([$model_id]);
				  $partNum = 1;
				  while($partRow = $stmt->fetch(PDO::FETCH_ASSOC)) {
					  include '_part_row.php';
					  $partNum++;
				  }
				  ?>
				</tbody>
			  </table>
			</div>

        </div>
    </div>
	
	<!-- bending 아이템 검색 모달 -->
	<div class="modal fade" id="bendingSearchModal" tabindex="-1" aria-labelledby="bendingSearchModalLabel" aria-hidden="true">
	  <div class="modal-dialog modal-full modal-dialog-centered">
		<div class="modal-content">
		  <div class="modal-header">
			<h5 class="modal-title" id="bendingSearchModalLabel">절곡품 아이템 찾기</h5>
			<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
		  </div>
		  <div class="modal-body" style="max-height: 400px; overflow-y: auto;">
			<!-- 검색결과가 표시될 영역 -->
			<div id="bendingSearchResults"></div>
		  </div>
		</div>
	  </div>
	</div>
	
</div>
</form>

<script>
$(document).ready(function(){    
    var loader = document.getElementById('loadingOverlay');
    if(loader)
        loader.style.display = 'none';
});

var ajaxRequest_write = null;

$("#closeBtn").on("click", function() {
    self.close();
});  

$("#saveBtn").on("click", function() {	

    let msg = '저장완료';
	
    var form = $('#board_form')[0];           
    var data = new FormData(form);            
    
    if (ajaxRequest_write !== null) {
        ajaxRequest_write.abort();
    }
	
    showMsgModal(2); // 파일저장중
	
    ajaxRequest_write = $.ajax({
        url: "insert.php",
        type: "post",
        data: data,
        processData: false,
        contentType: false,
        success: function(data) {
			console.log(data);            
			$(opener.location).attr("href", "javascript:reloadlist();");			
            setTimeout(function() {
				hideMsgModal();
				self.close();                                   
				// location.reload();
            }, 1000);             
        },
        error: function(jqxhr, status, error) {
            console.log(jqxhr, status, error);
			hideMsgModal();
        }                           
    });                                                 
});         

$("#deleteBtn").on("click", function() {
    var delId = $("#model_id").val();
    delFn(delId);
});

$("#copyBtn").on("click", function() {
    // 복사 모드로 전환 (기존 mode 필드의 값을 "copy"로 변경)
    $("#mode").val("copy");
    
    // 복사 진행 전 사용자 확인 (Swal 이용)
    Swal.fire({
        title: '복사 확인',
        text: "현재 모델의 BOM 데이터를 복사하여 새 모델로 생성합니다. 계속하시겠습니까?",
        icon: 'info',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: '복사',
        cancelButtonText: '취소'
    }).then((result) => {
        if (result.isConfirmed) {
            // 확인되면 폼 제출 (insert.php에서 mode=="copy"에 따라 새 레코드로 처리)
            $("#board_form").submit();
        }
    });
});

function delFn(delId) {
    $("#mode").val("delete");
    $("#model_id").val(delId);

    Swal.fire({
        title: '모델 삭제',
        text: "모델 삭제는 신중하셔야 합니다. 정말 삭제 하시겠습니까?",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: '삭제',
        cancelButtonText: '취소'
    }).then((result) => {
        if (result.isConfirmed) {
            if (ajaxRequest_write !== null) {
                ajaxRequest_write.abort();
            }      
            ajaxRequest_write = $.ajax({
                url: "insert.php",
                type: "post",
                data: $("#board_form").serialize(),
                success: function(data) {
                    console.log(data);
                    Toastify({
                        text: "모델 삭제 완료!",
                        duration: 3000,
                        close: true,
                        gravity: "top",
                        position: "center",
                        backgroundColor: "#4fbe87"
                    }).showToast();
                    setTimeout(function() {
                        $(opener.location).attr("href", "javascript:reloadlist();");
                        self.close();
                    }, 1000);                                        
                },
                error: function(jqxhr, status, error) {
                    console.log(jqxhr, status, error);
                }
            });                                                
        } 
    }); 
}

// 부품 행 일련번호 갱신 함수
function updatePartSerialNumbers() {
  $('#partsTable > tbody > tr').filter(':not(.subparts-row)').each(function(index) {
    $(this).find('.part-serial').text(index + 1);
  });
}

function addPartRow(tableBody, rowData = {}) {
  var newRow = $('<tr>');
  newRow.attr('data-part_id', '');

  // 1번 칸: 일련번호 및 검색 버튼
  var rowStr = '';
  rowStr += '<td class="text-center">';
  rowStr += '  <div class="d-flex justify-content-center">';
  rowStr += '    <span class="part-serial mx-1"></span>';
  rowStr += '    <button type="button" style="padding:2;" class="btn btn-primary btn-sm search-bending-btn" onclick="openBendingSearchModal(this)">';
  rowStr += '      <i class="bi bi-search"></i>';
  rowStr += '    </button>';
  rowStr += '  </div>';
  rowStr += '</td>';
  newRow.append(rowStr);

  // 2번 칸: 중분류 select 박스
  var selectHtml = '<select name="part_name[]" class="form-select w-auto mx-1" style="font-size: 0.8rem; height: 32px;">';
  selectHtml += '<option value="">' + "(선택)" + '</option>';

  var itemsList = <?php echo json_encode($l3_list, JSON_UNESCAPED_UNICODE); ?>;

  if (typeof itemsList !== 'undefined' && Array.isArray(itemsList)) {
    for (var i = 0; i < itemsList.length; i++) {
      var itemName = (itemsList[i].item_name) ? itemsList[i].item_name : itemsList[i];
      var selected = (rowData.part_name && rowData.part_name === itemName) ? ' selected' : '';
      selectHtml += '<option value="' + itemName + '"' + selected + '>' + itemName + '</option>';
    }
  }
  selectHtml += '</select>';
  newRow.append('<td class="text-center">' + selectHtml + '</td>');

  // 3~7번 칸: 나머지 입력 필드들
  newRow.append('<td class="text-center"><input type="text" name="spec[]" autocomplete="off" class="form-control" value="' + (rowData.spec || '') + '"></td>');
  newRow.append('<td class="text-center"><input type="text" name="unit[]" autocomplete="off" class="form-control" value="' + (rowData.unit || 'SET') + '"></td>');
  newRow.append('<td class="text-center"><input type="number" name="quantity[]" autocomplete="off" class="form-control" value="' + (rowData.quantity || '1') + '"></td>');
  newRow.append('<td class="text-center"><input type="number" name="unitprice[]" autocomplete="off" class="form-control" value="' + (rowData.unitprice || '1') + '"></td>');
  newRow.append('<td class="text-center"><input type="text" name="memo[]" autocomplete="off" class="form-control" value="' + (rowData.memo || '') + '"></td>');

  // 8번 칸: 버튼 및 hidden input
  var actionCell = '';
  actionCell += '<td class="text-center">';
  actionCell += '<button type="button" class="btn btn-outline-dark btn-sm add-part-row" style="padding:5px;">+</button> ';
  actionCell += '<button type="button" class="btn btn-outline-danger btn-sm remove-part-row" style="padding:5px;">-</button> ';
  actionCell += '<button type="button" class="btn btn-outline-secondary btn-sm toggle-subparts"><i class="bi bi-caret-down"></i>하위 부품</button>';
  actionCell += '<input type="hidden" name="part_id[]" value="">';
  actionCell += '</td>';
  newRow.append(actionCell);

  // 메인 행 추가
  tableBody.append(newRow);

  // 하위 부품용 <tr> 생성 및 추가
  var subpartsRow = $('<tr class="subparts-row">').attr('data-part_id', '').attr('data-part-name', rowData.part_name || '');
  var subpartsCol = '';
  subpartsCol += '<td colspan="8">';
  subpartsCol += '  <div class="subparts-container d-flex justify-content-center">';
  subpartsCol += '    <table class="table table-sm table-bordered subpartsTable w-95">';
  subpartsCol += '      <thead class="table-success">';
  subpartsCol += '        <tr>';
  subpartsCol += '          <th class="text-center w150px">부품명</th>';
  subpartsCol += '          <th class="text-center">재질</th>';
  subpartsCol += '          <th class="text-center">연신율 합</th>';
  subpartsCol += '          <th class="text-center">전개도 합</th>';
  subpartsCol += '          <th class="text-center w110px">연신율 + 전개도</th>';
  subpartsCol += '          <th class="text-center w100px">면적당 단가</th>';
  subpartsCol += '          <th class="text-center w110px">단가</th>';
  subpartsCol += '          <th class="text-center w60px">수량</th>';
  subpartsCol += '          <th class="text-center w110px">단가합계</th>';
  subpartsCol += '        </tr>';
  subpartsCol += '      </thead>';
  subpartsCol += '      <tbody class="subpartsTable">';
  subpartsCol += '        <!-- 하위 부품 데이터 동적 삽입 예정 -->';
  subpartsCol += '      </tbody>';
  subpartsCol += '    </table>';
  subpartsCol += '  </div>';
  subpartsCol += '</td>';

  subpartsRow.append(subpartsCol);
  tableBody.append(subpartsRow);

  updatePartSerialNumbers();
}


$(document).ready(function() {
	// 상단 "부품 추가" 버튼 클릭 시 (1단계 부품 행 하나 추가)
	$("#addPartBtn").on("click", function(e) {
		e.stopPropagation();
		addPartRow($('#partsTable > tbody'));
	});

	// 동적으로 추가된 각 부품 행의 "+" 버튼 클릭 시 (새로운 부품 행 추가)
	$('#partsTable > tbody').on('click', '.add-part-row', function(e) {
		e.stopPropagation();
		addPartRow($('#partsTable > tbody'));
	});

	$('#partsTable > tbody').on('click', '.remove-part-row', function(e) {
		e.stopPropagation();
		// 현재 1단계 부품 행을 찾고, 해당 part_id를 가져옴
		var $partRow = $(this).closest('tr');
		var partId = $partRow.data('part_id');

		// 1단계 부품 행 삭제
		$partRow.remove();

		// 같은 part_id를 가진 하위 부품 행(2단계)도 삭제
		$('#partsTable > tbody > tr.subparts-row[data-part_id="' + partId + '"]').remove();
		
		updatePartSerialNumbers();
	});
	
});

// 하위 부품 관리 영역 토글
$(document).on('click', '.toggle-subparts', function() {
    var tr = $(this).closest('tr');
    var partId = tr.data('part_id');
    var subpartsRow = $('tr.subparts-row[data-part_id="'+partId+'"]');
    subpartsRow.toggle();
});
 
// 하위 부품 행 일련번호 갱신 함수
function updateSubpartSerialNumbers(tableBody) {
    tableBody.find('tr').each(function(index) {
        $(this).find('.subpart-serial').text(index + 1);
    });
}


$(document).ready(function(){    
   var title = '<?=$title_message;?>';
   saveMenuLog(title);
});

// 하위 부품 전체 펼치기버튼 
$(document).ready(function(){
    $("#expandAllBtn").on("click", function(){
        var btn = $(this);
        if(btn.text().trim() === "전체 펼치기") {
            // 모든 하위 부품 영역 펼치기 (slideDown 애니메이션)
            $("tr.subparts-row").slideDown();
            btn.text("전체 접기");
        } else {
            // 모든 하위 부품 영역 접기 (slideUp 애니메이션)
            $("tr.subparts-row").slideUp();
            btn.text("전체 펼치기");
        }
    });	
	 $("#expandAllBtn").trigger("click");	
});
</script>

<script>
// PHP의 모델 목록 데이터를 JavaScript 변수로 전달
var modelsList = <?= json_encode($modelsList) ?>;
// 기존 선택된 모델명 (있다면)
var selectedModel = $("#model_name").val();

$("#major_category").on("change", function() {
    var selectedMajor = $(this).val();
    var $modelSelect = $("#model_name");
    $modelSelect.empty();
    $modelSelect.append('<option value="">모델 선택</option>');
    
    $.each(modelsList, function(index, model) {
        // 대분류가 빈 값이거나, 해당 모델의 slatitem이 선택된 대분류와 일치하면 옵션 추가
        if (selectedMajor === "" || model.slatitem === selectedMajor) {
            var option = $('<option></option>')
                .attr('value', model.model_name)
                .text(model.model_name);
            // 이전에 선택된 모델이 있다면 재선택
            if (model.model_name === selectedModel) {
                option.prop('selected', true);
            }
            $modelSelect.append(option);
        }
    });
});
// 페이지 로드 시, 현재 대분류에 맞게 모델명 목록 업데이트
// $("#major_category").trigger("change");

function openBendingSearchModal(btn) {
    window.currentSearchButton = btn;
    // 상단 검색폼의 대분류 값은 그대로 사용하고,
    // 현재 subpart 행의 조상인 subparts-row에서 부모 부품의 선택값을 가져옵니다.
    var major_category = $("#major_category").val(); 
    // 현재 버튼이 속한 tr 요소 찾기
    var subpartsRow = $(btn).closest('tr');
    // tr 요소 내에서 part_name select 요소의 선택된 값 가져오기
    var selectedBendingCategory = subpartsRow.find('select[name="part_name[]"]').val();	    
    var model_name = $("#model_name").val(); 
    var finishing_type = $("#finishing_type").val(); 
    var spec = $("#spec").val(); 
    var guiderail_type = $("#guiderail_type").val();	
  
    $.ajax({
        url: "/bendingfee/searchBending.php",
        type: "GET",
        data: { 
            major_category: major_category, 
            seconditem: selectedBendingCategory, 
            model_name: model_name, 
            finishing_type: finishing_type, 
            check_type: guiderail_type,   // 가이드레일 측면형, 벽면형 구분
            spec: spec 
        },
        success: function(response) {
            $("#bendingSearchResults").html(response);
            var modal = new bootstrap.Modal(document.getElementById('bendingSearchModal'));
            modal.show();
        },
        error: function(xhr, status, error) {
            console.error("Error fetching bending items: " + error);
        }
    });
}

function selectBendingItem(data) {
    console.log('return data', data);
    var btn = window.currentSearchButton;
    var row = $(btn).closest('tr');

    // sumList 파싱
    var number = "";
    try {
        var parsedList;
        if (typeof data.sumList === "string") {
            parsedList = JSON.parse(data.sumList);
        } else {
            parsedList = data.sumList;
        }
        if (Array.isArray(parsedList)) {
            number = parsedList.length > 0 ? parsedList[parsedList.length - 1] : "";
        } else {
            number = parsedList;
        }
    } catch (error) {
        console.error("JSON 파싱 오류:", error, "sumList 원본 데이터:", data.sumList);
    }

   // 해당 행의 입력란 업데이트
    row.find('input[name="subpart_name[]"]').val(data.itemName);
    row.find('input[name="sub_spec[]"]').val(data.item_spec !== null ? data.item_spec : "");
    row.find('input[name="material[]"]').val(data.material);
    row.find('input[name="horizontal_width[]"]').val(number);
    row.find('input[name="image_url[]"]').val(data.imgdata);

    // bending 아이템의 이미지 데이터 (imgdata)를 사용하여 이미지 태그 생성
    var imageFile = data.imgdata;
    var imageHtml = "";
    if (imageFile) {
        var imagePath = '/bending/img/' + imageFile;
        imageHtml = '<img src="' + imagePath + '" alt="이미지" style="max-width:100px;">';
    }
    // 하위 부품 행에서 이미지 셀은 7번째 td (인덱스 6)
    row.find('td').eq(6).html(imageHtml);

    // 모달 닫기
    var modalEl = document.getElementById('bendingSearchModal');
    var modalInstance = bootstrap.Modal.getInstance(modalEl);
    modalInstance.hide();
}

function selectGuidrail(rowElement, num) {
    var item_bend = <?php echo isset($itemList) ? json_encode($itemList) : '[]'; ?>;

    // 현재 버튼이 속한 tr 요소 찾기
    var btn = window.currentSearchButton;
    var subpartsRow = $(btn).closest('tr');

    // 현재 tr과 연결된 하위 tbody 찾기
    var subpartsTbody = subpartsRow.next('tr').find('tbody.subpartsTable'); // 올바르게 찾는 방식

    if (subpartsTbody.length === 0) {
        console.warn("하위 tbody.subpartsTable을 찾을 수 없습니다.");
        return;
    }
	
	var part_id = subpartsRow.find('input[name="part_id[]"]').val();
    
    // spec[] 입력 필드를 찾아 값을 설정
    var $specInput = subpartsRow.find('input[name="spec[]"]');
    
    console.log("현재 선택된 행 part_id :", part_id);
    // console.log("현재 선택된 행:", subpartsRow);
    // console.log("선택된 spec 요소:", $specInput);
    // console.log("subpartsTbody:", subpartsTbody);
    
    var selectedspec = subpartsRow.find('select[name="part_name[]"]').val();
    
    // alert(selectedspec);
    // console.log(selectedspec);
    
    if (typeof item_bend === 'string') {
        try {
            item_bend = JSON.parse(item_bend);
        } catch (e) {
            console.error('JSON 파싱 오류:', e);
            item_bend = [];
        }
    }
    if (!Array.isArray(item_bend)) {
        item_bend = [];
    }

    var $row = $(rowElement);
    var model_name = $row.data('model_name');
    var rail_length = $row.data('rail_length');
    var rail_width  = $row.data('rail_width');
    var finishing_type = $row.data('finishing_type');
    var seconditem = $row.data('seconditem');
    var check_type = $row.data('check_type');

    // spec[] 입력 필드에 값 설정
    if ($specInput.length) {
        $specInput.val(rail_length + '*' + rail_width);
    } else {
        console.warn("spec[] 입력 필드를 찾을 수 없습니다.");
    }

    $.ajax({
       url: '/bendingfee/ajax_getGuiderailData.php',
       type: 'POST',
       data: {
         model_name: model_name,
         seconditem: seconditem,
         finishing_type: finishing_type,
         rail_length: rail_length,
         rail_width: rail_width,
         check_type: check_type
       },
       dataType: 'json',
       success: function(response) {
         var tableBody = '';
		 var UnitSum = 0;
         response.forEach(function(product, index) {
            var bendSum = 0;
            if (product.bendingRates && product.bendingRates.length > 0) {
                product.bendingRates.forEach(function(rate) {
                    bendSum += Number(rate);
                });
            }
            var plateSum = (product.sums && product.sums.length > 0) ? product.sums[product.sums.length - 1] : 0;
            var finalSum = bendSum + plateSum;

            var unitPrice = '';
            var computedPrice = 0;
			

            // 재질을 가져오고 공백 제거 후 대문자로 변환
            var appliedMaterial = (product.material ? product.material.trim().toUpperCase() : "");

            // 두께에서 숫자만 추출 (공백 및 'T' 제거)
            var appliedThickness = (product.material ? product.material.replace(/[^0-9.]/g, '') : ""); 

            // "EGI" 또는 "SUS"만 추출하여 RawMaterial 값 설정
            var RawMaterial = appliedMaterial.includes("EGI") ? "EGI" :
                              appliedMaterial.includes("SUS") ? "SUS" : "";            

            // 'EGI'가 포함된 경우 매칭 로직 적용
            if (appliedMaterial.includes("EGI")) {
                if (appliedThickness === "1.15") {
                    appliedThickness = "1.2"; 
                } else if (appliedThickness === "1.55") {
                    appliedThickness = "1.6"; 
                }
            }

            var matchedItem = item_bend.find(function(item) {
                return item.col1.toUpperCase() === RawMaterial && item.col5 === appliedThickness;
            });

            var appliedUnitPrice = matchedItem ? parseFloat(matchedItem.col17.toString().replace(/,/g, '')) : 0;

            if (!isNaN(finalSum) && finalSum !== 0 && matchedItem) {
                computedPrice = finalSum * appliedUnitPrice / 1000;
                unitPrice = computedPrice.toLocaleString();
            }

            var quantity = product.surang ;
            var lineTotal = (computedPrice > 0) ? computedPrice * quantity : 0;
            
            tableBody += '<tr>';
			tableBody += '<td><input type="text" name="subpart_name[]" readonly class="form-control text-center" value="' + product.label + '" /></td>';
			tableBody += '<td><input type="text" name="material[]" readonly class="form-control text-center" value="' + appliedMaterial + '" /></td>';
			tableBody += '<td><input type="text" name="bendSum[]"  readonly class="form-control text-end" value="' + bendSum + '" /></td>';
			tableBody += '<td><input type="text" name="plateSum[]" readonly class="form-control text-end" value="' + plateSum + '" /></td>';
			tableBody += '<td><input type="text" name="finalSum[]" readonly class="form-control text-end" value="' + finalSum + '" /></td>';
			tableBody += '<td><input type="text" name="unitPrice[]"  readonly class="form-control text-end" value="' + appliedUnitPrice.toLocaleString() + '" /></td>'; // 적용된 면적당 단가 표시
			tableBody += '<td><input type="text" name="computedPrice[]"  readonly  class="form-control text-end unit-price" value="' + unitPrice + '" /></td>';
			tableBody += '<td><input type="text" name="quantity[]"  readonly class="form-control text-end quantity" value="' + quantity + '" /></td>';
			tableBody += '<td><input type="text" name="lineTotal[]" readonly  class="form-control text-end line-total" value="' + lineTotal.toLocaleString() + '" />';			
			tableBody += '<input type="hidden" name="parent_part_id[]" readonly  class="form-control text-end " value="' + part_id + '" /></td>';	// 부모 part_id		 
            tableBody += '</tr>';
			
			UnitSum += lineTotal;
         });	 
				 
		subpartsTbody.html(tableBody);  

		// 🔽 여기에서 UnitSum 값을 부모 행의 unitprice에 넣기
		var $unitPriceInput = subpartsRow.find('input[name="unitprice[]"]');
		if ($unitPriceInput.length) {
			$unitPriceInput.val(UnitSum.toLocaleString());
		} else {
			console.warn("부모 unitprice[] 필드를 찾을 수 없습니다.");
		}
 
       },
       error: function(jqXHR, textStatus, errorThrown) {
         console.error("AJAX 호출 실패: " + textStatus, errorThrown);
       }
    });
	
	$('#bendingSearchModal').modal('hide');	
}

function selectCase(rowElement, num) {
    var item_bend = <?php echo isset($itemList) ? json_encode($itemList) : '[]'; ?>;
    
    if (typeof item_bend === 'string') {
        try {
            item_bend = JSON.parse(item_bend);
        } catch (e) {
            console.error('JSON 파싱 오류:', e);
            item_bend = [];
        }
    }
    if (!Array.isArray(item_bend)) {
        item_bend = [];
    }

    console.log('단가표 : ', item_bend);
	
    var $row = $(rowElement);
    var box = $row.data('box');
    var check_type = $row.data('check_type');
    var box_width  = $row.data('box_width');
    var box_height = $row.data('box_height');
    var front_bottom_width = $row.data('front_bottom_width');
    var rail_width = $row.data('rail_width');
    var seconditem = $row.data('seconditem');

    $("#check_type").val(check_type);
    $("#box_width").val(box_width);
    $("#box_height").val(box_height);
    $("#front_bottom_width").val(front_bottom_width);
    $("#rail_width").val(rail_width);
    
    $("#spec").val(box_width + '*' + box_height);

    $.ajax({
       url: '/bendingfee/ajax_getCaseData.php',
       type: 'POST',
       data: {
         seconditem: seconditem,
         check_type: check_type,
         box_width: box_width,
         box_height: box_height,
         front_bottom_width: front_bottom_width,         
         rail_width: rail_width
       },
       dataType: 'json',
       success: function(response) {
          console.log(response);
         var tableBody = '';
         response.forEach(function(product, index) {
             
            // '마구리'라는 단어가 포함된 항목은 제외
            if (product.label.includes('마구리')) {
                return;
            }

            var bendSum = 0;
            if (product.bendingRates && product.bendingRates.length > 0) {
                product.bendingRates.forEach(function(rate) {
                    bendSum += Number(rate);
                });
            }
            var plateSum = (product.sums && product.sums.length > 0) ? product.sums[product.sums.length - 1] : 0;
            var finalSum = bendSum + plateSum;

            var unitPrice = '';
            var computedPrice = 0;
            var meterUnitPrice = 0;

            // EGI 1.55T → EGI 1.6T 적용
            var appliedMaterial = "EGI";
            var appliedThickness = "1.6"; 

            var matchedItem = item_bend.find(function(item) {
                return item.col1.toUpperCase() === appliedMaterial && item.col5 === appliedThickness;
            });

            var appliedUnitPrice = matchedItem ? parseFloat(matchedItem.col17.toString().replace(/,/g, '')) : 0;
            meterUnitPrice = matchedItem ? parseFloat(matchedItem.col18.toString().replace(/,/g, '')) : 0; // 미터당 단가 추가

            if (!isNaN(finalSum) && finalSum !== 0 && matchedItem) {
                computedPrice = finalSum * appliedUnitPrice / 1000;
                unitPrice = computedPrice.toLocaleString();
            }
			
            var quantity = product.surang ;
            var lineTotal = (computedPrice > 0) ? computedPrice * quantity : 0;
            
            tableBody += '<tr>';
            tableBody += '<td>' + product.label + '</td>';
            tableBody += '<td>EGI 1.6T</td>';
            tableBody += '<td>' + bendSum + '</td>';
            tableBody += '<td>' + plateSum + '</td>';
            tableBody += '<td>' + finalSum + '</td>';
            tableBody += '<td>' + appliedUnitPrice.toLocaleString() + '</td>'; // 적용된 면적당 단가 표시            
            tableBody += '<td><input type="text" class="form-control text-end unit-price" value="' + unitPrice + '" /></td>';
            tableBody += '<td><input type="text" class="form-control text-end quantity" value="' + quantity + '" /></td>';
            tableBody += '<td><input type="text" class="form-control text-end line-total" value="' + lineTotal.toLocaleString() + '" /></td>';
            tableBody += '<td><button type="button" class="btn btn-danger btn-sm delete-row">삭제</button></td>';
            tableBody += '</tr>';
         });
         $('#partsTable tbody').html(tableBody);         
       },
       error: function(jqXHR, textStatus, errorThrown) {
         console.error("AJAX 호출 실패: " + textStatus, errorThrown);
       }
    });

    var btn = window.currentSearchButton;
    var modalEl = document.getElementById('bendingSearchModal');
    var modalInstance = bootstrap.Modal.getInstance(modalEl);
    modalInstance.hide();
}

function selectMarguri(rowElement, num) {
    var item_bend = <?php echo isset($itemList) ? json_encode($itemList) : '[]'; ?>;
    
    if (typeof item_bend === 'string') {
        try {
            item_bend = JSON.parse(item_bend);
        } catch (e) {
            console.error('JSON 파싱 오류:', e);
            item_bend = [];
        }
    }
    if (!Array.isArray(item_bend)) {
        item_bend = [];
    }

    console.log('단가표 : ', item_bend);

    var $row = $(rowElement);
    var item_name = $row.data('item_name');
    var item_spec = $row.data('item_spec'); // '450*800' 형태
    var material = 'EGI 1.6T'; // 마구리는 1.55T 대신 1.6T로 고정
    
    $("#spec").val(item_spec);

    var imgdata = $row.data('imgdata');
    $("#imageBending").attr('src', imgdata ? imgdata : '../img/no_image.png');

    var dimensions = item_spec.split('*').map(Number);
    if (dimensions.length !== 2 || isNaN(dimensions[0]) || isNaN(dimensions[1])) {
        console.error("item_spec 값 오류: ", item_spec);
        return;
    }
    var width = dimensions[0] + 100;
    var height = dimensions[1] + 100;
    
    // 면적 계산 (mm^2 → m^2 변환: / 1,000,000)
    var area = (width * height) / 1000000;

    // 단가 계산
    var unitPrice = 0;
    var computedPrice = 0;
    var meterUnitPrice = 0;

    var appliedMaterial = "EGI";
    var appliedThickness = "1.6"; 

    var matchedItem = item_bend.find(function(item) {
        return item.col1.toUpperCase() === appliedMaterial && item.col5 === appliedThickness;
    });

    var appliedUnitPrice = matchedItem ? parseFloat(matchedItem.col17.toString().replace(/,/g, '')) : 0;
    meterUnitPrice = matchedItem ? parseFloat(matchedItem.col18.toString().replace(/,/g, '')) : 0; // 미터당 단가 추가

    if (!isNaN(area) && area > 0 && matchedItem) {
        computedPrice = Math.round(area * appliedUnitPrice);
        unitPrice = computedPrice.toLocaleString(undefined, { maximumFractionDigits: 0 });
    }

	var quantity = 2 ; // 마구리는 기본2개 설정
    var lineTotal = computedPrice * quantity;

    var tableRow = '<tr>';
    tableRow += '<td>' + item_name + '</td>';
    tableRow += '<td>' + material + '</td>';
    tableRow += '<td>가로폭(' + width + ')</td>';
    tableRow += '<td>세로높이(' + height + ')</td>';
    tableRow += '<td> 면적㎡(' + area.toFixed(2) + ')</td>'; // 면적 소수점 2자리 유지
    tableRow += '<td>' + appliedUnitPrice.toLocaleString() + '</td>'; // 면적당 단가    
    tableRow += '<td><input type="text" class="form-control text-end unit-price" value="' + unitPrice + '" /></td>';
    tableRow += '<td><input type="text" class="form-control text-end quantity" value="' + quantity + '" /></td>';
    tableRow += '<td><input type="text" class="form-control text-end line-total" value="' + lineTotal.toLocaleString(undefined, { maximumFractionDigits: 0 }) + '" /></td>';
    tableRow += '<td><button type="button" class="btn btn-danger btn-sm delete-row">삭제</button></td>';
    tableRow += '</tr>';

    $('#partsTable tbody').html(tableRow);   

    var modalEl = document.getElementById('bendingSearchModal');
    var modalInstance = bootstrap.Modal.getInstance(modalEl);
    modalInstance.hide();
}

function selectBottombar(rowElement, num) {
    var item_bend = <?php echo isset($itemList) ? json_encode($itemList) : '[]'; ?>;

    if (typeof item_bend === 'string') {
        try {
            item_bend = JSON.parse(item_bend);
        } catch (e) {
            console.error('JSON 파싱 오류:', e);
            item_bend = [];
        }
    }
    if (!Array.isArray(item_bend)) {
        item_bend = [];
    }

    var btn = window.currentSearchButton;
    var subpartsRow = $(btn).closest('tr');
    var subpartsTbody = subpartsRow.next('tr').find('tbody.subpartsTable');

    if (subpartsTbody.length === 0) {
        console.warn("하위 tbody.subpartsTable을 찾을 수 없습니다.");
        return;
    }

    var part_id = subpartsRow.find('input[name="part_id[]"]').val();
    var $specInput = subpartsRow.find('input[name="spec[]"]');
    var selectedspec = subpartsRow.find('select[name="part_name[]"]').val();

    var $row = $(rowElement);    
    var model_name = $row.data('model_name');
    var finishing_type = $row.data('finishing_type');
    var rail_length = $row.data('rail_length');
    var rail_width = $row.data('rail_width');

    if ($specInput.length) {
        $specInput.val(rail_length + '*' + rail_width);
    } else {
        console.warn("spec[] 입력 필드를 찾을 수 없습니다.");
    }

    $.ajax({
       url: '/bendingfee/ajax_getBottombarData.php',
       type: 'POST',
       data: {         
         model_name: model_name,
         finishing_type: finishing_type,
         rail_length: rail_length,         
         rail_width: rail_width
       },
       dataType: 'json',
       success: function(response) {
         var tableBody = '';
         var UnitSum = 0;

         response.forEach(function(product, index) {
            if (product.label.includes('L') || product.label.includes('평철')) return;

            var bendSum = 0;
            if (product.bendingRates && product.bendingRates.length > 0) {
                product.bendingRates.forEach(function(rate) {
                    bendSum += Number(rate);
                });
            }

            var plateSum = (product.sums && product.sums.length > 0) ? product.sums[product.sums.length - 1] : 0;
            var finalSum = bendSum + plateSum;
            var unitPrice = '';
            var computedPrice = 0;

            var appliedMaterial = (product.material ? product.material.trim().toUpperCase() : "");
            var appliedThickness = (product.material ? product.material.replace(/[^0-9.]/g, '') : ""); 
            var RawMaterial = appliedMaterial.includes("EGI") ? "EGI" :
                              appliedMaterial.includes("SUS") ? "SUS" : "";

            if (appliedMaterial.includes("EGI")) {
                if (appliedThickness === "1.15") appliedThickness = "1.2";
                else if (appliedThickness === "1.55") appliedThickness = "1.6";
            }

            var matchedItem = item_bend.find(function(item) {
                return item.col1.toUpperCase() === RawMaterial && item.col5 === appliedThickness;
            });

            var appliedUnitPrice = matchedItem ? parseFloat(matchedItem.col17.toString().replace(/,/g, '')) : 0;

            if (!isNaN(finalSum) && finalSum !== 0 && matchedItem) {
                computedPrice = finalSum * appliedUnitPrice / 1000;
                unitPrice = computedPrice.toLocaleString();
            }

            var quantity = product.label.includes('L') ? 2 : 1;
            var lineTotal = (computedPrice > 0) ? computedPrice * quantity : 0;

            tableBody += '<tr>';
            tableBody += '<td><input type="text" name="subpart_name[]" readonly class="form-control text-center" value="' + product.label + '" /></td>';
            tableBody += '<td><input type="text" name="material[]" readonly class="form-control text-center" value="' + appliedMaterial + '" /></td>';
            tableBody += '<td><input type="text" name="bendSum[]" readonly class="form-control text-end" value="' + bendSum + '" /></td>';
            tableBody += '<td><input type="text" name="plateSum[]" readonly class="form-control text-end" value="' + plateSum + '" /></td>';
            tableBody += '<td><input type="text" name="finalSum[]" readonly class="form-control text-end" value="' + finalSum + '" /></td>';
            tableBody += '<td><input type="text" name="unitPrice[]" readonly class="form-control text-end" value="' + appliedUnitPrice.toLocaleString() + '" /></td>';
            tableBody += '<td><input type="text" name="computedPrice[]" readonly class="form-control text-end unit-price" value="' + unitPrice + '" /></td>';
            tableBody += '<td><input type="text" name="quantity[]" readonly class="form-control text-end quantity" value="' + quantity + '" /></td>';
            tableBody += '<td><input type="text" name="lineTotal[]" readonly class="form-control text-end line-total" value="' + lineTotal.toLocaleString() + '" />';
            tableBody += '<input type="hidden" name="parent_part_id[]" class="form-control text-end" value="' + part_id + '" /></td>';
            tableBody += '</tr>';

            UnitSum += lineTotal;
         });

         subpartsTbody.html(tableBody);

         // UnitSum을 부모 unitprice[] 필드에 입력
         var $unitPriceInput = subpartsRow.find('input[name="unitprice[]"]');
         if ($unitPriceInput.length) {
             $unitPriceInput.val(UnitSum.toLocaleString());
         } else {
             console.warn("부모 unitprice[] 필드를 찾을 수 없습니다.");
         }
       },
       error: function(jqXHR, textStatus, errorThrown) {
         console.error("AJAX 호출 실패: " + textStatus, errorThrown);
       }
    });

    // 모달 닫기
    var modalEl = document.getElementById('bendingSearchModal');
    var modalInstance = bootstrap.Modal.getInstance(modalEl);
    modalInstance.hide();
}


function selectLbar(rowElement, num) {
    var item_bend = <?php echo isset($itemList) ? json_encode($itemList) : '[]'; ?>;
    
    if (typeof item_bend === 'string') {
        try {
            item_bend = JSON.parse(item_bend);
        } catch (e) {
            console.error('JSON 파싱 오류:', e);
            item_bend = [];
        }
    }
    if (!Array.isArray(item_bend)) {
        item_bend = [];
    }

    console.log('단가표 : ', item_bend); 

    var $row = $(rowElement);        
    var itemName = $row.data('itemname');
    var item_spec = $row.data('item_spec');
    var appliedMaterial = $row.data('material'); // data-material에서 가져옴

    // 재질 변환 및 공백 제거
    appliedMaterial = appliedMaterial ? appliedMaterial.trim().toUpperCase() : "";

    var response = $row.data('response');

    console.log('response : ', response);

    try {
        if (typeof response === "string") {
            response = JSON.parse(response);
        }
    } catch (e) {
        console.error('JSON 파싱 오류:', e);
        response = {};
    }

    console.log('파싱 후 response : ', response); 	

    $("#spec").val(item_spec);

    // response 내부의 배열을 개별 변수로 저장
    var inputList = response.inputList || [];
    var bendingrateList = response.bendingrateList || [];
    var sumList = response.sumList || [];    

    // console.log('inputList:', inputList);
    // console.log('bendingrateList:', bendingrateList);
    // console.log('sumList:', sumList);
    // console.log('itemName:', itemName);

    var tableBody = '';

	var bendSum = bendingrateList.reduce((acc, val) => acc + Number(val || 0), 0);
	// var plateSum = sumList.reduce((acc, val) => acc + Number(val || 0), 0);  // 전체를 더하는 공식
	var plateSum = sumList.length > 0 ? Number(sumList.slice(-1)[0]) : 0; // 마지막 값만 가져오는 코드
	
	var finalSum = bendSum + plateSum;

	var unitPrice = '';
	var computedPrice = 0;

	// 두께에서 숫자만 추출 (공백 및 'T' 제거)
	var appliedThickness = (appliedMaterial ? appliedMaterial.replace(/[^0-9.]/g, '') : ""); 

	// "EGI" 또는 "SUS"만 추출하여 RawMaterial 값 설정
	var RawMaterial = appliedMaterial.includes("EGI") ? "EGI" :
					  appliedMaterial.includes("SUS") ? "SUS" : "";			

	console.log("Material:", appliedMaterial, "순수자재 : ", RawMaterial, "Thickness:", appliedThickness);

	// 'EGI'가 포함된 경우 매칭 로직 적용
	if (appliedMaterial.includes("EGI")) {
		if (appliedThickness === "1.15") {
			appliedThickness = "1.2"; 
		} else if (appliedThickness === "1.55") {
			appliedThickness = "1.6"; 
		}
	}

	// 면적당 단가 찾기
	var matchedItem = item_bend.find(function(bendItem) {
		return bendItem.col1.toUpperCase() === RawMaterial && bendItem.col5 === appliedThickness;
	});

	var appliedUnitPrice = matchedItem ? parseFloat(matchedItem.col17.toString().replace(/,/g, '')) : 0;

	if (!isNaN(finalSum) && finalSum !== 0 && matchedItem) {
		computedPrice = finalSum * appliedUnitPrice / 1000;
		unitPrice = computedPrice.toLocaleString();
	}

	var quantity = itemName.includes('L') ? 2 : 1;
	var lineTotal = (computedPrice > 0) ? computedPrice * quantity : 0;

	// **1개의 행만 추가**
	var tableBody = '<tr>';
	tableBody += '<td>' + itemName + '</td>';
	tableBody += '<td>' + appliedMaterial + '</td>';
	tableBody += '<td>' + bendSum + '</td>';
	tableBody += '<td>' + plateSum + '</td>';
	tableBody += '<td>' + finalSum + '</td>';
	tableBody += '<td>' + appliedUnitPrice.toLocaleString() + '</td>'; // 면적당 단가 표시
	tableBody += '<td><input type="text" class="form-control text-end unit-price" value="' + unitPrice + '" /></td>';
	tableBody += '<td><input type="text" class="form-control text-end quantity" value="' + quantity + '" /></td>';
	tableBody += '<td><input type="text" class="form-control text-end line-total" value="' + lineTotal.toLocaleString() + '" /></td>';
	tableBody += '<td><button type="button" class="btn btn-danger btn-sm delete-row">삭제</button></td>';
	tableBody += '</tr>';

	$('#partsTable tbody').html(tableBody);
	
    var btn = window.currentSearchButton;
    var modalEl = document.getElementById('bendingSearchModal');
    var modalInstance = bootstrap.Modal.getInstance(modalEl);
    modalInstance.hide();
}

function changeImage() {
	var $imageBending = $('#imageBending'); // 이미지 요소 참조
    var secondItemVal = $('#seconditem').val();
    // 기본적으로 이미지 초기화
    $imageBending.attr('src', '../img/no_image.png');

    if (secondItemVal === '가이드레일') {
        // 가이드레일 스타일 유지
        $imageBending.css({ "width": "250px", "height": "250px" });		
        // PHP에서 guiderail.json 파일의 내용을 JavaScript 변수에 로드
        var guiderailImages = <?php 
            $jsonFile = $_SERVER['DOCUMENT_ROOT'].'/guiderail/guiderail.json';
            if (file_exists($jsonFile)) {
                echo file_get_contents($jsonFile);
            } else {
                echo '[]';
            }
        ?>;

        function updateImage(model, checkType, finishing_type) {
            let imagePath = '';

            if (Array.isArray(guiderailImages)) {
                let found = guiderailImages.find(function(item) {
                    return item.model_name === model && item.check_type === checkType  && item.finishing_type === finishing_type ;
                });
                if (found) {
                    imagePath = found.image;
                }
            }

             $imageBending.attr('src', imagePath || '../img/no_image.png'); // 기본값 설정
        }

        var selectedProdModel = $("#model_name").val();
        var selected_check_type = $("#check_type").val();
        var finishing_type = $("#finishing_type").val();

        console.log('selectedProdModel', selectedProdModel);
        console.log('selected_check_type', selected_check_type);
        console.log('finishing_type', finishing_type);

        updateImage(selectedProdModel, selected_check_type, finishing_type);
    } 
    else if (secondItemVal === '케이스') {
        // 셔터박스 스타일 변경
        $imageBending.css({ "width": "auto", "height": "auto" });
		
        var selectedCheckType = $("#check_type").val();        
        var imagePath = '../img/box/box_both_sample.jpg'; // 기본 이미지        
                
        $imageBending.attr('src', imagePath);
    }
    else if (secondItemVal === '마구리') {        
        $imageBending.css({ "width": "auto", "height": "auto" });
		
        var selectedCheckType = $("#check_type").val();        
        var imagePath = '../img/box/box_both_Maguri.jpg'; // 기본 이미지        
                
        $imageBending.attr('src', imagePath);
    }
	else if (secondItemVal === '하단마감재') {        
        $imageBending.css({ "width": "450px", "height": "250px" });		
        // PHP에서 bottombar.json 파일의 내용을 JavaScript 변수에 로드
        var bottombarImages = <?php 
            $jsonFile = $_SERVER['DOCUMENT_ROOT'].'/bottombar/bottombar.json';
            if (file_exists($jsonFile)) {
                echo file_get_contents($jsonFile);
            } else {
                echo '[]';
            }
        ?>;

        function updateImage(model, finishing_type) {
            let imagePath = '';

            if (Array.isArray(bottombarImages)) {
                let found = bottombarImages.find(function(item) {
                    return item.model_name === model && item.finishing_type === finishing_type ;
                });
                if (found) {
                    imagePath = found.image;
                }
            }

             $imageBending.attr('src', imagePath || '../img/no_image.png'); // 기본값 설정
        }

        var selectedProdModel = $("#model_name").val();        
        var finishing_type = $("#finishing_type").val();

        console.log('selectedProdModel', selectedProdModel);        
        console.log('finishing_type', finishing_type);

        updateImage(selectedProdModel,  finishing_type);
    }
	else if (secondItemVal === 'L-BAR') {        
        $imageBending.css({ "width": "auto", "height": "auto" });		        
        var imagePath = '../img/Lbar/Lbar2.jpg'; // 기본 이미지                        
        $imageBending.attr('src', imagePath);
    } 	
	else if (secondItemVal === '보강평철') {        
        $imageBending.css({ "width": "auto", "height": "auto" });		        
        var imagePath = '../bending/img/2024_09_28_11_48_24_평철.jpg'; // 기본 이미지                        
        $imageBending.attr('src', imagePath);
    } 	
}

$(document).ready(function() {	
	// Log 파일보기
	$("#showlogBtn").click( function() {     	
		var num = $('#num').val();
		// table 이름을 넣어야 함
		var workitem =  $('#tablename').val();
		// 버튼 비활성화
		var btn = $(this);						
			popupCenter("../Showlog.php?num=" + num + "&workitem=" + workitem , '로그기록', 500, 500);									 
		btn.prop('disabled', false);					 					 
	});		
});


</script>
</body>
</html>