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

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

if ($mode === 'copy') {
    $title_message = "(데이터복사) 절곡판 단가";
} else {
    $title_message = "절곡판 단가";
}

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

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

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

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

</head>

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

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


if ($mode == "copy" || $mode == 'split') {
    try {
        $sql = "select * from " . $DB . ".{$tablename}  where num = ? ";
        $stmh = $pdo->prepare($sql); 
        $stmh->bindValue(1, $num, PDO::PARAM_STR); 
        $stmh->execute();
        $count = $stmh->rowCount();              
        if($count<1){  
            print "검색결과가 없습니다.<br>";
        } else {
            $row = $stmh->fetch(PDO::FETCH_ASSOC);
        }
        include '_row.php';
    } catch (PDOException $Exception) {
        print "오류: ".$Exception->getMessage();
    }
    // 자료번호 초기화 
    $num = 0;		 
	$registedate=date("Y-m-d");
	$mode = 'insert';
}  
    
if(empty($mode))
     $mode='insert';	

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

<input type="hidden" id="mode" name="mode" value="<?= isset($mode) ? $mode : '' ?>">
<input type="hidden" id="num" name="num" value="<?= isset($num) ? $num : '' ?>">
<input type="hidden" id="level" name="level" value="<?= isset($level) ? $level : '' ?>">
<input type="hidden" id="user_name" name="user_name" value="<?= isset($user_name) ? $user_name : '' ?>">
<input type="hidden" id="update_log" name="update_log" value="<?= isset($update_log) ? $update_log : NULL ?>">
<input type="hidden" id="tablename" name="tablename" value="<?= isset($tablename) ? $tablename : '' ?>">
<input type="hidden" id="is_deleted" name="is_deleted" value="<?= isset($is_deleted) ? $is_deleted : '0' ?>">
<input type="hidden" id="itemList" name="itemList">

<?php include $_SERVER['DOCUMENT_ROOT'] . "/common/write_formTopCard.php";  // 저장, 수정, 닫기 등 card 모음 ?>		

<div class="container-fluid mt-4">
      <div class="row ">    
        <div class="col-lg-2 col-sm-2">	  
		</div>
	<div class="col-lg-8 col-sm-8">	  		
		  <div class=" d-flex justify-content-center align-items-center"> 
				<table class="table table-bordered">
					<tbody>						
						<tr>
							<td class="text-center" style="width:10%;"> 등록일 </td>
							<td class="text-center"   style="width:10%;"  > 
								<input type="date" id="registedate" name="registedate" class="form-control"value="<?= isset($registedate) ? $registedate : '' ?>">
							</td>     
							<td class="text-center"   style="width:10%;"  >  메모 </td>
							<td > 
								<textarea id="memo" name="memo" class="form-control" rows="4"><?=$memo?></textarea>
							</td>          							
						</tr>								
					</tbody>
				</table>                    
			  </div>				                				
		  </div>				                				
			<div class="col-lg-2 col-sm-2">	  
		</div>		  
	  </div>	
	<div class='d-flex mt-2 mb-2 m-1'>
		<span class='badge bg-dark fs-6 me-3'>품목(item)</span>
		<button type='button' class='btn btn-primary btn-sm viewNoBtn add-row' data-table='myTable' style='margin-right: 5px;'>+</button>
		<!-- <button type='button' class='btn btn-danger btn-sm viewNoBtn remove-row' data-table='myTable' style='margin-right: 5px;'>-</button> -->
	</div>		  
    <div class="row justify-content-center">
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title text-center">절곡판 단가표</h5>
                    <table id="myTable" class="table table-bordered table-hover">
						<thead class="table-primary text-center">
							<tr>
								<th rowspan="2" class="align-middle">+ - Copy</th>
								<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 bg-primary text-white">(판매) <br> ㎡ / 단가</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>
    </div>

</form>

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

var ajaxRequest = null;
var ajaxRequest_write = null;

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

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

});

