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

$mode = isset($_REQUEST['mode']) ? $_REQUEST['mode'] : '';  
$num = isset($_REQUEST["num"]) ? $_REQUEST["num"] : "";

$title_message = "철재스라트 견적서" ;

$tablename = 'output'; 

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

<style>
.hidden {
    display: none;
}

.scrollable-modal-body {
    max-height: 500px;
    overflow-y: auto;
}
</style>

</head>

<?   
include $_SERVER['DOCUMENT_ROOT'] . '/mymodal.php';

require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();	
 
$today = date("Y-m-d"); // 현재일자 변수지정

  if ($mode=="modify" || !empty($num) )
  {
    try{ 
      $sql = "select * from $DB.$tablename where num = ? ";
      $stmh = $pdo->prepare($sql); 

      $stmh->bindValue(1,$num,PDO::PARAM_STR); 
      $stmh->execute();
      $count = $stmh->rowCount();            
	  $row = $stmh->fetch(PDO::FETCH_ASSOC);  // $row 배열로 DB 정보를 불러온다.
    if($count<1){  
      print "검색결과가 없습니다.<br>";
     }else{

       include '_row.php';
	   // print_r($estimateList);
	   
      }
     }catch (PDOException $Exception) {
       print "오류: ".$Exception->getMessage();
     }
  } 
else
{
$secondord = isset($_REQUEST['secondord']) ? $_REQUEST['secondord'] : '';
$secondordman = isset($_REQUEST['secondordman']) ? $_REQUEST['secondordman'] : '';
$secondordmantel = isset($_REQUEST['secondordmantel']) ? $_REQUEST['secondordmantel'] : '';
$outworkplace = isset($_REQUEST["outworkplace"]) ? $_REQUEST["outworkplace"] : '';

}	
?>

<form id="board_form" name="board_form" method="post" enctype="multipart/form-data" onkeydown="return captureReturnKey(event)">	
    <input type="hidden" id="num" name="num" value="<?= isset($num) ? $num : '' ?>">
    <input type="hidden" id="tablename" name="tablename" value="<?= isset($tablename) ? $tablename : '' ?>">
    <input type="hidden" id="estimateList" name="estimateList">
	
    <?php include $_SERVER['DOCUMENT_ROOT'] . '/mymodal.php'; ?>

    <div class="container-fluid">	  
        <div class="card">	  
            <div class="card-body">	  
                <div class="d-flex justify-content-center align-items-center mt-3 mb-2 ">		
                    <span class="fs-5 me-5"> <?=$title_message?>  </span>                                                       
                    <span class="text-end" style="width:10%;">	                        
						<button type="button" class="btn btn-dark btn-sm me-4 saveBtn"> <ion-icon name="save-outline"></ion-icon> 저장 </button>                    
                        <button class="btn btn-secondary btn-sm" onclick="self.close();"> <i class="bi bi-x-lg"></i> 닫기 </button> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    </span>
                </div> 		
                <div class="d-flex row justify-content-center"> 	
				<table class="table table-bordered w-75">
					<thead class="table-primary">
						<tr>
							<th>상품명</th>
							<th>제품명</th>
							<th>제품명 설명</th>
							<th>비고</th>
						</tr>
					</thead>
					<tbody>
						<tr>
							<td class="text-start">국민방화 스크린 셔터</td>
							<td class="text-start">KSS01</td>
							<td class="text-start">K(경동:국민방화 브랜드명) S(실리카코팅직물 스크린) S(SUS마감)</td>
							<td class="text-start"></td>
						</tr>
						<tr>
							<td class="text-start">국민방화 스크린 셔터</td>
							<td class="text-start">KSE01</td>
							<td class="text-start">K(경동:국민방화 브랜드명) S(실리카코팅직물 스크린) E(EGI마감)</td>
							<td class="text-start"></td>
						</tr>
						<tr>
							<td class="text-start">국민방화 스크린 플러스 셔터</td>
							<td class="text-start">KWE01</td>
							<td class="text-start">K(경동:국민방화 브랜드명) W(와이어글라스코팅직물 스크린) E(EGI마감)</td>
							<td class="text-start">SUS 마감일 경우 --- 기존 EGI 마감재에 SUS 마감재로 덧방 추가</td>
						</tr>
						<tr>
							<td class="text-start">국민방화 스틸 셔터</td>
							<td class="text-start">KD-SL60</td>
							<td class="text-start">KD(경동:국민방화 브랜드명) SL(철재 : SLAT) 60(비차열 60분)</td>
							<td class="text-start">해당 성적서는 사용 안하고 있음 - KTE01 및 KQTS01로 대체 사용중</td>
						</tr>
						<tr>
							<td class="text-start">국민방화 스틸 셔터</td>
							<td class="text-start">KTE01</td>
							<td class="text-start">K(경동:국민방화 브랜드명) T(철재 : Steel) E(EGI마감)</td>
							<td class="text-start"></td>
						</tr>
						<tr>
							<td class="text-start">국민방화 투시형 스틸 셔터</td>
							<td class="text-start">KQTS01</td>
							<td class="text-start">K(경동:국민방화 브랜드명) Q(투시형 : Quartz) T(철재 : Steel) S(SUS마감)</td>
							<td class="text-start">투시창 생략하여 제작 설치 가능</td>
						</tr>
					</tbody>
				</table>
								
				</div>
				
                <div class="d-flex row justify-content-center"> 	
                    <div class="d-flex row  justify-content-center">						

                       <table class="table table-bordered ">	
                            <tbody>
                                <tr>
									<td style="width:80px;"> 상품선택 </td>
									<td style="width:250px;">
										<div class="d-flex align-items-center justify-content-start">				
											<select name="productSelect" id="productSelect" class="form-control" style="width:100%;">
												<option value="">상품을 선택하세요</option>
												<option value="KSS01">KSS01 - 국민방화 스크린 셔터</option>
												<option value="KSE01">KSE01 - 국민방화 스크린 셔터</option>
												<option value="KWE01">KWE01 - 국민방화 스크린 플러스 셔터</option>
												<option value="KD-SL60">KD-SL60 - 국민방화 스틸 셔터</option>
												<option value="KTE01">KTE01 - 국민방화 스틸 셔터</option>
												<option value="KQTS01">KQTS01 - 국민방화 투시형 스틸 셔터</option>
											</select>
										</div>
									</td>

                                   <td class="fw-bold" style="width:80px;"> 현장명 </td>
                                    <td style="width:400px;"> 
                                        <div class="d-flex align-items-center justify-content-start"> 
                                            <input type="text" id="outworkplace" name="outworkplace" value="<?=$outworkplace?>" class="form-control text-start" autocomplete="off" > 
                                        </div>
                                    </td>
                                   <td style="width:80px;"> 발주처 </td>
                                    <td style="width:250px;"> 
                                        <div class="d-flex align-items-center justify-content-start"> 
                                            <input type="text" id="secondord" name="secondord" value="<?=$secondord?>" class="form-control text-start" autocomplete="off" > 
                                        </div>
                                    </td>
                                    <td style="width:80px;"> 담당자 </td>				
                                    <td>
                                        <div class="d-flex align-items-center justify-content-start"> 					 
                                            <input type="text" id="secondordman" name="secondordman" value="<?=$secondordman?>" class="form-control text-start" autocomplete="off" >
                                        </div>	
                                    </td>
                                    <td style="width:80px;"> 전화번호 </td>				
                                    <td>
                                        <div class="d-flex align-items-center justify-content-start">					
                                            <input type="text" name="secondordmantel" id="secondordmantel" value="<?=$secondordmantel?>" class="form-control text-start" >
                                        </div>
                                    </td>
                                </tr>                              	
                            </tbody>
                        </table>
							
                    </div>						
                </div>
            </div>
		</div>
