<?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;
}   
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include $_SERVER['DOCUMENT_ROOT'] . '/load_header.php'; 
$title_message = '견적 단가';   

$header = isset($_REQUEST["header"]) ? $_REQUEST["header"] : "";
?>  

<style>
textarea {
    overflow: hidden;
    resize: none; /* 사용자 크기 조절을 방지 */
}  
input[type="checkbox"],
input[type="radio"] {
    transform: scale(1.2); /* 크기 확대 */
    margin: 3px; /* 여백 추가 */
}

.readonly-checkbox,
.readonly-radio {
    pointer-events: none; /* 사용자 상호작용 비활성화 */
    opacity: 1; /* 불투명도 설정 */
    color: red;
}

label {
    font-size: 1.2em; /* 글꼴 크기 확대 */
    display: inline-block;
    margin: 3px 0;
}
</style>

<title>  <?=$title_message?>  </title> 

</head>
<body> 
<?php 
if($header !=='no')
	require_once($_SERVER['DOCUMENT_ROOT'] . '/myheader.php'); ?>   
<?php
$mode ='view';
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();	

$tablename = 'price_raw_materials'; 

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 정보를 불러온다.     
	   include $_SERVER['DOCUMENT_ROOT'] . '/price_raw_materials/_row.php';	
	
} catch (PDOException $Exception) {
	print "오류: ".$Exception->getMessage();
}

$tablename = 'price_motor'; 

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_motor = $row['itemList'];
} catch (PDOException $Exception) {
	print "오류: ".$Exception->getMessage();
}

$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'];
} catch (PDOException $Exception) {
	print "오류: ".$Exception->getMessage();
}

$tablename = 'price_shaft'; 

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_shaft = $row['itemList'];
} catch (PDOException $Exception) {
	print "오류: ".$Exception->getMessage();
}

$tablename = 'price_pole'; 

try {	
	$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_pole = $row['itemList'];
} catch (PDOException $Exception) {
	print "오류: ".$Exception->getMessage();
}

$tablename = 'price_angle'; 

try {	
	$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_angle = $row['itemList'];
} catch (PDOException $Exception) {
	print "오류: ".$Exception->getMessage();
}

$tablename = 'price_pipe'; 

try {	
	$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_pipe = $row['itemList'];
} catch (PDOException $Exception) {
	print "오류: ".$Exception->getMessage();
}

$tablename = 'price_screenplate'; 

try {	
	$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_screenplate = $row['itemList'];
} catch (PDOException $Exception) {
	print "오류: ".$Exception->getMessage();
}

$tablename = 'price_smokeban'; 

try {	
	$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_smokeban = $row['itemList'];
} catch (PDOException $Exception) {
	print "오류: ".$Exception->getMessage();
}
?>

<form id="board_form"  name="board_form" method="post" enctype="multipart/form-data">
	<input type="hidden" id="mode" name="mode" value="<?= isset($mode) ? $mode : '' ?>">	
<div class='container-fluid'>	
    <div class="d-flex justify-content-end mt-2 mb-1">
	   <?php if($header=='no') { ?>
				<button type="button" class="btn btn-outline-dark  btn-sm " onclick="self.close();" > <i class="bi bi-box-arrow-left"></i> 창닫기 </button>	&nbsp; 				
	   <?  }  ?>	
	</div>
</div>