function initializePage() {
    // PHP에서 넘어온 JSON 데이터를 JavaScript 객체로 변환
    var itemList = <?php echo isset($itemList) ? json_encode($itemList) : '[]'; ?>;

    // itemList가 올바른 배열인지 확인
    if (!Array.isArray(itemList)) {
        itemList = [];
    }

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

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

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


function saveData() {
	
    const formData = [];
    $('#myTable 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);
    });
    
    // JSON으로 인코딩된 데이터를 서버로 전송
    $('#itemList').val(JSON.stringify(formData));

    const form = $('#board_form')[0];
    const 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.php",
        type: "post",
        data: datasource,
        dataType: "json",
        success: function(data) {
                console.log(data);                
               
                setTimeout(function() {
                Toastify({
                        text: "저장완료",
                        duration: 3000,
                        close:true,
                        gravity:"top",
                        position: "center",
                        style: {
                            background: "linear-gradient(to right, #00b09b, #96c93d)"
                        },
                    }).showToast();                

                    }, 1000);        
               
                    setTimeout(function() {
                        if (window.opener && !window.opener.closed) {                    
                            if (typeof window.opener.restorePageNumber === 'function') {
                                window.opener.restorePageNumber(); // 함수가 있으면 실행
                            }                    
                        }     
                        setTimeout(function() {
                           if (data && data.num) 
                            // 저장된 데이터 번호를 사용하여 새로운 페이지로 이동                        
                            window.location.href = 'write_form.php?mode=view&tablename=' + $('#tablename').val() + '&num=' + data.num;    
                        }, 1000);    
                   
                }, 1500);    

                hideOverlay();                               
           
    },
    error: function(jqxhr, status, error) {
        console.log(jqxhr, status, error);
        alert("An error occurred: " + error); // Display error message
    }                        
 });
}

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

    if (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.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) {
								window.opener.location.reload(); // 부모창 리로드
							}

							setTimeout(function() {
								self.close(); // 현재 창 닫기
							}, 1000);

						}, 1500);
  

						hideOverlay();                     
                    },
                    error: function(jqxhr, status, error) {
                        console.log(jqxhr, status, error);
                    }
                });
            }
        });
    }
}

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

    // + / - 버튼 추가
    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 ms-2 me-2">-</button>' +
        '<button type="button" class="btn btn-success btn-sm viewNoBtn copy-row"><i class="bi bi-copy"></i></button>' +
        '</div></td>');

    // 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);

    // 숫자 필드에 3자리마다 콤마 추가
    newRow.find('.number-format').on('input change', function() {
        let value = $(this).val().replace(/,/g, '');  // 기존의 콤마를 제거
        if (!isNaN(value) && value !== '') {
            $(this).val(Number(value).toLocaleString('en'));  // 3자리마다 콤마 추가
        }
		calculateRow(newRow);
    });

    // 처음 로드될 때도 자동 계산 적용
    calculateRow(newRow);
}
function calculateRow(row) {
    // col3부터 col18까지의 값을 가져오기
    const col3 = parseFloat(row.find('.col3').val().replace(/,/g, '')) || 0;
    const col4 = parseFloat(row.find('.col4').val().replace(/,/g, '')) || 0;
    const col5 = parseFloat(row.find('.col5').val().replace(/,/g, '')) || 0;
    const col6 = parseFloat(row.find('.col6').val().replace(/,/g, '')) || 0;
	const col7 = (Math.round(col3 * col4)); // col7을 반올림하여 소수점 첫째자리까지 계산


    // col7 계산
    if (!isNaN(col7)) {
        row.find('.col7').val(Number(col7).toLocaleString('en'));
    }

    const col8 = (col5 * col6 * col7).toFixed(1); // col8은 col5 * col6 * col7로 계산
    if (!isNaN(col8)) {
        row.find('.col8').val(Number(col8).toLocaleString('en'));
    }

    const col9 = parseFloat(row.find('.col9').val().replace(/,/g, '')) || 0;
    const col10 = (col9 * 1.2).toFixed(1); // col10 = col9 * 1.2로 계산
    if (!isNaN(col10)) {
        row.find('.col10').val(Number(col10).toLocaleString('en'));
    }

    const col11 = (col8 * col10).toFixed(1); // col11 = col8 * col10로 계산
    if (!isNaN(col11)) {
        row.find('.col11').val(Number(col11).toLocaleString('en'));
    }

    const col12 = (Math.round(col11 / 1000) * 1000).toFixed(1); // col12는 엑셀수식 ROUND(N5,-3)
    if (!isNaN(col12)) {
        row.find('.col12').val(Number(col12).toLocaleString('en'));
    }

    const col13 = parseFloat(row.find('.col13').val().replace(/,/g, '')) || 0;
    const col14 = (Math.round(col7 * col13 / 1000) * 1000).toFixed(1); // col14는 엑셀수식 ROUND(J5*P5,-3)
    if (!isNaN(col14)) {
        row.find('.col14').val(Number(col14).toLocaleString('en'));
    }

    const col15 = (parseFloat(col12) + parseFloat(col14)).toFixed(1); // col15는 엑셀수식 O5+Q5
    if (!isNaN(col15)) {
        row.find('.col15').val(Number(col15).toLocaleString('en'));
    }

    const col16 = (col15 / col7).toFixed(1); // col16는 엑셀수식 R5/J5
    if (!isNaN(col16)) {
        row.find('.col16').val(Number(col16).toLocaleString('en'));
    }

    const col17 = (Math.round(col16 / 1000) * 1000).toFixed(1); // col17는 엑셀수식 ROUND(S5,-3)
    if (!isNaN(col17)) {
        row.find('.col17').val(Number(col17).toLocaleString('en'));
    }

    const col18 = (col15 / col8).toFixed(1); // col18는 엑셀수식 R5/K5
    if (!isNaN(col18)) {
        row.find('.col18').val(Number(col18).toLocaleString('en'));
    }
}


$(document).ready(function() {
    var mode = '<?php echo $mode; ?>'; 

	
	$("#copyBtn").click(function(){ 
		
		location.href = 'write_form.php?mode=copy&num='  + $("#num").val() + "&tablename="  + $("#tablename").val() ;
				
	 }); // end of function		
	
    // view 모드일 때, 버튼 및 입력 요소 비활성화
    if (mode === 'view') {
        $('input, textarea').prop('readonly', true); // Disable all input, textarea, and select elements
        $('input[type=hidden]').prop('readonly', false); 
        $('button.add-row, button.remove-row, button.copy-row').prop('disabled', true); // 버튼 비활성화
    }	
	

    // 행 삭제
    $(document).on('click', '.remove-row', function() {
        if (mode !== 'view') {
            $(this).closest('tr').remove();
        }
    }); 

    // 행 추가
    $(document).on('click', '.add-row', function() {
        if (mode !== 'view') {
            var tableId = $(this).data('table');
            var tableBody = $('#' + tableId).find('tbody');
            addRow(tableBody, {}, tableId);
        }
    });	
	
    // 행 복사
    $(document).on('click', '.copy-row', function() {
        if (mode !== 'view') {
            var currentRow = $(this).closest('tr');
            var clonedRow = currentRow.clone(); // 현재 행 복사
            clonedRow.find('input').each(function() {
                // 복사된 행의 input 값도 복사
                $(this).val($(this).val());
            });
            currentRow.after(clonedRow); // 현재 행 바로 아래에 추가
        }
    });

	
});

</script>


</body>
</html>
