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

if($header ==='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 = 'instock';

require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();

$order = " ORDER BY inspection_date DESC, lot_no asc ";

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"  style="width:850px;">
			<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 ($header == 'header') {
    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($level=='1') { ?>
		<!-- <button id="uploadBtn" type="button" class="btn btn-dark btn-sm me-2"> <i class="bi bi-box-arrow-up"></i> 업로드 </button>	 -->
	<?php } ?>    
    </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:150px;" >로트번호</th>
                 <th class="text-center" style="width:80px;" >검사일</th>
                 <th class="text-center" style="width:80px;" >납품업체</th>                 
                 <th class="text-center" style="width:200px;" >품목명</th>
                 <th class="text-center" style="width:200px;" >규격</th>
                 <th class="text-center" style="width:50px;" > 단위</th>
                 <th class="text-center" style="width:60px;" >입고량</th>
			     <th class="text-center" style="width:150px;" >자재번호</th>
			     <th class="text-center" style="width:150px;" >제조사</th>
                 <th class="text-center" style="width:100px;" >비고</th>
				 <th class="text-center" style="width:100px;" >매입가 <br>(VAT별도)</th>
				 <th class="text-center" style="width:100px;" >중량(KG)</th>
            </thead>
            <tbody>                  
            <?php          
            $start_num = $total_row;                  
            while($row = $stmh->fetch(PDO::FETCH_ASSOC)) {
                include '_row.php';                                        
            ?>                     
            <tr onclick="loadForm('update', '<?=$row['num']?>');">
                <td class="text-center"><?= $start_num ?></td>
                <td class="text-center fw-bold text-success"><?= $row['lot_no'] ?></td>
                <td class="text-center"><?= $row['inspection_date'] ?></td>
                <td class="text-center"><?= $row['supplier'] ?></td>                
                <td class="text-start fw-bold text-primary"><?= $row['item_name'] ?></td>
                <td class="text-start text-secondary"><?= $row['specification'] ?></td>
                <td class="text-center fw-bold text-secondary"><?= $row['unit'] ?></td>
                <td class="text-end fw-bold text-primary">
					<?php if (is_numeric($row['received_qty'])) : ?>
						<?= number_format($row['received_qty']) ?>
					<?php else : ?>
						<?= htmlspecialchars($row['received_qty']) ?>
					<?php endif; ?>
				</td>
                <td class="text-start fw-bold text-secondary"><?= $row['material_no'] ?></td>				
                <td class="text-center"><?= $row['manufacturer'] ?></td>                

                <td class="text-start"><?= $row['remarks'] ?></td>
				<td class="text-center"><?= $row['purchase_price_excl_vat'] ?></td>
				<?php
				$weight_kg = $row['weight_kg'];
				$weight_kg = str_replace(',', '', $weight_kg);

				// 결과값이 숫자 형태인지 확인하고, 숫자일 경우 number_format 적용
				if (is_numeric($weight_kg) && $weight_kg != '' && $weight_kg != '0') {
					$weight_kg = number_format((float)$weight_kg);
				}
				?>

				<td class="text-end"><?= $weight_kg ?></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 = [];
var lotnumData = [];

function loadForm(mode, num = null) {
    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").on("click", function() {
                $("#myModal").hide();
            });


            $(document).on('click', '.specialbtnClear', function(e) {
                e.preventDefault();
                $(this).siblings('input').val('').focus();
                $('#item_name').val('');
                $('#material_no').val('');                
            });

            $(document).on('click', '.btnClear_lot', function(e) {
                e.preventDefault();
                $(this).siblings('input').val('').focus();                
                $('#lot_no').val('');
            });

            $(document).on('input', '.inputcode ', function() {
                initializeAutocomplete(this);
            });     
			
            $(document).on('input', '.inputitemname ', function() {
                initializeAutocomplete(this);
            });       
			
            $(document).on('input', '.inputlot ', function() {
                initializeAutocomplete(this);
            });       
			
            let isSaving = false;
            
            $("#saveBtn").on("click", function() {
                if (isSaving) return;
                isSaving = true;

                var header = $("#header").val();
                var formData = $("#board_form").serialize();
                let continuousRegistration = $("#continuous_registration").is(':checked');

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

                        if (!continuousRegistration) {
                            $("#myModal").hide();
                            location.reload();
                        } else {
                            $("#mode").val('insert');
                            $("#num").val('');							
							
                            isSaving = false;
                        }
                    },
                    error: function(jqxhr, status, error) {
                        console.log(jqxhr, status, error);
                        isSaving = false;
                    }
                });
            });

            $("#deleteBtn").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);
        }
    });
}
</script>

<script>
var ajaxRequest_write = null;
var dataTable; 
var material_regpageNumber;

$(document).ready(function() {            
    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>' 
    });

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

        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>

<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";
    });

	// upload
	$("#uploadBtn").on("click", function() {	
		  popupCenter('uploadgrid.php' , '업로드', 1800, 800);	
	});		
  	
	
});

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

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, ',');
}

$(document).on("keypress", "input", function(event) {
	return event.keyCode != 13;
});		

$(document).ready(function(){    
   // 방문기록 남김
   saveMenuLog('수입검사 관리대장');
});

</script>