<div class='container-fluid'>
    <div class="table-responsive ">        
    <div class="d-flex justify-content-center w-80">        
		<div class="card"> 
			<div class="card-body">
				<h5 class="card-title text-center">주자재</h5>
				<table id="price_raw_materialsTable" class="table table-bordered table-hover table-sm">
				   <thead class="table-primary text-center">
						<tr>                                
							<th class="align-middle">품목</th>
							<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">면적<br>(1슬랫당)</th>
							<th class="align-middle">1㎡당<br>무게(kg)</th>
							<th class="align-middle">입고가<br>(kg단가)</th>
							<th class="align-middle">㎡ / 단가<br>(15%로스)</th>
							<th class="align-middle">가공비</th>
							<th class="align-middle">미미</th>
							<th class="align-middle">합계</th>
							<th class="align-middle bg-danger text-white"> 합계<br>(인건비포함)</th>
							<th class="align-middle "> 비인정 품목코드</th>
						</tr>						
					</thead>
					<tbody>     
						<!-- Additional Rows Go Here -->
					</tbody>
				</table>
			</div>
		</div>        
    </div>
    </div>

    <div class="table-responsive ">        
    <div class="d-flex justify-content-center">    
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title text-center">모터</h5>
                    <table id="item_motorTable" class="table table-bordered table-hover table-sm">
					 <thead class="table-primary text-center">
							<tr>								
								<th rowspan="2" class="align-middle">NO.</th>
								<th rowspan="2" class="align-middle">구분</th>								
								<th colspan="5" class="align-middle">단가표</th>
								<th colspan="1" class="align-middle">합계</th>
								<th colspan="1" class="align-middle">1달러</th>
								<th colspan="1" class="align-middle">위엔화</th>
								<th colspan="1" class="align-middle">달러</th>
								<th colspan="1" class="align-middle">달러</th>
								<th rowspan="1" class="align-middle">통관+운송</th>								
								<th rowspan="1" class="align-middle  bg-danger text-white">판매가</th>
								<th rowspan="2" class="align-middle">판매마진</th>
								<th rowspan="1" class="align-middle">매출대비</th>
							</tr>
							<tr>
								<!-- Second row headers for the "단가 표" section -->
								<th class="align-middle">품목</th>
								<th class="align-middle">모터</th>
								<th class="align-middle">브라켓</th>
								<th class="align-middle">콘트롤박스</th>
								<th class="align-middle">리미트</th>								
								<th class="align-middle">위엔화</th>
								<th class="align-middle">위엔화</th>
								<th class="align-middle">달러</th>
								<th class="align-middle">한화</th>
								<th class="align-middle">한화 합계</th>
								<th class="align-middle">20% UP</th>
								<th class="align-middle bg-danger text-white">(모터+브라켓)</th>								
								<th class="align-middle">마진율(%)</th>
							</tr>
						</thead>
                        <tbody>     
                            <!-- Additional Rows Go Here -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>	
       </div>

    <div class="row justify-content-center">
           <div class="card">
                <div class="card-body">
                    <h5 class="card-title text-center">절곡판</h5>
                    <table id="item_bendTable" class="table table-bordered table-hover table-sm">
						<thead class="table-primary text-center">
							<tr>								
								<th colspan="2" class="align-middle">품목</th>
								<th colspan="2" class="align-middle">규격</th>
								<th rowspan="2" class="align-middle">두께(T)</th>
								<th rowspan="2" class="align-middle">비중</th>
								<th rowspan="1" class="align-middle">면적(㎡)</th>
								<th rowspan="1" class="align-middle">무게(kg)</th>
								<th rowspan="2" class="align-middle">입고가<br>(kg단가)</th>
								<th rowspan="1" class="align-middle">LOSS 할증가</th>
								<th rowspan="1" class="align-middle">판 단가(자재비)</th>
								<th rowspan="2" class="align-middle">판 단가</th>
								<th rowspan="2" class="align-middle">면적당<br> 가공비</th>
								<th rowspan="1" class="align-middle">가공비</th>
								<th rowspan="2" class="align-middle  bg-danger text-white">합계<br>(가공+판)</th>
								<th rowspan="2" class="align-middle">㎡ / 단가</th>
								<th rowspan="2" class="align-middle">㎡ / 단가</th>
								<th rowspan="2" class="align-middle">kg / 단가</th>
							</tr>
							<tr>
								<th class="align-middle">재질1</th>
								<th class="align-middle">재질2</th>
								<th class="align-middle">폭</th>
								<th class="align-middle">길이</th>
								<th class="align-middle">폭*길이</th>
								<th class="align-middle">두께*비중*면적</th>
								<th class="align-middle">입고가*1.2</th>
								<th class="align-middle">무게*loss할증가</th>
								<th class="align-middle">면적*가공비</th>
							</tr>
						</thead>

                        <tbody>     
                            <!-- Additional Rows Go Here -->
                        </tbody>
                    </table>
                </div>
            </div>
