<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");  

if (!isset($_SESSION["level"]) || $_SESSION["level"] > 5) {
    sleep(1);
    header("Location:" . $WebSite . "login/login_form.php");
    exit;
}   
include $_SERVER['DOCUMENT_ROOT'] . '/load_header.php';
$title_message = '소모품 단가'; 
?>
 
<link href="css/style.css" rel="stylesheet">   
<title> <?=$title_message?> </title> 
</head> 

<body>         
<?php
$header = isset($_REQUEST['header']) ? $_REQUEST['header'] : '';  

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

function checkNull($strtmp) {
    return ($strtmp !== null && trim($strtmp) !== '');
}

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

$tablename = 'price_etc';

require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();
 
$order = " ORDER BY  registedate desc  ";
    
if (checkNull($search)) {
    $sql = "SELECT * FROM ".$DB.".".$tablename." 
            WHERE searchtag LIKE '%$search%' AND is_deleted IS NULL " . $order;    
} else {
    $sql = "SELECT * FROM ".$DB.".".$tablename . " WHERE is_deleted IS NULL " . $order;   
}

try {      
    $stmh = $pdo->query($sql);
    $total_row = $stmh->rowCount();        
?>    

<form id="board_form" name="board_form" method="post" enctype="multipart/form-data">             
    <input type="hidden" id="mode" name="mode" value="<?=$mode?>">             
    <input type="hidden" id="num" name="num"> 
    <input type="hidden" id="tablename" name="tablename" value="<?=$tablename?>">                 
    <input type="hidden" id="header" name="header" value="<?=$header?>">      

<div class="container-fluid">
	<!-- Modal -->
	<div id="myModal" class="modal">
		<div class="modal-content" >
			<div class="modal-header">
				<span class="modal-title">소모품 단가</span>
				<span class="close">&times;</span>
			</div>
			<div class="modal-body">
				<div class="custom-card"></div>
			</div>
		</div>
	</div>
</div>

                
<?php 
if ($chkMobile) {
    print '<div class="container-fluid">';
    print '<div class="card justify-content-center text-center mt-1">';
} else {
    print '<div class="container">';
    print '<div class="card justify-content-center text-center mt-5">';
}
?>     
    <div class="card-header">
        <span class="text-center fs-5">  <?=$title_message?>   </span>                                
    </div>
    <div class="card-body">  
    <div class="container mt-2 mb-2">   
    ▷ <?= $total_row ?> &nbsp; 
    <div class="inputWrap30">            
        <input type="text" id="search" class="form-control" style="width:150px;" name="search" value="<?=$search?>" onKeyPress="if (event.keyCode==13){ enter(); }">
        <button class="btnClear"></button>
    </div>                            
    &nbsp;&nbsp;
    <button class="btn btn-outline-dark btn-sm" type="button" id="searchBtn"> <i class="bi bi-search"></i> </button> &nbsp;&nbsp;&nbsp;&nbsp;        
    
    <button id="newBtn" type="button" class="btn btn-dark btn-sm me-2"> <i class="bi bi-pencil-square"></i> 신규 </button>    
    <?php if($header !== 'header') 
            print '<button id="closeBtn" type="button" class="btn btn-dark btn-sm"> &times; 닫기 </button>';
    ?>            
    </div>        
        
    <div class="table-responsive">   
       <table class="table table-hover" id="myTable">         
            <thead class="table-primary">
                 <th class="text-center" style="width:60px;">번호</th>
                 <th class="text-center" style="width:80px;">등록일자</th>                 
                 <th class="text-center" style="width:200px;">품목명</th>
                 <th class="text-center" style="width:150px;">규격</th>                 			     
                 <th class="text-center" style="width:50px;">수량</th>
                 <th class="text-center" style="width:50px;">단위</th>
				 <th class="text-center" style="width:100px;">단가</th>                 
                 <th class="text-center" style="width:100px;">매입처</th>                 			     
                 <th class="text-center" style="width:200px;">비고</th>
            </thead>
            <tbody>                  
            <?php          
            $start_num = $total_row;                  
            while($row = $stmh->fetch(PDO::FETCH_ASSOC)) {
                include '_row.php';                                        
            ?>                     
            <tr onclick="loadForm('update', '<?=$num?>');">
                <td class="text-center"><?= $start_num ?></td>
                <td class="text-center"><?= $registedate ?></td>                
                <td class="text-start fw-bold text-primary"><?= $item_name ?></td>                
                <td class="text-start text-secondary"><?= $spec ?></td>                
                <td class="text-center">
					<?php if (is_numeric($surang)) : ?>
						<?= number_format($surang) ?>
					<?php else : ?>
						<?= htmlspecialchars($surang) ?>
					<?php endif; ?>
				</td>

				<td class="text-center"><?= $unit ?></td>                
				<td class="text-end"><?= $unitprice ?></td>                
                <td class="text-start"><?= $secondord?></td>                
                <td class="text-start"><?= $comment ?></td>
            </tr>
        <?php
            $start_num--;
                 } 
              } catch (PDOException $Exception) {
                  print "오류: ".$Exception->getMessage();
              }  
        ?>         
      </tbody>
     </table>
    </div>
    </div>
    </div>        