<?php
function generateTableSection($id, $title, $badgeClass = 'bg-dark') {   
    // 합계가 필요한 열 번호 (0-based index)
	$sumColumns = [13, 14, 15, 16, 17, 18, 20, 25, 26, 27, 28, 29, 34, 35, 36, 37, 38, 39, 40, 42, 43, 45, 46, 48, 49, 51, 52, 55, 56, 57, 58, 59, 60, 61, 62, 64, 65, 66, 67];

    echo "
    <div class='table-responsive mb-5'>             
        <div class='d-flex p-1 mt-1 mb-2'>
            <span class='badge $badgeClass fs-6 me-3'>$title</span>
            <button type='button' class='btn btn-primary btn-sm viewNoBtn add-row me-5' data-table='{$id}Table' style='margin-right: 5px;'>+</button>
            <button type='button' id='viewEstimateUnit' class='btn btn-primary btn-sm ' data-table='{$id}Table' > 단가표 </button>
        </div>
        <div class='d-flex row'> &nbsp;&nbsp;
            <table class='table table-bordered' id='{$id}Table'> 
                <thead id='thead_{$id}'>
                    <tr>
                        <th rowspan='6'>행추가<br>삭제</th>
                        <th rowspan='6'>일련<br>번호</th>
                        <th rowspan='6'>층수</th>
                        <th rowspan='6'>부호</th>
                        <th rowspan='6'>제품명</th>
                        <th rowspan='6'>종류</th>
                        <th rowspan='4' colspan='2'>가이드레일</th>
                        <th rowspan='4' colspan='2'>①오픈사이즈</th>
                        <th rowspan='4' colspan='2'>②제작사이즈</th>
                        <th rowspan='6'>③면적</th>
                        <th rowspan='6'>④중량</th>
                        <th rowspan='6'>셔터<br>수량</th>
                        <th rowspan='2' colspan='3' >연동제어기</th>
                        <th rowspan='2' colspan='5'>⑤모터</th>
                        <th rowspan='1' colspan='30'>절곡</th>
                        <th rowspan='1' colspan='15'>부자재</th>                                                                                                
                    </tr>
                    <tr>
						<th rowspan='2' colspan='8'>⑥가이드레일(한쌍)</th>
						<th rowspan='2' colspan='12'>⑦케이스(셔터박스)</th>
						<th rowspan='2' colspan='10'>⑧하단마감재</th>
						<th rowspan='2' colspan='8'>⑨감기샤프트</th>
						<th rowspan='2' colspan='4'>⑩각파이프</th>
                        <th rowspan='4'>⑪환봉</th>
                        <th rowspan='4'>⑫앵글</th>						
					</tr>
                    <tr>
						<th rowspan='4'> 매립 </th>					
						<th rowspan='4'> 노출 </th>						
						<th rowspan='4'> 매립형 <br> 뒷박스 </th>						
						<th rowspan='4'> 전원 </th>						
						<th rowspan='4'> 용량 </th>						
						<th colspan='3'> 브라케트 </th>					
					</tr>
					<tr>
                        <th rowspan='3'>가로*세로</th>
                        <th rowspan='3'>사이즈</th>
                        <th rowspan='3'>받침용<br>앵글</th>
                        <th rowspan='2' colspan='6'>마감/보강재</th>
                        <th rowspan='3'>하부base</th>
                        <th > 레일용<br> 연기차단재</th>
                        <th colspan='11'> 케이스 </th>                        
                        <th> 케이스용<br>연기차단재</th>
                        <th colspan='3'>하장바</th>
                        <th colspan='3'>엘바</th>
                        <th colspan='3'>보강평철</th>
                        <th colspan='1'>무게평철</th>
                        <th rowspan='3'>사이즈<br>(인치)</th>
                        <th colspan='7'>원형파이프</th>
                        <th rowspan='2' colspan='4'> 50*30*1.4T </th>
                    </tr>
					<tr>
						<th rowspan='2'> 설치유형 </th>					
						<th rowspan='2'> 마감유형 </th>					
						<th rowspan='2'> 가로 </th>					
						<th rowspan='2'> 높이 </th>					
						<th rowspan='2'> 가로 </th>					
						<th rowspan='2'> 높이 </th>										
                        <th rowspan='2'>W50</th>
                        <th colspan='8'>셔터박스</th>
                        <th rowspan='1'>상부덮개</th>
                        <th colspan='2'>마구리</th>                        
                        <th colspan='1'>W80</th>                        
                        <th colspan='3'>60*40</th>                        
                        <th colspan='3'>60*17</th>                        
                        <th colspan='3'>50</th>                        
                        <th colspan='1'>12T</th>                        
                        <th colspan='1'>2</th>                        
                        <th colspan='3'>4</th>                        
                        <th colspan='3'>5</th>    
                    </tr>
                    <tr>
                        <th>사이즈(G)</th>
                        <th>2438</th>
                        <th>3000</th>
                        <th>3500</th>
                        <th>4000</th>
                        <th>4300</th>                        
                        <th>규격</th>
                        <th>사이즈(S)</th>
                        <th>1219</th>
                        <th>2438</th>
                        <th>3000</th>
                        <th>3500</th>
                        <th>4000</th>
                        <th>4150</th>
                        <th>1219*389</th>
                        <th>사이즈</th>
                        <th>수량</th>
                        <th>3000</th>
						<th>사이즈</th>
						<th>3000</th>
                        <th>4000</th>
						<th>사이즈</th>
						<th>3000</th>
                        <th>4000</th>
						<th>사이즈</th>
						<th>3000</th>
                        <th>4000</th>
                        <th>2000</th>
                        <th>300</th>
                        <th>3000</th>
                        <th>4500</th>
                        <th>6000</th>
                        <th>6000</th>
                        <th>7000</th>
                        <th>8200</th>
                        <th>보강</th>
                        <th>사이즈</th>
                        <th>3000</th>
                        <th>6000</th>
                        <th>3000</th>
                        <th>2500</th>
                    </tr>
                </thead>
                <tbody id='{$id}Group'>
                    <!-- 자동생성 -->
                </tbody>
				 <tfoot class='table-secondary'>
									<tr>
										<th class='text-end' colspan='12'> 합계 &nbsp; </th>";
										
										for ($i = 13; $i <= 67; $i++) {
											if (in_array($i, $sumColumns)) {
												echo "<th class='text-end' id='totalCol{$i}'></th>";
											} else {
												echo "<th class='text-end'></th>";
											}
										}

					echo "          </tr>
								</tfoot>				
            </table>
			 <div class='d-flex row mt-3 mb-5'> &nbsp;&nbsp;
        </div>            
        </div>            
    </div>
    ";     
}