</div> <!--container-->

    <div class="row justify-content-center">        
		<div class="col-lg-12 col-sm-12">
            <div class="card">
                <div class="card-body">                 
                    <h5 class="card-title text-center">부자재(샤프트)</h5>
                    <table id="itemshaftTable" class="table table-bordered table-hover table-sm">
                      <thead class="table-primary text-center">
						<tr>							
							<th class="align-middle">품목</th>
							<th class="align-middle">상차/다발</th>
							<th class="align-middle">1다발(개)</th>
							<th class="align-middle">단위</th>
							<th class="align-middle">지름(mm)</th>
							<th class="align-middle">원 면적</th>
							<th class="align-middle">2</th>
							<th class="align-middle">파이</th>
							<th class="align-middle">R(반지름)</th>
							<th class="align-middle">길이(M)</th>
							<th class="align-middle">도장/㎡</th>
							<th class="align-middle">도장</th>
							<th class="align-middle">차1대/도장</th>
							<th class="align-middle">용차</th>
							<th class="align-middle">도장+용차</th>
							<th class="align-middle">가공비</th>
							<th class="align-middle">입고가<br>(6M)</th>
							<th class="align-middle">원가합계</th>
							<th class="align-middle bg-danger text-white">판매가 20% UP</th>
							<th class="align-middle">m / 단가</th>
						</tr>
						</thead>
                        <tbody>     
						
                        </tbody>
                    </table>
                </div>
                </div>
            </div>
        </div>
  
    <div class="row justify-content-center w-50">
        <div class="col-lg-12 col-sm-12">
				<div class="card">
					<div class="card-body">
						<h5 class="card-title text-center">부자재(환봉)</h5>
						<table id="itempoleTable" class="table table-bordered table-hover table-sm">
						  <thead class="table-primary text-center">
							<tr>									
								<th class="align-middle">품목</th>							
								<th class="align-middle">길이(M)</th>							
								<th class="align-middle">입고가<br>(5M)</th>							
								<th class="align-middle bg-danger text-white">판매가 20%</th>
							</tr>
						</thead>

							<tbody>     
								<!-- Additional Rows Go Here -->
							</tbody>
						</table>
					</div>
				</div>
		</div>  
	</div>  
  
    <div class="row justify-content-center">
        <div class="col-lg-12 col-sm-12">
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title text-center">부자재(앵글)</h5>
                    <table id="itemangleTable" class="table table-bordered table-hover table-sm">
                      <thead class="table-primary text-center">
						<tr>							
							<th class="align-middle">품목</th>
							<th class="align-middle">상차/다발</th>
							<th class="align-middle">1다발(개)</th>
							<th class="align-middle">단위</th>
							<th class="align-middle">지름(mm)</th>
							<th class="align-middle">원 면적</th>
							<th class="align-middle">2</th>
							<th class="align-middle">파이</th>
							<th class="align-middle">R(반지름)</th>
							<th class="align-middle">길이(M)</th>
							<th class="align-middle">도장/㎡</th>
							<th class="align-middle">도장</th>
							<th class="align-middle">차1대/도장</th>
							<th class="align-middle">용차</th>
							<th class="align-middle">도장+용차</th>
							<th class="align-middle">가공비</th>
							<th class="align-middle">입고가<br>(6M)</th>
							<th class="align-middle">원가합계</th>
							<th class="align-middle bg-danger text-white">판매가 20%</th>
							<th class="align-middle">m / 단가</th>
						</tr>
					</thead>

                        <tbody>     
                            <!-- Additional Rows Go Here -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="row">	  
			<div class="d-flex justify-content-center w-75">
					<div class="card">
						<div class="card-body">
							<h5 class="card-title text-center">부자재(각파이프) </h5>							
							<table id="itempipeTable" class="table table-bordered table-hover table-sm">
							  <thead class="table-primary text-center">
								<tr>									
									<th class="align-middle">품목</th>							
									<th class="align-middle">길이(mm)</th>							
									<th class="align-middle">규격(가로x세로)</th>							
									<th class="align-middle">두께(T)</th>							
									<th class="align-middle">길이(M)</th>	
									<th class="align-middle">입고가</th>											
									<th class="align-middle">원가합계</th>
									<th class="align-middle bg-danger text-white">판매가 15%</th>																		
								</tr>
							</thead>

								<tbody>     
									<!-- Additional Rows Go Here -->
								</tbody>
							</table>
						</div>
					</div>
			</div>  
	</div>

	<div class="row d-flex justify-content-center w-75">
			<div class="card">
				<div class="card-body">
					<h5 class="card-title text-center">부자재(스크린평철)</h5>
					<table id="itemscreenplateTable" class="table table-bordered table-hover table-sm">
					  <thead class="table-primary text-center">
						<tr>							
							<th class="align-middle">품목</th>							
							<th class="align-middle">두께(T)</th>							
							<th class="align-middle">폭</th>							
							<th class="align-middle">길이(M)</th>	
							<th class="align-middle">가공비</th>							
							<th class="align-middle">입고가</th>											
							<th class="align-middle">원가합계</th>
							<th class="align-middle bg-danger text-white">판매가 20% UP</th>																		
						</tr>
					</thead>
						<tbody>     
							<!-- Additional Rows Go Here -->
						</tbody>
					</table>
				</div>
			</div>
	</div> 

    <div class="row">	  
			<div class="d-flex justify-content-center w-75">
					<div class="card">
						<div class="card-body">
							<h5 class="card-title text-center">부자재(연기차단재)</h5>							
							<table id="itemsmokebanTable" class="table table-bordered table-hover table-sm">
							  <thead class="table-primary text-center">
								<tr>									
									<th class="align-middle">품목</th>							
									<th class="align-middle">용도</th>							
									<th class="align-middle">단위(롤)</th>							
									<th class="align-middle">길이(mm)</th>							
									<th class="align-middle">폭(mm)</th>							
									<th class="align-middle">용차</th>							
									<th class="align-middle">가공비</th>	
									<th class="align-middle">입고가</th>											
									<th class="align-middle">원가합계</th>
									<th class="align-middle bg-danger text-white">판매가 15%</th>																		
									<th class="align-middle">1롤/50M</th>
								</tr>
							</thead>
								<tbody>     
									<!-- Additional Rows Go Here -->
								</tbody>
							</table>
						</div>
					</div>
			</div>  
	</div>

