<?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>

</head>
<body>         

<?php require_once($_SERVER['DOCUMENT_ROOT'] . '/myheader.php'); ?>   

<?php
$seconditem = $_REQUEST['seconditem'] ?? '' ;
$model_name = $_REQUEST['model_name'] ?? '' ;
$firstitem = $_REQUEST['firstitem'] ?? '' ;
$mode = $_REQUEST['mode'] ?? '' ;
$search = $_REQUEST['search'] ?? '' ;

$tablename = 'price_bend'; 

try {
	// 최신 데이터를 가져오기 위해 ORDER BY와 LIMIT을 추가
	$sql = "SELECT * FROM {$DB}.$tablename where is_deleted = '0' ORDER BY num DESC LIMIT 1";
	$stmh = $pdo->prepare($sql); 
	$stmh->execute();
	$row = $stmh->fetch(PDO::FETCH_ASSOC);  // $row 배열로 DB 정보를 불러온다.     	   
	$item_bend = $row['itemList'];
	$bendingFeeDate = $row['registedate'];
} catch (PDOException $Exception) {
	print "오류: ".$Exception->getMessage();
}

$tablename = 'BDmodels';
$order_by = "ORDER BY num DESC";

// 기본 조건: is_deleted = 0
$conditions = ["is_deleted = 0"];
$bindParams = [];

if (!empty($search)) {
    try {
        // 1. 텍스트 타입 컬럼만 추출
        $columnsSql = "SHOW COLUMNS FROM {$DB}.{$tablename}";
        $columnsStmt = $pdo->query($columnsSql);
        $searchableColumns = [];

        while ($col = $columnsStmt->fetch(PDO::FETCH_ASSOC)) {
            $field = $col['Field'];
            $type = strtolower($col['Type']);

            // text, varchar, char 형식만 LIKE 검색 대상
            if (strpos($type, 'char') !== false || strpos($type, 'text') !== false) {
                $searchableColumns[] = $field;
            }
        }

        // 2. 컬럼별 개별 placeholder로 조건 생성
        foreach ($searchableColumns as $i => $colName) {
            $ph = ":search{$i}";
            $searchConditions[] = "$colName LIKE $ph";
            $bindParams[$ph] = "%{$search}%";
        }

        if (!empty($searchConditions)) {
            $conditions[] = '(' . implode(' OR ', $searchConditions) . ')';
        }

    } catch (PDOException $e) {
        echo "컬럼 조회 오류: " . $e->getMessage();
    }
}
if (!empty($firstitem)) {
    $conditions[] = "major_category = :firstitem";
    $bindParams[":firstitem"] = $firstitem;
}

if (!empty($seconditem)) {
    $conditions[] = "seconditem = :seconditem";
    $bindParams[":seconditem"] = $seconditem;
}

if (!empty($model_name)) {
    $conditions[] = "model_name = :model_name";
    $bindParams[":model_name"] = $model_name;
}


// 최종 WHERE 조건 조립
$sqlWhere = implode(" AND ", $conditions);
$sql = "SELECT * FROM {$DB}.{$tablename} WHERE {$sqlWhere} {$order_by}";

// echo '<pre>';
// print_r($l1_list);
// echo '</pre>';