// shutter
generateTableSection('estimate', 'shutter');

?>
</div> <!-- end of container -->
	
</form>
</body>
</html>

<script>
var ajaxRequest = null;
var ajaxRequest_write = null;
var hallDoorOptions = [] ;
var carDoorOptions =  [];
var carWallOptions = [];
var etcOptions = [];

$(document).ready(function() {
    initializePage();
    bindEventHandlers();
		
    $(".saveBtn").click(function() {
        saveData();
    });

    $("#viewEstimateUnit").click(function() {
		var url = '/output/estimateUnit.php';
		 customPopup(url, '견적 단가 관리', 1850, 900); 	
    });

    $(".deleteBtn").click(function() {
        deleteData();
    });

});

function updateTotals() {
    // 합계를 계산할 열의 인덱스 (1-based, 실제로는 0-based로 사용)
    var sumColumns = [12, 13, 14, 15, 16, 17, 18, 19, 24, 25, 26, 27, 28, 29, 31, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66];
    
    // 각 열에 대한 합계 계산
    sumColumns.forEach(function(colIndex) {
        var total = 0;

        // 해당 열의 모든 셀 값 합산 (input 값을 읽어옴)
        $('#estimateTable tbody tr').each(function() {
            var inputElement = $(this).find('td').eq(colIndex - 1).find('input');
            if (inputElement.length > 0) {
                var inputValue = inputElement.val() || "0"; // 값이 없거나 undefined인 경우 "0"으로 대체
                // console.log('Input Value at colIndex ' + colIndex + ':', inputValue);

                var cellValue = parseFloat(inputValue.replace(/,/g, '')) || 0;
                total += cellValue;
            }
        });

        // 합계를 해당 열의 footer에 업데이트
        $('#totalCol' + colIndex).text(total.toLocaleString());
        // console.log('Total for colIndex ' + colIndex + ':', total.toLocaleString());
    });
}



// 초기 페이지 설정
function initializePage() {
    var loader = document.getElementById('loadingOverlay');
    loader.style.display = 'none';

    var estimate = <?php echo json_encode($estimateList ?? []); ?>;
	
    loadTableData('#estimateTable', estimate, 'estimate');
     
}

// 이벤트 핸들러 바인딩
function bindEventHandlers() {
    $(document).on('click', '.remove-row', function() {
        $(this).closest('tr').remove();
		updateTotals();
    });

    $(document).on('click', '.close-modal', function() {
        $(this).closest('.modal').modal('hide');
    });

    $(document).on('click', '.add-row', function() {
        var tableId = $(this).data('table');
        var tableBody = $('#' + tableId).find('tbody');
        addRow(tableBody, {}, tableId);
		updateTotals();
    });

}

function loadTableData(tableId, dataList, typebutton) {
    var tableBody = $(tableId).find('tbody');    
    var theadId;

    switch (tableId) {
        case '#estimateTable':
            theadId = '#thead_estimate';
            break;        
        default:
            theadId = null;
    }

    if (typeof dataList === 'string') {
        try {
            dataList = JSON.parse(dataList);
        } catch (e) {
            console.error('Failed to parse dataList:', e);
            dataList = [];
        }
    }

	$(theadId).show();
    // if (theadId) {
        // if (dataList.length === 0) {
            // $(theadId).hide();
        // } else {
            // $(theadId).show();
        // }
    // }

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

    if (dataList.length === 0) {
        console.log('no record');
    } else {
        dataList.forEach(function(item) {
            addRow(tableBody, item, typebutton);
        });
    }
}

function showModal(options, modalId, modalBodyId, input) {
    targetInput = input;
    $(modalBodyId).empty();
    options.forEach(function(item) {
        $(modalBodyId).append('<tr><td class="text-center">' + item + '</td></tr>');
    });
    $(modalId).modal('show');
}

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