</form>

</body>
</html>


<script>
var ajaxRequest = null;
var itemData = [];

function loadForm(mode, num = null) {
    if (mode === 'copy' && num) {
        $("#mode").val('copy');
        $("#num").val(num); // 기존 데이터 복사할 num 유지
    } else if (num == null) {
        $("#mode").val('insert');
    } else {
        $("#mode").val('update');
        $("#num").val(num);
    }   
	
    $.ajax({
        type: "POST",
        url: "fetch_modal.php",
        data: { mode: mode, num: num },
        dataType: "html",
        success: function(response) {
            document.querySelector(".modal-body .custom-card").innerHTML = response;
            $("#myModal").show();

            $("#closeBtn").off("click").on("click", function() {
                $("#myModal").hide();
            });

            // 기존 이벤트 제거 후 재등록
            $(document).off('click', '.specialbtnClear').on('click', '.specialbtnClear', function(e) {
                e.preventDefault(); // 기본 동작을 방지합니다.                
                $('#item_name').val('');                
            });

            let isSaving = false;

            // 저장 버튼 (기존 이벤트 제거 후 재등록)
            $("#saveBtn").off("click").on("click", function() {
                if (isSaving) return;
                isSaving = true;

                var header = $("#header").val();
                var formData = $("#board_form").serialize();                

                $.ajax({
                    url: "process.php",
                    type: "post",
                    data: formData,
                    success: function(response) {
                        Toastify({
                            text: "저장완료",
                            duration: 3000,
                            close: true,
                            gravity: "top",
                            position: "center",
                            backgroundColor: "#4fbe87",
                        }).showToast();

                        setTimeout(function() {
                            $("#myModal").hide();
                            location.reload();
                        }, 2000);
                    },
                    error: function(jqxhr, status, error) {
                        console.log(jqxhr, status, error);
                        isSaving = false;
                    }
                });
            });		

            // 복사 버튼 (기존 이벤트 제거 후 재등록)
            $("#copyBtn").off("click").on("click", function() {
                var num = $('#num').val(); // num을 비워 새로 삽입할 수 있도록 초기화
				$("#myModal").hide();
				setTimeout(function() {
					copyForm('copy', num); // 복사 모드로 폼 다시 로드						
				}, 500);				
                
            });
			
            // 삭제 버튼
            $("#deleteBtn").off("click").on("click", function() {			            
                var level = '<?= $_SESSION["level"] ?>';

                if (level !== '1') {
                    Swal.fire({
                        title: '삭제불가',
                        text: "관리자만 삭제 가능합니다.",
                        icon: 'error',
                        confirmButtonText: '확인'
                    });
                    return;
                }

                Swal.fire({
                    title: '자료 삭제',
                    text: "삭제는 신중! 정말 삭제하시겠습니까?",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: '삭제',
                    cancelButtonText: '취소'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $("#mode").val('delete');
                        var formData = $("#board_form").serialize();

                        $.ajax({
                            url: "process.php",
                            type: "post",
                            data: formData,
                            success: function(response) {
                                Toastify({
                                    text: "파일 삭제완료",
                                    duration: 2000,
                                    close: true,
                                    gravity: "top",
                                    position: "center",
                                    style: {
                                        background: "linear-gradient(to right, #00b09b, #96c93d)"
                                    },
                                }).showToast();

                                $("#myModal").hide();
                                location.reload();
                            },
                            error: function(jqxhr, status, error) {
                                console.log(jqxhr, status, error);
                            }
                        });
                    }
                });
            });
        },
        error: function(jqxhr, status, error) {
            console.log("AJAX Error: ", status, error);
        }
    });
}