try {     
	$stmh = $pdo->prepare($sql);
	$stmh->execute($bindParams);
	$total_row = $stmh->rowCount();          
?>  

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

    <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 ?>">             
	
<div class="container-fluid">
	<div class="card justify-content-center text-center mt-3">
		<div class="card-header">
			<div class="d-flex justify-content-center align-items-center">   
				<span class="text-center fs-5">  <?=$title_message?>   </span>         
				<button type="button" class="btn btn-dark btn-sm mx-3"  onclick='location.reload();' title="새로고침"> <i class="bi bi-arrow-clockwise"></i> </button>  	 
					<!--
					<button type="button" class="btn btn-dark btn-sm mx-1"  onclick="window.location.href='../guiderail/list.php?header=header'" title="가이드레일"> <i class="bi bi-door-open"></i> </button>  	 
					<button type="button" class="btn btn-dark btn-sm mx-1"  onclick="window.location.href='../shutterbox/list.php?header=header'"  title="셔터박스"> <i class="bi bi-file-break"></i>  </button>  	 
					<button type="button" class="btn btn-dark btn-sm mx-1"  onclick="window.location.href='../bottombar/list.php?header=header'"  title="하장바"> <i class="bi bi-input-cursor"></i> </button>  	 
					-->				
			</div>
		</div>	
		<div class="card-body">    
		<div class="alert alert-primary" role="alert">
			마구리는 M당 단가에서 제외함, 케이스는 '양면 점검구 기준', 가이드레일은 기본 1개당 단가
		</div>		
		<?php include $_SERVER['DOCUMENT_ROOT'] . '/lot/lotTable.php'; ?>	
		<div class="d-flex justify-content-center align-items-center mb-4">                                                                           
			<button type="button" class="btn btn-dark btn-sm mx-1" onclick="gotoBendingListBtn(); return false; " > <i class="bi bi-journal-text"></i> 절곡 기초자료 이동 </button>                
			<button type="button" class="btn btn-dark btn-sm mx-1" onclick="loadmodelBtn(); return false; " > <i class="bi bi-pencil-square"></i> 셔터 모델관리 </button>                
			<button type="button" class="btn btn-dark btn-sm mx-1" onclick="loadQCBtn(); return false; " > <i class="bi bi-pencil-square"></i> 절곡물 품목관리 </button>                
			<button type="button" class="btn btn-dark btn-sm mx-1" onclick="loadTreeBtn(); return false; " > <i class="bi bi-pencil-square"></i> 모델 Tree </button>                
			<button type="button" class="btn btn-secondary btn-sm mx-1" onclick="previousBtn(); return false; " > 이전 BOM 화면 </button>    
			<button type="button" class="btn btn-primary btn-sm ms-1 me-1 " onclick="bendingBtn(); return false; " > <i class="bi bi-journal-richtext"></i> 절곡바라시 </button>                
			<button type="button" class="btn btn-primary btn-sm ms-1 me-1 " onclick="guiderailBtn(); return false; " > <i class="bi bi-door-open"></i> 가이드레일  </button>                
            <button type="button" class="btn btn-primary btn-sm mx-1" onclick="caseBtn(); return false; " > <i class="bi bi-file-break"></i> 케이스  </button>                
            <button type="button" class="btn btn-primary btn-sm mx-1" onclick="bottombarBtn(); return false; " > <i class="bi bi-input-cursor"></i> 하장바세트  </button>                            
		</div>
			
			<div class="d-flex p-1 m-1 mt-1 mb-1 justify-content-center align-items-center"> 	 		
			▷  <?= $total_row ?> &nbsp; 		
					
			<!-- 대분류 -->
			<select id="firstitem" name="firstitem"  class="form-select mx-1 d-block w-auto" style="font-size: 0.8rem; height: 32px;">
				<option value="">(대분류)</option>
				<option value="스크린" <?= ($firstitem == '스크린') ? 'selected' : '' ?>>스크린</option>
				<option value="철재" <?= ($firstitem == '철재') ? 'selected' : '' ?>>철재</option>
			</select> &nbsp;

			<!-- 중분류 -->
			<?php
			// 예: getCategoryByName($parentName) 함수가 존재하며,
			// '절곡물'이라는 2단계 카테고리의 자식(3단계) 카테고리 이름 배열을 리턴한다.
			$l3_list = getCategoryByName('스크린','절곡물');
			?>
			<select id="seconditem" name="seconditem" class="form-select mx-1 d-block w-auto" style="font-size: 0.8rem; height: 32px;">
				<option value="">(중분류)</option>
				<?php foreach($l3_list as $itemVal): ?>
					<option 
						value="<?= htmlspecialchars($itemVal, ENT_QUOTES, 'UTF-8') ?>"
						<?= ($seconditem === $itemVal) ? 'selected' : '' ?>>
						<?= htmlspecialchars($itemVal, ENT_QUOTES, 'UTF-8') ?>
					</option>
				<?php endforeach; ?>
			</select>		
			
			<!-- 제품모델(KSS01 등) 선택 -->
			<?php  selectModel('model_name', $model_name);  ?>				
			
			<div class="inputWrap">
				<input type="text" id="search" class="form-control" style="width:150px;" name="search" autocomplete="off" value="<?=$search?>" onKeyPress="if (event.keyCode==13){ enter(); }">
				<button class="btnClear"></button>
			</div>				
			<div id="autocomplete-list"></div>				
			<button id="searchBtn" type="button" class="btn btn-dark btn-sm mx-1"><i class="bi bi-search"></i> 검색 </button>			
			<button type="button" class="btn btn-dark btn-sm mx-1" id="newBtn"><i class="bi bi-pencil-fill"></i> 신규</button>
			<button type="button" class="btn btn-dark btn-sm mx-1" onclick="generateExcel();" > <i class="bi bi-file-earmark-spreadsheet"></i> 엑셀다운로드 </button>
		</div>	 
		</div> <!--card-body-->
	   </div> <!--card -->   
</div> <!--container-fluid -->   

<div class="container-fluid">  
		<div class="row justify-content-center">
		<div class="card w-50">
			<div class="card-body">
				<div class="d-flex justify-content-center align-items-center" >
					<h5 class="card-title text-center">절곡 ㎡ 단가표 (기준일: <?=$bendingFeeDate?>) </h5>
					<span id="bendTableUnitToggle" class="badge bg-secondary ms-3 me-2">
						<i class="bi bi-chevron-down"></i>
					</span>
				</div>
				<table id="item_bendTable" class="table table-bordered table-hover">
					<thead class="table-primary text-center">
						<tr>
							<th class="align-middle">품목</th>
							<th class="align-middle">규격</th>
							<th class="align-middle">두께(T)</th>
							<th class="align-middle">비중</th>
							<th class="align-middle">㎡ / 단가</th>
						</tr>
					</thead>
					<tbody>
						<!-- Additional Rows Go Here -->
					</tbody>
				</table>
			</div>
		</div>
	</div> <!--row-->	 
	<div class="table-responsive"> 
        <table class="table table-hover" id="myTable">        
			<thead class="table-primary">								
				<th class="text-center" style="width:50px;">번호</th>
				<th class="text-center" style="width:100px;">대분류</th>
				<th class="text-center" style="width:250px;">중분류</th>
				<th class="text-center" style="width:150px;">모델명</th>
				<th class="text-center" style="width:100px;">형상</th>
				<th class="text-center" style="width:130px;">마감타입</th>
				<th class="text-center" style="width:150px;">규격</th>
				<th class="text-center" style="width:80px;">박스폭</th>
				<th class="text-center" style="width:80px;">박스높이</th>
				<th class="text-center" style="width:80px;">전면밑</th>
				<th class="text-center" style="width:80px;">레일폭</th>
				<th class="text-center" style="width:80px;" > <i class="bi bi-image"></i> 형태 </th>  
				<th class="text-center" style="width:80px;">단가/M</th>
				<th class="text-center" style="width:160px;">메모</th>
				<th class="text-center" style="width:100px;">단가기준일</th>
				<th class="text-center" style="width:140px;">등록일</th>
				<th class="text-center" style="width:140px;">수정일</th>
			</thead>
        <tbody>                        
			<?php           
			$start_num = $total_row;              
			while($row = $stmh->fetch(PDO::FETCH_ASSOC)) {
				 include '_row.php';
					
				// _row.php 파일에서 변수들이 이미 선언되었으므로, 그 값을 활용합니다.
				$seconditem = $row['seconditem'] ?? ''; // 중분류(예: 가이드레일, 케이스, 하단마감재, 등)

				$imgUrl = ''; // 기본값

				if ($seconditem === '가이드레일') {
					// 가이드레일: guiderail.json 파일에서 model_name, check_type, finishing_type 모두 일치하는 항목 검색
					$jsonFile = $_SERVER['DOCUMENT_ROOT'].'/guiderail/guiderail.json';
					if (file_exists($jsonFile)) {
						$jsonData = file_get_contents($jsonFile);
						$data = json_decode($jsonData, true);
						if (is_array($data)) {
							foreach ($data as $item) {
								if (
									$item['model_name'] === $row['model_name'] &&
									$item['check_type'] === $row['check_type'] &&
									$item['finishing_type'] === $row['finishing_type']
								) {
									$imgUrl = "<img src='{$item['image']}' alt='가이드레일 이미지' style='width:80px;height:auto;'>";
									break;
								}
							}
						}
					}
				} elseif ($seconditem === '케이스') {
					// 케이스: check_type 값에 따라 미리 지정된 이미지 사용
					switch ($row['check_type']) {
						case '양면 점검구':
							$imgUrl = "<img src='../img/box/box_both.png?v=1' alt='양면 점검구' style='width:80px;height:auto;'>";
							break;
						case '밑면 점검구':
							$imgUrl = "<img src='../img/box/box_bottom.png?v=1' alt='밑면 점검구' style='width:80px;height:auto;'>";
							break;
						case '후면 점검구':
							$imgUrl = "<img src='../img/box/box_back.png?v=1' alt='후면 점검구' style='width:80px;height:auto;'>";
							break;
						default:
							$imgUrl = "<img src='../img/box/box_both.png?v=1' alt='기본 케이스 이미지' style='width:80px;height:auto;'>";
							break;
					}
				} elseif ($seconditem === '하단마감재') {
					// 하단마감재: bottombar.json 파일에서 model_name과 finishing_type이 일치하는 항목 검색
					$jsonFile = $_SERVER['DOCUMENT_ROOT'].'/bottombar/bottombar.json';
					if (file_exists($jsonFile)) {
						$jsonData = file_get_contents($jsonFile);
						$data = json_decode($jsonData, true);
						if (is_array($data)) {
							foreach ($data as $item) {
								if (
									$item['model_name'] === $row['model_name'] &&
									$item['finishing_type'] === $row['finishing_type']
								) {
									$imgUrl = "<img src='{$item['image']}' alt='하단마감재 이미지' style='width:80px;height:auto;'>";
									break;
								}
							}
						}
					}
				} elseif ($seconditem === 'L-BAR') {
					// L-BAR인 경우 기본 이미지 지정
					$imgUrl = "<img src='../img/Lbar/Lbar2.jpg' alt='L-BAR 이미지' style='width:80px;height:auto;'>";
				} elseif ($seconditem === '보강평철') {
					// 보강평철인 경우 기본 이미지 지정
					$imgUrl = "<img src='../bending/img/2024_09_28_11_48_24_평철.jpg' alt='보강평철 이미지' style='width:80px;height:auto;'>";
				} elseif ($seconditem === '마구리') {
					// 보강평철인 경우 기본 이미지 지정
					$imgUrl = "<img src='../img/box/box_both_Maguri.jpg' alt='마구리 이미지' style='width:40px;height:auto;'>";
				} elseif ($seconditem === '가이드레일용 연기차단재' || $seconditem === '케이스용 연기차단재' ) {
					// 보강평철인 경우 기본 이미지 지정
					$imgUrl = "<img src='../img/part/smokeban.jpg' alt='연기차단재 이미지' style='width:80px;height:auto;'>";
				} else {
					// 그 외 또는 이미지 없음
					$imgUrl = "<img src='../img/no_image.png' alt='No Image' style='width:80px;height:auto;'>";
				}
				?>
											   
			<tr  data-num="<?= htmlspecialchars($num, ENT_QUOTES, 'UTF-8') ?>"   onclick="redirectToView('<?=$row['num']?>')"   >				
				<td class="text-center"><?= $start_num ?></td>
				<td class="text-center text-primary fw-bold"><?= htmlspecialchars($row['major_category'], ENT_QUOTES, 'UTF-8') ?></td>
				<td class="text-center fw-bold"><?= htmlspecialchars($row['seconditem'], ENT_QUOTES, 'UTF-8') ?></td>
				<td class="text-center"><?= htmlspecialchars($row['model_name'], ENT_QUOTES, 'UTF-8') ?></td>
				<td class="text-center text-danger"><?= htmlspecialchars($row['check_type'], ENT_QUOTES, 'UTF-8') ?></td>
				<td class="text-center"><?= htmlspecialchars($row['finishing_type'], ENT_QUOTES, 'UTF-8') ?></td>
				<td class="text-center"><?= htmlspecialchars($row['spec'], ENT_QUOTES, 'UTF-8') ?></td>
				<td class="text-center"><?= htmlspecialchars($box_width, ENT_QUOTES, 'UTF-8') ?></td>
				<td class="text-center"><?= htmlspecialchars($box_height, ENT_QUOTES, 'UTF-8') ?></td>
				<td class="text-center"><?= htmlspecialchars($front_bottom_width, ENT_QUOTES, 'UTF-8') ?></td>
				<td class="text-center"><?= htmlspecialchars($rail_width, ENT_QUOTES, 'UTF-8') ?></td>
				<td class="text-center"> <?= $imgUrl ?> </td>
				<td class="text-end"><?= htmlspecialchars($row['unitprice'], ENT_QUOTES, 'UTF-8') ?></td>
				<td class="text-center"><?= htmlspecialchars($row['description'], ENT_QUOTES, 'UTF-8') ?></td>				
				<td class="text-center"><?= htmlspecialchars(substr($row['priceDate'], 2), ENT_QUOTES, 'UTF-8') ?></td>
				<td class="text-center"><?= htmlspecialchars(substr($row['created_at'], 5), ENT_QUOTES, 'UTF-8') ?></td>
				<td class="text-center"><?= htmlspecialchars(substr($row['updated_at'], 5), ENT_QUOTES, 'UTF-8') ?></td>

			</tr>
			<?php
				$start_num--;
			}
			} catch (PDOException $Exception) {
				print "오류: ".$Exception->getMessage();
			}  
			?>       
        </tbody>
        </table>
        </div>
    </div>