function saveData() {
    const myform = document.getElementById('board_form');
    let allValid = true;
	
    if (!allValid) return;

    var num = $("#num").val();
    $("#overlay").show();
    $("button").prop("disabled", true);

    Toastify({
        text: "저장중...",
        duration: 2000,
        close: true,
        gravity: "top",
        position: "center",
        style: {
            background: "linear-gradient(to right, #00b09b, #96c93d)"
        },
    }).showToast();

    if (Number(num) < 1) {
        $("#mode").val('insert');
    } else {
        $("#mode").val('modify');
    }

    let formData = [];
    $('#estimateTable tbody tr').each(function() {
        let rowData = {};
        $(this).find('input, select').each(function() {
            let name = $(this).attr('name').replace('[]', '');
            let value = $(this).val();
            rowData[name] = value;
        });
        formData.push(rowData);
    });
	
    let jsonString = JSON.stringify(formData);
    $('#estimateList').val(jsonString);

    var form = $('#board_form')[0];
    var datasource = new FormData(form);

    if (ajaxRequest_write !== null) {
        ajaxRequest_write.abort();
    }

    ajaxRequest_write = $.ajax({
        enctype: 'multipart/form-data',
        processData: false,
        contentType: false,
        cache: false,
        timeout: 600000,
        url: "insert_estimate.php",
        type: "post",
        data: datasource,
        dataType: "json",
        success: function(data) {
            setTimeout(function() {
                if (window.opener && !window.opener.closed) {
                    if (typeof window.opener.restorePageNumber === 'function') {
                        window.opener.restorePageNumber();
                    }
                }
            }, 1000);
            ajaxRequest_write = null;
            setTimeout(function() {
                hideOverlay();
                self.close();
            }, 1000);
        },
        error: function(jqxhr, status, error) {
            console.log(jqxhr, status, error);
        }
    });
}

function deleteData() {    
    var level = '<?php echo $level; ?>';

    if (!first_writer.includes(first_writer) && level !== '1') {
        Swal.fire({
            title: '삭제불가',
            text: "작성자와 관리자만 삭제가능합니다.",
            icon: 'error',
            confirmButtonText: '확인'
        });
    } else {
        Swal.fire({
            title: '자료 삭제',
            text: "삭제는 신중! 정말 삭제하시겠습니까?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: '삭제',
            cancelButtonText: '취소'
        }).then((result) => {
            if (result.isConfirmed) {
                $("#mode").val('delete');
                var form = $('#board_form')[0];
                var formData = new FormData(form);

                formData.set('mode', $("#mode").val());
                formData.set('num', $("#num").val());

                if (ajaxRequest_write !== null) {
                    ajaxRequest_write.abort();
                }

                ajaxRequest_write = $.ajax({
                    enctype: 'multipart/form-data',
                    processData: false,
                    contentType: false,
                    cache: false,
                    timeout: 1000000,
                    url: "insert_estimate.php",
                    type: "post",
                    data: formData,
                    dataType: "json",
                    success: function(data) {
                        Toastify({
                            text: "파일 삭제완료 ",
                            duration: 2000,
                            close: true,
                            gravity: "top",
                            position: "center",
                            style: {
                                background: "linear-gradient(to right, #00b09b, #96c93d)"
                            },
                        }).showToast();
                        setTimeout(function() {
                            if (window.opener && !window.opener.closed) {
                                if (typeof window.opener.restorePageNumber === 'function') {
                                    window.opener.restorePageNumber();
                                }
                                window.opener.location.reload();
                                window.close();
                            }
                        }, 1000);
                    },
                    error: function(jqxhr, status, error) {
                        console.log(jqxhr, status, error);
                    }
                });
            }
        });
    }
}

function disableInputsForViewMode() {
    $('input, textarea').prop('readonly', true);
    $('select, .restrictbtn, .sub_add, .add').prop('disabled', true);
    $('input[type=file]').prop('readonly', false);
    $('input[type=checkbox]').prop('disabled', true);
    $('.viewNoBtn').prop('disabled', true);
    $('.specialbtnClear').prop('disabled', true);
}

function captureReturnKey(e) {
    if (e.keyCode == 13 && e.srcElement.type != 'textarea') {
        return false;
    }
}

function recaptureReturnKey(e) {
    if (e.keyCode == 13 && e.srcElement.type != 'textarea') {
        return false;
    }
}

function closePopup() {
    if (popupWindow && !popupWindow.closed) {
        popupWindow.close();
        isWindowOpen = false;
    }
}

function showWarningModal() {
    Swal.fire({
        title: '등록 오류 알림',
        text: '필수입력 요소를 확인바랍니다.',
        icon: 'warning',
    }).then(result => {
        if (result.isConfirmed) {
            return;
        }
    });
}

function showlotError() {
    Swal.fire({
        title: '등록 오류 알림',
        text: '입력 항목들을 점검해주세요.',
        icon: 'warning',
    }).then(result => {
        if (result.isConfirmed) {
            return;
        }
    });
}

function inputNumber(input) {
    // 현재 커서 위치를 저장
    const cursorPosition = input.selectionStart;
    // 입력값에서 숫자만 남기고 제거
    const value = input.value.replace(/,/g, '');    
    // 천 단위 콤마 추가
    const formattedValue = Number(value).toLocaleString();
    // 포맷팅된 값으로 설정
    input.value = formattedValue;
    // 포맷팅 후에도 원래 커서 위치 유지
    input.setSelectionRange(cursorPosition, cursorPosition);
}