</div>

</form>
	
<script>


function initializePage() {
    // PHP에서 넘어온 JSON 데이터를 JavaScript 객체로 변환
    var itemList = <?php echo isset($itemList) ? json_encode($itemList) : '[]'; ?>;
	
    if (typeof itemList === 'string') {
        try {
            itemList = JSON.parse(itemList);
        } catch (e) {
            console.error('JSON 파싱 오류:', e);
            itemList = [];
        }
    }	

    if (!Array.isArray(itemList)) {
        itemList = [];
    }

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

    // JSON 데이터를 순회하며 각 행을 추가하고, 값을 채워 넣음
    itemList.forEach(function(rowData) {
        addRow(tableBody, rowData);
    });
	
    // 모터 단가
    var item_motor = <?php echo isset($item_motor) ? json_encode($item_motor) : '[]'; ?>;
    if (typeof item_motor === 'string') {
        try {
            item_motor = JSON.parse(item_motor);
        } catch (e) {
            console.error('JSON 파싱 오류:', e);
            item_motor = [];
        }
    }	
    
    // item_motor가 올바른 배열인지 확인
    if (!Array.isArray(item_motor)) {
        item_motor = [];
    }
	console.log(item_motor);

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

    // JSON 데이터를 순회하며 각 행을 추가하고, 값을 채워 넣음
    item_motor.forEach(function(rowData) {
        addRow_motor(tableBody, rowData);
    });	
	
    // 절곡 단가
    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);
    });	
	
    // 샤프트 단가
    var item_shaft = <?php echo isset($item_shaft) ? json_encode($item_shaft) : '[]'; ?>;
    if (typeof item_shaft === 'string') {
        try {
            item_shaft = JSON.parse(item_shaft);
        } catch (e) {
            console.error('JSON 파싱 오류:', e);
            item_shaft = [];
        }
    }	
    
    // item_shaft가 올바른 배열인지 확인
    if (!Array.isArray(item_shaft)) {
        item_shaft = [];
    }

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

    // JSON 데이터를 순회하며 각 행을 추가하고, 값을 채워 넣음
    item_shaft.forEach(function(rowData) {
        addRow_shaft(tableBody, rowData);
    });	
	
	
    // pole 단가
    var item_pole = <?php echo isset($item_pole) ? json_encode($item_pole) : '[]'; ?>;
    if (typeof item_pole === 'string') {
        try {
            item_pole = JSON.parse(item_pole);
        } catch (e) {
            console.error('JSON 파싱 오류:', e);
            item_pole = [];
        }
    }	    
    // item_pole가 올바른 배열인지 확인
    if (!Array.isArray(item_pole)) {
        item_pole = [];
    }
    var tableBody = $('#itempoleTable tbody');  // 테이블의 tbody 선택
    // JSON 데이터를 순회하며 각 행을 추가하고, 값을 채워 넣음
    item_pole.forEach(function(rowData) {
        addRow_pole(tableBody, rowData);
    });	
	
    // angle 단가
    var item_angle = <?php echo isset($item_angle) ? json_encode($item_angle) : '[]'; ?>;
    if (typeof item_angle === 'string') {
        try {
            item_angle = JSON.parse(item_angle);
        } catch (e) {
            console.error('JSON 파싱 오류:', e);
            item_angle = [];
        }
    }	    
    // item_angle가 올바른 배열인지 확인
    if (!Array.isArray(item_angle)) {
        item_angle = [];
    }
    var tableBody = $('#itemangleTable tbody');  // 테이블의 tbody 선택
    // JSON 데이터를 순회하며 각 행을 추가하고, 값을 채워 넣음
    item_angle.forEach(function(rowData) {
        addRow_angle(tableBody, rowData);
    });	
	
	
    // pipe 단가
    var item_pipe = <?php echo isset($item_pipe) ? json_encode($item_pipe) : '[]'; ?>;
    if (typeof item_pipe === 'string') {
        try {
            item_pipe = JSON.parse(item_pipe);
        } catch (e) {
            console.error('JSON 파싱 오류:', e);
            item_pipe = [];
        }
    }	    
    // item_pipe가 올바른 배열인지 확인
    if (!Array.isArray(item_pipe)) {
        item_pipe = [];
    }
    var tableBody = $('#itempipeTable tbody');  // 테이블의 tbody 선택
    // JSON 데이터를 순회하며 각 행을 추가하고, 값을 채워 넣음
    item_pipe.forEach(function(rowData) {
        addRow_pipe(tableBody, rowData);
    });		
	
    // screenplate 단가
    var item_screenplate = <?php echo isset($item_screenplate) ? json_encode($item_screenplate) : '[]'; ?>;
    if (typeof item_screenplate === 'string') {
        try {
            item_screenplate = JSON.parse(item_screenplate);
        } catch (e) {
            console.error('JSON 파싱 오류:', e);
            item_screenplate = [];
        }
    }	    
    // item_screenplate가 올바른 배열인지 확인
    if (!Array.isArray(item_screenplate)) {
        item_screenplate = [];
    }
    var tableBody = $('#itemscreenplateTable tbody');  // 테이블의 tbody 선택
    // JSON 데이터를 순회하며 각 행을 추가하고, 값을 채워 넣음
    item_screenplate.forEach(function(rowData) {
        addRow_screenplate(tableBody, rowData);
    });	
		
    // smokeban 단가
    var item_smokeban = <?php echo isset($item_smokeban) ? json_encode($item_smokeban) : '[]'; ?>;
    if (typeof item_smokeban === 'string') {
        try {
            item_smokeban = JSON.parse(item_smokeban);
        } catch (e) {
            console.error('JSON 파싱 오류:', e);
            item_smokeban = [];
        }
    }	    
    // item_smokeban가 올바른 배열인지 확인
    if (!Array.isArray(item_smokeban)) {
        item_smokeban = [];
    }
    var tableBody = $('#itemsmokebanTable tbody');  // 테이블의 tbody 선택
    // JSON 데이터를 순회하며 각 행을 추가하고, 값을 채워 넣음
    item_smokeban.forEach(function(rowData) {
        addRow_smokeban(tableBody, rowData);
    });	
	
	
	
	
	
}