function copyForm(mode, num = null) {
    if (mode === 'copy' && num) {
        $("#mode").val('copy');
        $("#num").val(num); // 기존 데이터 복사할 num 유지
    } else if (num == null) {
        $("#mode").val('insert');
    } else {
        $("#mode").val('update');
        $("#num").val(num);
    }   
	
    $.ajax({
        type: "POST",
        url: "fetch_modal.php",
        data: { mode: mode, num: num },
        dataType: "html",
        success: function(response) {
            document.querySelector(".modal-body .custom-card").innerHTML = response;
            $("#myModal").show();

            $("#closeBtn").off("click").on("click", function() {
                $("#myModal").hide();
            });

            // 기존 이벤트 제거 후 재등록
            $(document).off('click', '.specialbtnClear').on('click', '.specialbtnClear', function(e) {
                e.preventDefault(); // 기본 동작을 방지합니다.                
                $('#item_name').val('');                
            });

            let isSaving = false;

            // 저장 버튼 (기존 이벤트 제거 후 재등록)
            $("#saveBtn").off("click").on("click", function() {
                if (isSaving) return;
                isSaving = true;

                var header = $("#header").val();
                var formData = $("#board_form").serialize();                

                $.ajax({
                    url: "process.php",
                    type: "post",
                    data: formData,
                    success: function(response) {
						
						console.log('response',response);
                        Toastify({
                            text: "저장완료",
                            duration: 3000,
                            close: true,
                            gravity: "top",
                            position: "center",
                            backgroundColor: "#4fbe87",
                        }).showToast();

                        setTimeout(function() {
                            $("#myModal").hide();
                            location.reload();
                        }, 2000);
                    },
                    error: function(jqxhr, status, error) {
                        console.log(jqxhr, status, error);
                        isSaving = false;
                    }
                });
            });		

	  },
        error: function(jqxhr, status, error) {
            console.log("AJAX Error: ", status, error);
        }
    });
}


</script>

<!-- 데이터 테이블 및 기타 기능을 위한 스크립트 -->
<script>
var ajaxRequest_write = null;
var dataTable; // DataTables 인스턴스 전역 변수
var material_regpageNumber; // 현재 페이지 번호 저장을 위한 전역 변수

$(document).ready(function() {            
    // DataTables 초기 설정
    dataTable = $('#myTable').DataTable({
        "paging": true,
        "ordering": true,
        "searching": true,
        "pageLength": 200,
        "lengthMenu": [ 100, 200, 500, 1000],
        "language": {
            "lengthMenu": "Show _MENU_ entries",
            "search": "Live Search:"
        },
        "order": [[1, 'desc']],
        "dom": 't<"bottom"ip>' // search 창과 lengthMenu 숨기기		
    });

    // 페이지 번호 복원 (초기 로드 시)
    var savedPageNumber = getCookie('material_regpageNumber');
    if (savedPageNumber) {
        dataTable.page(parseInt(savedPageNumber) - 1).draw(false);
    }

    // 페이지 변경 이벤트 리스너
    dataTable.on('page.dt', function() {
        var material_regpageNumber = dataTable.page.info().page + 1;
        setCookie('material_regpageNumber', material_regpageNumber, 10); // 쿠키에 페이지 번호 저장
    });

    // 페이지 길이 셀렉트 박스 변경 이벤트 처리
    $('#myTable_length select').on('change', function() {
        var selectedValue = $(this).val();
        dataTable.page.len(selectedValue).draw(); // 페이지 길이 변경 (DataTable 파괴 및 재초기화 없이)

        // 변경 후 현재 페이지 번호 복원
        savedPageNumber = getCookie('material_regpageNumber');
        if (savedPageNumber) {
            dataTable.page(parseInt(savedPageNumber) - 1).draw(false);
        }
    });

    $(document).on('click', '.specialbtnClear', function(e) {
        e.preventDefault(); // 기본 동작을 방지합니다.
        $(this).siblings('input').val('').focus();
    });
	
    $(document).on('click', '.btnClear_lot', function(e) {
        e.preventDefault(); // 기본 동작을 방지합니다.
        $(this).siblings('input').val('').focus();
    });
});

function restorePageNumber() {
    var savedPageNumber = getCookie('material_regpageNumber');
    location.reload(true);
}
</script>

<!-- 페이지로딩 및 Modal Script -->
<script>
$(document).ready(function(){    
    var loader = document.getElementById('loadingOverlay');
    loader.style.display = 'none';

    var modal = document.getElementById("myModal");
    var span = document.getElementsByClassName("close")[0];

    span.onclick = function() {
        modal.style.display = "none";
    }

    $(".close").on("click", function() {		
        $("#myModal").hide();
    });
	
    $("#newBtn").on("click", function() {		
        loadForm('insert');
    });

    $("#searchBtn").on("click", function() {
        $("#board_form").submit();
    });
	
    $("#closeBtn").on("click", function() {
         var modal = document.getElementById("myModal");
		 modal.style.display = "none";
    });
});

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

function phonebookBtn(searchfield)
{	    
    var search = $("#" + searchfield).val();				
    href = '../phonebook_buy/list.php?search=' + search ;				
	popupCenter(href, '매입처 검색', 1600, 800);
}

function inputNumberFormat(obj) {
    // 숫자 이외의 문자는 제거
    obj.value = obj.value.replace(/[^0-9]/g, '');
    
    // 콤마를 제거하고 숫자를 포맷팅
    let value = obj.value.replace(/,/g, '');
    obj.value = value.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

// Prevent form submission on Enter key
$(document).on("keypress", "input", function(event) {
	return event.keyCode != 13;
});		

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


</script>