$(document).ready(function() {
    var estimate = <?php echo json_encode($estimateList ?? []); ?>;

    // estimate가 비어 있거나 undefined일 때만 샘플 행 추가 코드 실행
    if (Array.isArray(estimate) && estimate.length === 0) {
        // 페이지가 로드되면 자동으로 add-row 클릭 이벤트를 6회 트리거
        $('.add-row').trigger('click');
        $('.add-row').trigger('click');
        
        setTimeout(function() {
            // 각 행에 입력할 데이터를 배열로 저장
            var rowData = [
                { col2: '1F', col3: 'FSS-1', col4: 'KSE01', col6: '벽면형(120*70)', col7: 'SUS마감', col8: '2335', col9: '3000', col14: '1', col15: '1', col16: '0', col17: '1', col18: '220V' },
                { col2: '2F', col3: 'FSS-2', col4: 'KSS01', col6: '벽면형(120*70)', col7: 'SUS마감', col8: '4405', col9: '3000', col14: '1', col15: '0', col16: '0', col17: '0', col18: '220V' },
                { col2: '3F', col3: 'FSS-3', col4: 'KSS01', col6: '벽면형(120*70)', col7: 'SUS마감', col8: '4405', col9: '3000', col14: '1', col15: '0', col16: '0', col17: '0', col18: '220V' },
                { col2: '4F', col3: 'FSS-4', col4: 'KSS01', col6: '벽면형(120*70)', col7: 'SUS마감', col8: '4405', col9: '3000', col14: '1', col15: '0', col16: '0', col17: '0', col18: '220V' },
                { col2: '5F', col3: 'FSS-5', col4: 'KSS01', col6: '벽면형(120*70)', col7: 'SUS마감', col8: '4250', col9: '3000', col14: '1', col15: '0', col16: '0', col17: '0', col18: '220V' }                
            ];

            // 각 행을 설정하는 반복문 
            rowData.forEach(function(data, index) {
                var row = $('#estimateTable tbody tr').eq(index);

                if (row.length > 0) {
                    row.find('input[name="col2[]"]').val(data.col2);
                    row.find('input[name="col3[]"]').val(data.col3);
                    row.find('select[name="col4[]"]').val(data.col4).trigger('change');
                    row.find('select[name="col6[]"]').val(data.col6).trigger('change');
                    row.find('select[name="col7[]"]').val(data.col7).trigger('change');
                    row.find('input[name="col8[]"]').val(data.col8).trigger('input');
                    row.find('input[name="col9[]"]').val(data.col9).trigger('input');
                    row.find('input[name="col14[]"]').val(data.col14).trigger('input');
                    row.find('input[name="col15[]"]').val(data.col15).trigger('input');
                    row.find('input[name="col16[]"]').val(data.col16).trigger('input');
                    row.find('input[name="col17[]"]').val(data.col17).trigger('input');
                    row.find('select[name="col18[]"]').val(data.col18).trigger('change');
                }
            });
            
            updateTotals();
        }, 1000); // 1000 milliseconds = 1 second
    }
});