function inputNumberFormat(obj) {
    obj.value = obj.value.replace(/[^0-9]/g, '');
}


function addRow(tableBody, rowData) {
    var newRow = $('<tr>');    
    
    // col1부터 col14까지 채우기
    for (let i = 1; i <= 14; i++) {
        let colValue = rowData['col' + i] || '';  // 값이 없으면 빈 문자열 사용

        // 특정 열만 readonly 속성 부여
        if (i == 7 || i == 9 || i == 12 ) {
            newRow.append('<td><input type="text" name="col' + i + '[]" value="' + colValue + '" class="form-control text-center number-format col' + i + '" autocomplete="off" readonly></td>');
        } else {
            newRow.append('<td><input type="text" name="col' + i + '[]" value="' + colValue + '" class="form-control text-center col' + i + '" autocomplete="off"></td>');
        }
    }

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

function addRow_motor(tableBody, rowData = {}) {
	console.log(tableBody);
    var newRow = $('<tr>');

    // 일련번호 추가 (두 번째 열)
    var rowIndex = tableBody.find('tr').length + 1;
    newRow.append('<td class="text-center align-middle row-index">' + rowIndex + '</td>');

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

        // 특정 열만 readonly 속성 부여
        if ([15].includes(i)) {
            newRow.append('<td><input type="text" name="col' + i + '[]" value="' + colValue + '" class="form-control text-center number-format calculate col' + i + '" autocomplete="off" readonly></td>');
        } else if  ([2, 10,11,12,13,14 ].includes(i)) 
		{
            newRow.append('<td><input type="text" name="col' + i + '[]" value="' + numberWithCommas(colValue) + '" style="width:130px;" class="form-control text-center  calculate  number-format  col' + i + '" autocomplete="off" ></td>');
        }else {
            newRow.append('<td><input type="text" name="col' + i + '[]" value="' + colValue + '" class="form-control text-center number-format   calculate  col' + i + '" autocomplete="off" ></td>');
        }
    }	
    // 새 행을 테이블에 추가
    tableBody.append(newRow);
}