</div>      
</form>

<!-- 페이지 로딩 및 DataTable 초기화 -->
<script>
var table;
$(document).ready(function(){    
    var loader = document.getElementById('loadingOverlay');
    if(loader)
        loader.style.display = 'none';
});

$(document).ready(function() {
    // DataTable에 details-control 열이 첫 번째 열로 추가됨
    table = $('#myTable').DataTable({
        "paging": true,
        "ordering": true,
        "searching": true,
        "pageLength": 100,
        "lengthMenu": [50, 100, 200, 500, 1000],
        "language": {
            "lengthMenu": "Show _MENU_ entries",
            "search": "Live Search:"
        },
		"columnDefs": [{
			"orderable": false,
			"className": 'details-control',
			"targets": 0,
			"defaultContent": '<i class="bi bi-plus"></i>'
		}],
		
        "order": [[0, 'desc']]
    });
    
    var savedPageNumber = getCookie('modelpageNumber');
    if (savedPageNumber) {
        table.page(parseInt(savedPageNumber) - 1).draw(false);
    }

    table.on('page.dt', function() {
        var modelpageNumber = table.page.info().page + 1;
        setCookie('modelpageNumber', modelpageNumber, 10);
    });

    $('#myTable_length select').on('change', function() {
        var selectedValue = $(this).val();
        table.page.len(selectedValue).draw();
        savedPageNumber = getCookie('modelpageNumber');
        if (savedPageNumber) {
            table.page(parseInt(savedPageNumber) - 1).draw(false);
        }
    });
});