function addRow(tableBody, rowData, typebutton) {
    var newRow = $('<tr>');
    var rowCount = tableBody.children('tr').length + 1;

    newRow.append('<td class="text-center" style="width:80px;">' +
        '<div class="d-flex justify-content-center mt-1">' + 
        '<button type="button" class="btn btn-primary btn-sm viewNoBtn add-row me-1" data-table="' + tableBody.closest('table').attr('id') + '">+</button>' +
        '<button type="button" class="btn btn-danger btn-sm viewNoBtn remove-row">-</button>' +
        '</div></td>');

    newRow.append('<td class="text-center" style="width:50px;">' +
        '<div class="d-flex flex-column justify-content-center">' +
        '<input type="text" name="col1[]" style="width:50px;" class="form-control text-center col-input" value="' + rowCount + '" readonly>' + 
        '</div></td>');

    for (let i = 2; i <= 66; i++) { 
        let width = [2, 3, 4, 5, 7, 20, 22, 23, 29, 31, 40].includes(i) ? '85px' : '50px';
        width = [6].includes(i) ? '120px' : width;         
        width = [18].includes(i) ? '60px' : width; 
        width = [23,32,43,46,49,62].includes(i) ? '10px' : width; 

        if ([4,6,7,18].includes(i)) {
			let options = '';
			if (i === 4) {
				options = '<option value=""></option>' + 
						  '<option value="KSS01"' + (rowData['col' + i] === 'KSS01' ? ' selected' : '') + '>KSS01</option>' +
						  '<option value="KSE01"' + (rowData['col' + i] === 'KSE01' ? ' selected' : '') + '>KSE01</option>' +
						  '<option value="KWE01"' + (rowData['col' + i] === 'KWE01' ? ' selected' : '') + '>KWE01</option>' +
						  '<option value="KD-SL60"' + (rowData['col' + i] === 'KD-SL60' ? ' selected' : '') + '>KD-SL60</option>' +
						  '<option value="KTE01"' + (rowData['col' + i] === 'KTE01' ? ' selected' : '') + '>KTE01</option>' +
						  '<option value="KQTS01"' + (rowData['col' + i] === 'KQTS01' ? ' selected' : '') + '>KQTS01</option>';
			} else if (i === 6) {
				options = '<option value=""></option>' + 
						  '<option value="벽면형(120*70)"' + (rowData['col' + i] === '벽면형(120*70)' ? ' selected' : '') + '>벽면형(120*70)</option>' +
						  '<option value="측면형(120*120)"' + (rowData['col' + i] === '측면형(120*120)' ? ' selected' : '') + '>측면형(120*120)</option>' +
						  '<option value="혼합형"' + (rowData['col' + i] === '혼합형' ? ' selected' : '') + '>혼합형</option>';
			} else if (i === 7) {
				options = '<option value=""></option>' + 
						  '<option value="SUS마감"' + (rowData['col' + i] === 'SUS마감' ? ' selected' : '') + '>SUS마감</option>' +
						  '<option value="EGI마감"' + (rowData['col' + i] === 'EGI마감' ? ' selected' : '') + '>EGI마감</option>';
			} else if (i === 18) {
				options = '<option value=""></option>' + 
						  '<option value="220V"' + (rowData['col' + i] === '220V' ? ' selected' : '') + '>220V</option>' +
						  '<option value="380V"' + (rowData['col' + i] === '380V' ? ' selected' : '') + '>380V</option>';
			}
        
            newRow.append('<td class="text-center">' +
                '<div class="d-flex justify-content-center">' +
                '<select name="col' + i + '[]" style="width:' + width + ';" class="form-control text-center col-select col' + i + '-select">' +
                options +
                '</select></div></td>');
				
        } else if ([5,10,11,12,13,19,20,21].includes(i)) {
            newRow.append('<td class="text-center">' +
                '<div class="d-flex justify-content-center">' +
                '<input type="text" name="col' + i + '[]" style="width:' + width + ';" class="form-control text-center col-input col' + i + '-input" readonly>' + 
                '</div></td>');
        } else {
            newRow.append('<td class="text-center">' +
                '<div class="d-flex justify-content-center">' +
                '<input type="text" name="col' + i + '[]" style="width:' + width + ';" class="form-control text-center col-input col' + i + '-input" value="' + (rowData['col' + i] || '') + '">' + 
                '</div></td>');
        }
    }

    tableBody.append(newRow);
	
	commonExe(newRow);

    newRow.find('.col4-select').on('change', function() {
        var col4Value = $(this).val();
        var col5Input = $(this).closest('tr').find('.col5-input');

        if (col4Value === "KSE01" || col4Value === "KSS01") {
            col5Input.val("실리카");
        } else {
            col5Input.val("와이어");
        }

        commonExe(newRow);
    });

    newRow.find('.col-input, .col-select').on('input change', function() {
        var row = $(this).closest('tr');
		commonExe(row);
    });
	
	function commonExe(row) {
        updateCol32(row);		
		updateCol10and11(row);
        updateCol12and13(row);
		updateCol21(row);		
		updateCol54(row);
        updateCol19(row);
        updateCol20(row);
        updateCol23(row);
        updateCol29(row);
        updateCol39(row);
        updateCol46(row);
        updateCol47(row);
        updateCol48(row);
        updateCol49(row);
        updateCol50to51(row);
        updateCol53(row);        
        updateCol55to60(row);
        updateCol61(row);
        updateCol62(row);
        updateCol63to64(row);
        updateCol65(row);
        updateCol40to45(row);
		updateCol22(row);
        updateCol31(row);
		updateCol33to38(row);
		updateTotals();
	}

    function updateCol10and11(row) {
        var col8Value = parseFloat(row.find('.col8-input').val()) || 0;
        var col9Value = parseFloat(row.find('.col9-input').val()) || 0;
        row.find('.col10-input').val(col8Value + 160);
        row.find('.col11-input').val(col9Value + 350);
    }

    function updateCol12and13(row) {
        var col8Value = parseFloat(row.find('.col8-input').val()) || 0;
        var col10Value = parseFloat(row.find('.col10-input').val()) || 0;
        var col11Value = parseFloat(row.find('.col11-input').val()) || 0;
        var area = (col10Value * col11Value) / 1000000;
        row.find('.col12-input').val(area.toFixed(2));
        var weight = (area * 2) + (col8Value / 1000 * 14.17);		
        row.find('.col13-input').val(weight.toFixed(2));
    }

    function updateCol19(row) {
        var col53Value = parseFloat(row.find('.col53-input').val()) || 0;
        var col13Value = parseFloat(row.find('.col13-input').val()) || 0;
        var col19Input = row.find('.col19-input');

        if ((col53Value === 4 && col13Value <= 150) ||
            (col53Value === 5 && col13Value <= 123) ||
            (col53Value === 6 && col13Value <= 104)) {
            col19Input.val(1);
        } else {
            col19Input.val(0);
        }
    }

    function updateCol20(row) {
        var col13Value = parseFloat(row.find('.col13-input').val()) || 0;
        var col20Input = row.find('.col20-input');

        if (col13Value <= 300) {
            col20Input.val("380*180");
        } else if (col13Value <= 400) {
            col20Input.val("530*320");
        } else if (col13Value > 400 && col13Value <= 600) {
            col20Input.val("600*350");
        } else if (col13Value > 600 && col13Value <= 1000) {
            col20Input.val("690*390");
        } else {
            col20Input.val(0);
        }

        updateCol22(row);
        updateCol31(row);
    }

    function updateCol22(row) {
        var col20Value = row.find('.col20-input').val();
        var col22Input = row.find('.col22-input');

        if (col20Value === "380*180") {
            col22Input.val("40*40*380");
        } else if (col20Value === "530*320") {
            col22Input.val("50*50*530");
        } else {
            col22Input.val(0);
        }
    }

    function updateCol23(row) {
        var col9Value = parseFloat(row.find('.col9-input').val()) || 0;
        var col23Input = row.find('.col23-input');
        col23Input.val(col9Value + 250);

        updateCol24to28(row);
    }

    function updateCol24to28(row) {
        var col23Value = parseFloat(row.find('.col23-input').val()) || 0;
        
        var col24Input = row.find('.col24-input');
        col24Input.val(col23Value <= 2438 ? 2 : 0);

        var col25Input = row.find('.col25-input');
        col25Input.val((col23Value > 2438 && col23Value <= 3000) ? 2 : 0);

        var col26Input = row.find('.col26-input');
        col26Input.val((col23Value > 3000 && col23Value <= 3500) ? 2 : 0);

        var col27Input = row.find('.col27-input');
        col27Input.val((col23Value > 3500 && col23Value <= 4000) ? 2 : 0);

        var col28Input = row.find('.col28-input');
        col28Input.val((col23Value > 4000 && col23Value <= 4300) ? 2 : 0);

        updateCol30(row);
    }

    function updateCol29(row) {
        var col6Value = row.find('.col6-select').val();
        var col29Input = row.find('.col29-input');

        if (col6Value === "벽면형(120*70)") {
            col29Input.val("130*80");
        } else if (col6Value === "측면형(120*120)") {
            col29Input.val("130*130");
        } else {
            col29Input.val(0);
        }
    }

    function updateCol30(row) {
        var col24to28Sum = 
            (parseInt(row.find('.col24-input').val()) || 0) +
            (parseInt(row.find('.col25-input').val()) || 0) +
            (parseInt(row.find('.col26-input').val()) || 0) +
            (parseInt(row.find('.col27-input').val()) || 0) +
            (parseInt(row.find('.col28-input').val()) || 0);

        row.find('.col30-input').val(col24to28Sum * 2);
    }

    function updateCol31(row) {
        var col20Value = row.find('.col20-input').val();
        var col31Input = row.find('.col31-input');

        if (col20Value === "380*180") {
            col31Input.val("500*380");
        } else {
            col31Input.val(0);
        }
    }

    function updateCol32(row) {
        var col8Value = parseFloat(row.find('.col8-input').val()) || 0;
        var col32Input = row.find('.col32-input');
        col32Input.val(col8Value + 220);
    }

    function updateCol39(row) {
        var col32Value = parseFloat(row.find('.col32-input').val()) || 0;
        var col39Input = row.find('.col39-input');
        col39Input.val(Math.ceil(col32Value / 1219));
    }

    function updateCol40to45(row) {
        var col8Value = parseFloat(row.find('.col8-input').val()) || 0;
        var col14Value = parseFloat(row.find('.col14-input').val()) || 0;
        var col31Value = row.find('.col31-input').val() || "";

        var col40Input = row.find('.col40-input');
        var col41Input = row.find('.col41-input');
        var col42Input = row.find('.col42-input');
        var col43Input = row.find('.col43-input');
        var col44Input = row.find('.col44-input');
        var col45Input = row.find('.col45-input');

        col40Input.val(col31Value == "500*380" ? "505*385" : "500*355");

        col41Input.val(col14Value * 2);
		
		// 8번째 요소에 220을 더해야 한다.
        col42Input.val(Math.floor((col8Value+220)*2/3000+1 ));
		
        col43Input.val(col8Value);

        col44Input.val(col8Value <= 3000 ? 1 :
                      col8Value <= 4000 ? 2 :
                      col8Value <= 6000 ? 2 :
                      col8Value <= 7000 ? 1 : 3);

		col45Input.val(
			(col8Value > 3000 && col8Value <= 4000) ? 1 :
			(col8Value > 6000 && col8Value <= 7000) ? 1 :
			(col8Value > 7000 && col8Value <= 8000) ? 2 : 0
		);

    }

    function updateCol46(row) {
        var col32Value = parseFloat(row.find('.col32-input').val()) || 0;
        var col46Input = row.find('.col46-input');
        col46Input.val(col32Value);
    }
	
	function updateCol47(row) {
		var col46Value = parseFloat(row.find('.col46-input').val()) || 0;
		var col47Input = row.find('.col47-input');

		col47Input.val((col46Value <= 3000) ? 2 :
					   (col46Value > 4000 && col46Value <= 6000) ? 4 :
					   (col46Value > 6000 && col46Value <= 7000) ? 2 :
					   (col46Value > 8000 && col46Value <= 9000) ? 6 : 0);
	}

	function updateCol48(row) {
		var col46Value = parseFloat(row.find('.col46-input').val()) || 0;
		var col48Input = row.find('.col48-input');

		col48Input.val((col46Value > 3000 && col46Value <= 4000) ? 2 :
					   (col46Value > 6000 && col46Value <= 7000) ? 2 :
					   (col46Value > 7000 && col46Value <= 8000) ? 4 : 0);
	}

    function updateCol49(row) {
        var col32Value = parseFloat(row.find('.col32-input').val()) || 0;
        var col49Input = row.find('.col49-input');
        col49Input.val(col32Value);

        updateCol50to51(row);
    }

	function updateCol50to51(row) {
		var col49Value = parseFloat(row.find('.col49-input').val()) || 0;

		var col50Input = row.find('.col50-input');
		var col51Input = row.find('.col51-input');

		// col50Input 값 설정
		if (col49Value <= 3000) {
			col50Input.val(1);
		} else if (col49Value <= 4000) {
			col50Input.val(1);
		} else if (col49Value <= 6000) {
			col50Input.val(2);
		} else if (col49Value <= 7000) {
			col50Input.val(1);
		} else {
			col50Input.val(3);
		}

		// col51Input 값 설정 (엑셀 공식 반영)
		if (col49Value > 3000 && col49Value <= 4000) {
			col51Input.val(1);
		} else if (col49Value > 6000 && col49Value <= 7000) {
			col51Input.val(1);
		} else if (col49Value > 7000 && col49Value <= 8000) {
			col51Input.val(2);
		} else {
			col51Input.val(0);
		}
	}


    function updateCol53(row) {
        var col10Value = parseFloat(row.find('.col10-input').val()) || 0;
        var col53Input = row.find('.col53-input');

        if (col10Value <= 6000) {
            col53Input.val(4);
        } else if (col10Value > 6000 && col10Value <= 8200) {
            col53Input.val(5);
        } else {
            col53Input.val(0);
        }
    }

    function updateCol54(row) {
        var col14Value = parseFloat(row.find('.col14-input').val()) || 0;
        row.find('.col54-input').val(col14Value);
    }

    function updateCol55to60(row) {
        var col53Value = parseFloat(row.find('.col53-input').val()) || 0;
        var col8Value = parseFloat(row.find('.col8-input').val()) || 0;

        row.find('.col55-input').val((col53Value === 4 && col8Value <= 3050) ? 1 : 0);
        row.find('.col56-input').val((col53Value === 4 && col8Value > 3050 && col8Value <= 4550) ? 1 : 0);
        row.find('.col57-input').val((col53Value === 4 && col8Value > 4550 && col8Value <= 6050) ? 1 : 0);
        row.find('.col58-input').val((col53Value === 5 && col8Value > 4850 && col8Value <= 6050) ? 1 : 0);
        row.find('.col59-input').val((col53Value === 5 && col8Value > 6050 && col8Value <= 7050) ? 1 : 0);
        row.find('.col60-input').val((col53Value === 5 && col8Value > 7050) ? 1 : 0);
    }

    function updateCol61(row) {
        var col32Value = parseFloat(row.find('.col32-input').val()) || 0;

        var col61Input = row.find('.col61-input');
        col61Input.val((col32Value <= 1600) ? 3 :
                      (col32Value <= 2800) ? 4 :
                      (col32Value <= 4000) ? 5 :
                      (col32Value <= 5200) ? 6 :
                      (col32Value <= 6400) ? 7 :
                      (col32Value <= 7600) ? 8 :
                      (col32Value <= 8800) ? 9 : 0);
    }

    function updateCol62(row) {
        var col32Value = parseFloat(row.find('.col32-input').val()) || 0;
        var col61Value = parseFloat(row.find('.col61-input').val()) || 0;

        row.find('.col62-input').val(col32Value + 3000 * col61Value);
    }

	function updateCol63to64(row) {
		var col62Value = parseFloat(row.find('.col62-input').val()) || 0;

		// col63 계산
		var col63Input = row.find('.col63-input');
		col63Input.val((col62Value <= 9000) ? 3 :
					   (col62Value > 9000 && col62Value <= 12000) ? 4 :
					   (col62Value > 12000 && col62Value <= 15000) ? 5 :
					   (col62Value > 15000 && col62Value <= 18000) ? 6 : 0);

		// col64 계산
		var col64Input = row.find('.col64-input');
		col64Input.val((col62Value > 18000 && col62Value <= 24000) ? 4 :
					   (col62Value > 24000 && col62Value <= 30000) ? 5 :
					   (col62Value > 30000 && col62Value <= 36000) ? 6 :
					   (col62Value > 36000 && col62Value <= 42000) ? 7 :
					   (col62Value > 42000 && col62Value <= 48000) ? 8 : 0);
	}

    function updateCol65(row) {
        var col10Value = parseFloat(row.find('.col10-input').val()) || 0;
        var col65Input = row.find('.col65-input');

        col65Input.val((col10Value <= 3000) ? 1 :
                      (col10Value <= 6000) ? 2 :
                      (col10Value <= 9000) ? 3 :
                      (col10Value <= 12000) ? 4 : 0);
    }

	// col21 값을 col53에 따라 설정하는 함수
	function updateCol21(row) {
		var col53Value = parseFloat(row.find('.col53-input').val()) || 0;
		var col21Input = row.find('.col21-input');
		col21Input.val(col53Value);
	}

	// col33 ~ col38 계산 함수 (기존 수식과 로직을 구현)
	function updateCol33to38(row) {
		var col32Value = parseFloat(row.find('.col8-input').val() ) || 0;
		col32Value += 220;
        // console.log('col32Value',col32Value);
		// col33 값 계산
		var col33Value = (col32Value <= 1219) ? 1 :
						 (col32Value > 4150 && col32Value <= 4219) ? 1 :
						 (col32Value > 4219 && col32Value <= 4719) ? 1 :
						 (col32Value > 4876 && col32Value <= 5219) ? 1 :
						 (col32Value > 5219 && col32Value <= 5369) ? 1 :
						 (col32Value > 9026 && col32Value <= 9219) ? 1 :
						 0;
		row.find('.col33-input').val(col33Value);

		// col34 값 계산
		var col34Value = (col32Value > 1219 && col32Value <= 2438) ? 1 :
						 (col32Value > 4719 && col32Value <= 4876) ? 2 :
						 (col32Value > 5369 && col32Value <= 5938) ? 1 :
						 (col32Value > 6000 && col32Value <= 6438) ? 1 :
						 (col32Value > 6500 && col32Value <= 6588) ? 1 :
						 (col32Value > 8300 && col32Value <= 8376) ? 2 :
						 (col32Value > 8376 && col32Value <= 8438) ? 1 :
						 (col32Value > 8438 && col32Value <= 8876) ? 2 :
						 (col32Value > 9000 && col32Value <= 9026) ? 2 :
						 (col32Value > 9219 && col32Value <= 9438) ? 1 :
						 (col32Value > 10150 && col32Value <= 10738) ? 1 :
						 0;
		row.find('.col34-input').val(col34Value);

		// col35 값 계산
		var col35Value = (col32Value > 2438 && col32Value <= 3000) ? 1 :
						 (col32Value > 4150 && col32Value <= 4219) ? 1 :
						 (col32Value > 5369 && col32Value <= 5438) ? 1 :
						 (col32Value > 5938 && col32Value <= 6000) ? 2 :
						 (col32Value > 6438 && col32Value <= 6500) ? 1 :
						 (col32Value > 7000 && col32Value <= 7150) ? 1 :
						 (col32Value > 8376 && col32Value <= 8438) ? 2 :
						 (col32Value > 8876 && col32Value <= 9000) ? 3 :
						 (col32Value > 9438 && col32Value <= 10150) ? 2 :
						 (col32Value > 10738 && col32Value <= 11000) ? 1 :
						 0;
		row.find('.col35-input').val(col35Value);

		// col36 값 계산
		var col36Value = (col32Value > 3000 && col32Value <= 3500) ? 1 :
						 (col32Value > 4219 && col32Value <= 4719) ? 1 :
						 (col32Value > 5438 && col32Value <= 5938) ? 1 :
						 (col32Value > 6438 && col32Value <= 6500) ? 1 :
						 (col32Value > 6588 && col32Value <= 7000) ? 2 :
						 (col32Value > 7150 && col32Value <= 7650) ? 1 :
						 (col32Value > 8300 && col32Value <= 8376) ? 1 :
						 (col32Value > 9219 && col32Value <= 9438) ? 2 :
						 (col32Value > 9438 && col32Value <= 9500) ? 1 :
						 0;
		row.find('.col36-input').val(col36Value);

		// col37 값 계산
		var col37Value = (col32Value > 3500 && col32Value <= 4000) ? 1 :
						 (col32Value > 4876 && col32Value <= 5219) ? 1 :
						 (col32Value > 6000 && col32Value <= 6438) ? 1 :
						 (col32Value > 7150 && col32Value <= 7500) ? 1 :
						 (col32Value > 7650 && col32Value <= 8000) ? 2 :
						 (col32Value > 8000 && col32Value <= 8150) ? 1 :
						 (col32Value > 8438 && col32Value <= 8876) ? 1 :
						 (col32Value > 9026 && col32Value <= 9219) ? 2 :
						 (col32Value > 9500 && col32Value <= 10000) ? 1 :
						 (col32Value > 10150 && col32Value <= 10438) ? 2 :
						 (col32Value > 10738 && col32Value <= 11000) ? 2 :
						 0;
		row.find('.col37-input').val(col37Value);

		// col38 값 계산
		var col38Value = (col32Value > 4000 && col32Value <= 4150) ? 1 :
						 (col32Value > 5219 && col32Value <= 5369) ? 1 :
						 (col32Value > 6500 && col32Value <= 6588) ? 1 :
						 (col32Value > 7000 && col32Value <= 7150) ? 1 :
						 (col32Value > 7500 && col32Value <= 7650) ? 1 :
						 (col32Value > 8000 && col32Value <= 8150) ? 1 :
						 (col32Value > 8150 && col32Value <= 8300) ? 2 :
						 (col32Value > 9000 && col32Value <= 9026) ? 1 :
						 (col32Value > 10000 && col32Value <= 10150) ? 1 :
						 (col32Value > 10438 && col32Value <= 10738) ? 2 :
						 0;
		row.find('.col38-input').val(col38Value);
	}

    newRow.find('.col4-select').trigger('change');
    newRow.find('.col6-select').trigger('change');
    newRow.find('.col8-input').trigger('change');
    newRow.find('.col9-input').trigger('change');
}


</script>