// 숫자에 3자리마다 콤마를 추가하는 함수
function numberWithCommas(x) {
    if (!x) return '';
    x = x.toString().replace(/[^0-9.-]/g, ''); // 숫자와 '-' 기호만 남김
    return x.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

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

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

        // 특정 열만 readonly 속성 부여
        if ([7, 8, 10, 11, 12, 14, 15, 16, 17, 18].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>');
        } else {
            newRow.append('<td><input type="text" name="col' + i + '[]" value="' + colValue + '" class="form-control text-center  number-format col' + i + '" autocomplete="off"></td>');
        }
    }

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

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

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

        // 특정 열만 readonly 속성 부여
        if ([ 6, 9, 12, 13, 15, 18, 19, 20].includes(i)) {
            newRow.append('<td><input type="text" name="col' + i + '[]" value="' + colValue + '" class="text-center form-control number-format col' + i + '" autocomplete="off" readonly></td>');
        } else if ([1].includes(i)) {
            newRow.append('<td><input type="text" name="col' + i + '[]" value="' + colValue + '" class="  form-control number-format text-center col' + i + '" style="width:120px;" autocomplete="off"></td>');
        } else {
            newRow.append('<td><input type="text" name="col' + i + '[]" value="' + colValue + '" class=" form-control  number-format text-center col' + i + '" autocomplete="off"></td>');
        }
    }
    tableBody.append(newRow);
}

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

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

        // 특정 열만 readonly 속성 부여
        if ([20].includes(i)) {  // 판매가 20%는 readonly
            newRow.append('<td><input type="text" name="col' + i + '[]" value="' + colValue + '" class="form-control text-center number-format col' + i + '" autocomplete="off" readonly></td>');
        } else {
            newRow.append('<td><input type="text" name="col' + i + '[]" value="' + colValue + '" class="form-control text-center col' + i + '" autocomplete="off"></td>');
        }
    }

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