// 펼침/접힘 클릭 이벤트 수정
$('#myTable tbody').on('click', 'td.details-control', function () {
    var tr = $(this).closest('tr');
    var row = table.row(tr);
    if (row.child.isShown()) {
        row.child.hide();
        tr.removeClass('shown details-disabled');
        $(this).html('<i class="bi bi-plus"></i>');
    } else {
        $(this).html('<i class="bi bi-dash-circle-fill"></i>');
        var num = tr.data('num');
        $.ajax({
            url: "model_tree.php",
            data: { num: num },
            type: "GET",
            success: function(html) {
                row.child(html).show();
                tr.addClass('shown details-disabled'); // 여기서 hover 효과를 없애기 위해 클래스 추가
                $(tr).find('td.details-control').html('<i class="bi bi-dash-circle-fill"></i>');
            },
            error: function(jqXHR, textStatus, errorThrown) {
                row.child("Error loading details").show();
                tr.addClass('shown details-disabled');
                $(tr).find('td.details-control').html('<i class="bi bi-dash-circle-fill"></i>');
            }
        });
    }
});

function restorePageNumber() {
    var savedPageNumber = getCookie('modelpageNumber');
    if (savedPageNumber) {
        table.page(parseInt(savedPageNumber) - 1).draw('page');
    }
    location.reload(true);
}

function enter() {
    $("#board_form").submit();                   
}

$(document).keydown(function(e){
    var code = e.keyCode || e.which;
    if (code == 27) { 
        self.close();
    }
});

function redirectToView(id) {
    var title = '<?=$title_message;?>';
    var tablename = $("#tablename").val();
    // 수정 화면 열기 (모달 팝업)
    popupCenter('write_form.php?mode=modify&num=' + id + '&tablename=' + tablename,  title, 1100, 900);    
}

// 절곡기초 바라시 이동
function gotoBendingListBtn() {
    var title = '<?=$title_message;?>';    
	var url = '../bending/list.php?header=header';	
    location.href = url;
}
// 모델관리
function loadmodelBtn() {
    var title = '<?=$title_message;?>';    
    popupCenter('modelslist.php',  title, 1100, 900);    
}
// 모델트리 호출
function loadTreeBtn() {
    var title = '<?=$title_message;?>';    
    popupCenter('../modelsTree/modelsTree.php',  title, 1100, 900);    
}
// 품목관리
function loadQCBtn() {
    var title = '<?=$title_message;?>';    
    popupCenter('itemlist.php',  title, 1100, 900);    
}
// 이전화면 호출
function previousBtn() {     
	var url = '../bendingfee_backup/list.php?header=header';	
    location.href = url;	
}
// 절곡바라시 띄우기
function bendingBtn() {    
	var url = '../bending/list.php';
    popupCenter(url, '', 1500, 900);    	
}
// 절곡품 가이드레일 창 띄우기
function guiderailBtn() {    
	var url = '../guiderail/list.php';	
    popupCenter(url, '', 1500, 900);    	
}