function addRow_angle(tableBody, rowData) {
    var newRow = $('<tr>');
    
    // col1부터 col20까지 채우기
    for (let i = 1; i <= 20; i++) {
        let colValue = rowData['col' + i] || '';  // 값이 없으면 빈 문자열 사용

        // 특정 열만 readonly 속성 부여
        if ([ 13, 15, 18, 19, 20].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>');
        } else if ([1].includes(i)) {
            newRow.append('<td><input type="text" name="col' + i + '[]" value="' + colValue + '" class=" form-control  number-format text-center col' + i + '" style="width:120px;" autocomplete="off"></td>');
        } else {
            newRow.append('<td><input type="text" name="col' + i + '[]" value="' + colValue + '" class=" form-control  number-format text-center col' + i + '" autocomplete="off"></td>');
        }
    }
    tableBody.append(newRow);
}

function addRow_pipe(tableBody, rowData) {
    var newRow = $('<tr>');    
    // col1부터 col8까지 채우기
    for (let i = 1; i <= 8; i++) {
        let colValue = rowData['col' + i] || '';  // 값이 없으면 빈 문자열 사용

        // 첫 번째 열 제외, 모든 열에 텍스트 박스를 추가
        newRow.append('<td><input type="text" name="col' + i + '[]" value="' + colValue + '" class="form-control text-center number-format col' + i + '" autocomplete="off"></td>');
    }
    tableBody.append(newRow);
}

function addRow_screenplate(tableBody, rowData){
    var newRow = $('<tr>');
    // col1부터 col8까지 채우기
    for (let i = 1; i <= 8; i++) {
        let colValue = rowData['col' + i] || '';  // 값이 없으면 빈 문자열 사용

        // 특정 열에 계산식 적용
        if ([7, 8].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>');
        } else {
            newRow.append('<td><input type="text" name="col' + i + '[]" value="' + colValue + '" class="form-control text-center number-format col' + i + '" autocomplete="off"></td>');
        }
   }
    tableBody.append(newRow);
}

function addRow_smokeban(tableBody, rowData) {
    var newRow = $('<tr>');
    
    // col1부터 col11까지 채우기
    for (let i = 1; i <= 11; i++) {
        let colValue = rowData['col' + i] || '';  // 값이 없으면 빈 문자열 사용

        // 특정 열에 계산식 적용 (col9, col10, col11)
        if ([9, 10, 11].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>');
        } else {
            newRow.append('<td><input type="text" name="col' + i + '[]" value="' + colValue + '" class="form-control text-center number-format col' + i + '" autocomplete="off"></td>');
        }
    }    
    tableBody.append(newRow);
}





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


$(document).ready(function() {
    initializePage();    
        
});

$(document).ready(function() {
    var mode = '<?php echo $mode; ?>'; 
	
    // view 모드일 때, 버튼 및 입력 요소 비활성화
    if (mode === 'view') {
        $('input, textarea').prop('readonly', true); // Disable all input, textarea, and select elements
        $('button.add-row, button.remove-row, button.copy-row').prop('disabled', true); // 버튼 비활성화
    }	
		
});

$(document).ready(function(){    
   // 방문기록 남김
   var title_message = '<?php echo $title_message ; ?>';
   saveMenuLog(title_message);
});

</script>


</body>
</html>