// 절곡품 케이스 창 띄우기
function caseBtn() {    
	var url = '../shutterbox/list.php';	
    popupCenter(url, '', 1500, 900);    	
}
// 절곡품 하단마감재 창 띄우기
function bottombarBtn() {    
	var url = '../bottombar/list.php';	
    popupCenter(url, '', 1500, 900);    	
}

$("#searchBtn").on("click", function() {
    $("#board_form").submit();
}); 

$("#newBtn").on("click", function() {      
    var title = '<?=$title_message;?>';
    var tablename = $("#tablename").val();
    popupCenter('write_form.php?tablename=' + tablename,  title + ' 신규등록', 1100, 900);    
});

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

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

//Lot No 부여법 (펼치고 접기)
$(document).ready(function() {         
    $("#bendTableToggle").on("click", function() {
        var showLotList_models = getCookie("showLotList_models");
        var bendTable = $("#item_Table");
        if (showLotList_models === "show") {
            bendTable.css("display", "none");
            setCookie("showLotList_models", "hide", 10);
        } else {
            bendTable.css("display", "block");
            setCookie("showLotList_models", "show", 10);
        }
    });

    // Check the cookie value on page load and set the table visibility
    var showLotList_models = getCookie("showLotList_models");
    var bendTable = $("#item_Table");
    if (showLotList_models === "show") {
        bendTable.css("display", "block");
    } else {
        bendTable.css("display", "none");
    }
});	

function addRow_bend(tableBody, rowData) {
    var newRow = $('<tr>');

    // col1부터 col18까지 채우기
    for (let i = 1; i <= 18; i++) {
        let colValue = rowData['col' + i] || '';  // 값이 없으면 빈 문자열 사용

        // 특정 열만 readonly 속성 부여
        if ([1, 2, 5, 6, 17].includes(i)) {
            newRow.append('<td><input type="text" name="col' + i + '[]" value="' + colValue + '" class="form-control text-center number-format col' + i + '" autocomplete="off" readonly></td>');
        } 
    }

    // 새 행을 테이블에 추가
    tableBody.append(newRow);
}

function initializePage() {
   // 절곡 단가
    var item_bend = <?php echo isset($item_bend) ? json_encode($item_bend) : '[]'; ?>;
    if (typeof item_bend === 'string') {
        try {
            item_bend = JSON.parse(item_bend);
        } catch (e) {
            console.error('JSON 파싱 오류:', e);
            item_bend = [];
        }
    }	
    
    // item_bend가 올바른 배열인지 확인
    if (!Array.isArray(item_bend)) {
        item_bend = [];
    }
	console.log(item_bend);

    var tableBody = $('#item_bendTable tbody');  // 테이블의 tbody 선택

    // JSON 데이터를 순회하며 각 행을 추가하고, 값을 채워 넣음
    item_bend.forEach(function(rowData) {
        addRow_bend(tableBody, rowData);
    });	
	
}
$(document).ready(function() {
    initializePage();    

    // Toggle button for bendTable
    $("#bendTableUnitToggle").on("click", function() {
        var showBendTable = getCookie("showBendTable");
        var bendTable = $("#item_bendTable");
        if (showBendTable === "show") {
            bendTable.css("display", "none");
            setCookie("showBendTable", "hide", 10);
        } else {
            bendTable.css("display", "block");
            setCookie("showBendTable", "show", 10);
        }
    });

    // Check the cookie value on page load and set the table visibility
    var showBendTable = getCookie("showBendTable");
    var bendTable = $("#item_bendTable");
    if (showBendTable === "show") {
        bendTable.css("display", "block");
    } else {
        bendTable.css("display", "none");
    }
});	

function generateExcel() {
    var table = document.getElementById('myTable'); // Make sure your table has id="myTable"
    // Get both thead and tbody rows. thead is rows[0], tbody starts from rows[1]
    var rows = table.getElementsByTagName('tr');
    var data = [];

    // Ensure there's at least one data row besides the header
    if (rows.length < 2) {
        console.log('No data rows found in the table.');
        alert('테이블에 데이터가 없습니다.');
        return;
    }

    // Define keys based on the thead structure (use meaningful English keys)
    // These keys MUST match the keys expected by saveExcel.php
    const keys = [
        'no',               // 번호
        'categoryMain',     // 대분류
        'categorySub',      // 중분류
        'modelName',        // 모델명
        'shape',            // 형상
        'finishType',       // 마감타입
        'specification',    // 규격
        'boxWidth',         // 박스폭
        'boxHeight',        // 박스높이
        'frontBottom',      // 전면밑
        'railWidth',        // 레일폭
        'form',             // 형태 (might contain image/icon)
        'unitPriceM',       // 단가/M
        'memo',             // 메모
        'priceBaseDate',    // 단가기준일
        'registrationDate', // 등록일
        'modificationDate'  // 수정일
    ];

    // Iterate through data rows (starting from index 1 to skip thead)
    for (var i = 1; i < rows.length; i++) {
        var cells = rows[i].getElementsByTagName('td');
        // Check if the row has the expected number of cells
        if (cells.length !== keys.length) {
             console.warn(`Row ${i} has ${cells.length} cells, expected ${keys.length}. Skipping row.`);
             continue; // Skip rows that don't match the header structure
        }
        var rowData = {};
        for (var j = 0; j < keys.length; j++) {
            // Use the defined key and get the corresponding cell's text
            rowData[keys[j]] = cells[j]?.innerText.trim() || '';
        }
        data.push(rowData);
    }

    if (data.length === 0) {
         console.log('No valid data extracted from the table.');
         alert('테이블에서 유효한 데이터를 추출하지 못했습니다.');
         return;
    }

    // Send data to saveExcel.php
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "saveExcel.php", true); // Ensure this path is correct
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                try {
                    var response = JSON.parse(xhr.responseText);
                    if (response.success) {
                        console.log('Excel file generated successfully.');
                        // Redirect to download script
                        // Ensure downloadExcel.php correctly handles the filename parameter
                        window.location.href = 'downloadExcel.php?filename=' + encodeURIComponent(response.filename.split('/').pop());
                    } else {
                        console.error('PHP Error: Failed to generate Excel file: ' + response.message);
                        alert('엑셀 파일 생성 실패: ' + response.message);
                    }
                } catch (e) {
                    console.error('JS Error: Error parsing response: ' + e.message + '\nResponse text: ' + xhr.responseText);
                    alert('서버 응답 처리 중 오류가 발생했습니다.');
                }
            } else {
                console.error('Server Error: Failed to generate Excel file: Server returned status ' + xhr.status);
                 alert('엑셀 파일 생성 요청 실패: 서버 상태 ' + xhr.status);
            }
        }
    };
    xhr.onerror = function () {
        console.error('Network Error: Could not connect to saveExcel.php');
        alert('엑셀 파일 생성 서버에 연결할 수 없습니다.');
    };
    xhr.send(JSON.stringify(data));
}

</script>
<?php include $_SERVER['DOCUMENT_ROOT'] . '/common/enlargeImage.php'; //  이미지 확대4배 JS코드  ?>
</body>
</html>
