<?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 = '재고 관리대장'; 

// 품질담당자 및 관리자인 경우 권한 부여
$QCadmin = 0 ;
if($user_name=='이세희' || $user_name=='개발자' || $user_name=='함신옥'  || $user_name=='노완호' )
	$QCadmin = 1 ;

?>

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

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

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

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

$tablename = 'instock';

// 현재 날짜
$currentDate = date("Y-m-d");

// fromdate 또는 todate가 빈 문자열이거나 null인 경우 기본 날짜 설정
if ($fromdate === "" || $fromdate === null || $todate === "" || $todate === null) {
    $fromdate = "2024-01-01"; // 2024년 1월 1일부터
    $todate = $currentDate;  // 현재날짜까지
    $Transtodate = $todate;
} else {
    $Transtodate = $todate;  // 설정된 기간
}

$SettingDate = "inspection_date"; // 정렬 기준 날짜

$order = " ORDER BY prodcode ASC ";

// 재고 계산을 위한 SQL 쿼리
// 입고량과 사용량을 계산하여 재고를 구함
// 사용량 테이블이 없을 경우를 대비하여 입고량만으로 계산
// 품목코드별로 그룹핑하여 합계 계산
if(checkNull($search)) {
    $sql = "SELECT 
                i.prodcode,
                MAX(i.item_name) as item_name,
                MAX(i.specification) as specification,
                MAX(i.unit) as unit,
                MAX(i.material_no) as material_no,
                MAX(i.manufacturer) as manufacturer,
                MAX(i.remarks) as remarks,
                MAX(i.purchase_price_excl_vat) as purchase_price_excl_vat,
                MAX(i.weight_kg) as weight_kg,
                SUM(CASE WHEN i.is_deleted IS NULL THEN CAST(REPLACE(i.received_qty, ',', '') AS DECIMAL(10,2)) ELSE 0 END) as total_in,
                0 as total_out,
                SUM(CASE WHEN i.is_deleted IS NULL THEN CAST(REPLACE(i.received_qty, ',', '') AS DECIMAL(10,2)) ELSE 0 END) as current_stock
            FROM {$DB}.{$tablename} i
            WHERE i.inspection_date BETWEEN date('$fromdate') AND date('$Transtodate') 
            AND (i.searchtag LIKE '%$search%' OR i.prodcode LIKE '%$search%' OR i.item_name LIKE '%$search%')
            AND i.is_deleted IS NULL
            GROUP BY i.prodcode
            HAVING current_stock > 0
            " . $order;    
} else {
    $sql = "SELECT 
                i.prodcode,
                MAX(i.item_name) as item_name,
                MAX(i.specification) as specification,
                MAX(i.unit) as unit,
                MAX(i.material_no) as material_no,
                MAX(i.manufacturer) as manufacturer,
                MAX(i.remarks) as remarks,
                MAX(i.purchase_price_excl_vat) as purchase_price_excl_vat,
                MAX(i.weight_kg) as weight_kg,
                SUM(CASE WHEN i.is_deleted IS NULL THEN CAST(REPLACE(i.received_qty, ',', '') AS DECIMAL(10,2)) ELSE 0 END) as total_in,
                0 as total_out,
                SUM(CASE WHEN i.is_deleted IS NULL THEN CAST(REPLACE(i.received_qty, ',', '') AS DECIMAL(10,2)) ELSE 0 END) as current_stock
            FROM {$DB}.{$tablename} i
            WHERE i.inspection_date BETWEEN date('$fromdate') AND date('$Transtodate') 
            AND i.is_deleted IS NULL
            GROUP BY i.prodcode
            HAVING current_stock > 0
            " . $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?>">
    <input type="hidden" id="QCadmin" name="QCadmin" value="<?=$QCadmin?>">

<div class="container-fluid">
	<!-- Modal -->
	<div id="myModal" class="modal">
		<div class="modal-content"  style="width:1200px;">
			<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">        
		<div class="d-flex  p-1 m-1 mt-1 justify-content-center align-items-center "> 		
		   <h5>  <?=$title_message?>  </h5>  &nbsp;&nbsp;&nbsp;&nbsp;	
		   <button type="button" class="btn btn-dark btn-sm "  onclick='location.reload();' > <i class="bi bi-arrow-clockwise"></i> </button>
		</div>	      
		
<div class="d-flex  p-1 m-1 mt-2 mb-1 justify-content-center align-items-center "> 		
	<span class="text-secondary"> 품목코드별 재고 현황 (현재는 입고량 기준, 사용량 테이블 연동 시 자동 계산) </span>
</div>			
    </div>
    <div class="card-body">  
    <div class="container mt-2 mb-2">       
		<div class="row"> 			 
			<div class="d-flex  p-1 m-1 mt-1 mb-1 justify-content-center align-items-center"> 
			▷ <?= $total_row ?> &nbsp; 					
			<input type="date" id="fromdate" name="fromdate"   class="form-control"   style="width:100px;" value="<?=$fromdate?>" >  &nbsp;   ~ &nbsp;  
			<input type="date" id="todate" name="todate"  class="form-control me-1"   style="width:100px;" value="<?=$todate?>" >  &nbsp;    		
				<div class="inputWrap">
					<input type="text" id="search" name="search" value="<?=$search?>" onkeydown="JavaScript:SearchEnter();" autocomplete="off"  class="form-control text-start" style="width:200px;" placeholder="품목코드/품목명 검색" > &nbsp;			
					<button class="btnClear"></button>
				</div>				
				
				<div id="autocomplete-list">						
				</div>	
				  &nbsp;
				<button id="searchBtn" type="button" class="btn btn-dark  btn-sm" > <i class="bi bi-search"></i> 검색  </button> 	
			</div>        
		</div>        
    </div>                
    <div class="table-responsive">   
       <table class="table table-hover" id="myTable">         
            <thead class="table-primary">
                 <th class="text-center" style="width:50px;" >번호</th>
                 <th class="text-center" style="width:100px;" >품목코드</th>
                 <th class="text-center" style="width:200px;" >품목명</th>
                 <th class="text-center" style="width:200px;" >규격</th>
                 <th class="text-center" style="width:40px;" > 단위</th>
                 <th class="text-center" style="width:80px;" >입고량</th>
                 <th class="text-center" style="width:80px;" >사용량</th>
                 <th class="text-center" style="width:80px;" >재고</th>
			     <th class="text-center" style="width:120px;" >자재번호</th>
			     <th class="text-center" style="width:120px;" >제조사</th>
                 <th class="text-center" style="width:100px;" >비고</th>
				 <th class="text-center" style="width:90px;" >매입가 <br>(VAT별도)</th>
				 <th class="text-center" style="width:80px;" >중량(KG)</th>
            </thead>
            <tbody>                  
            <?php          
			$start_num = $total_row;                  
				while($row = $stmh->fetch(PDO::FETCH_ASSOC)) {
					$specification_clean = preg_replace('/\s+/', ' ', $row['specification']); // 연속된 공백을 하나의 공백으로 변경			
					$remarks_clean = preg_replace('/\s+/', ' ', $row['remarks']); // 연속된 공백을 하나의 공백으로 변경			
            ?>                     
			<tr data-prodcode="<?= htmlspecialchars($row['prodcode']) ?>" 
				data-itemname="<?= htmlspecialchars($row['item_name']) ?>" 
				data-specification="<?= htmlspecialchars($row['specification']) ?>" 
				data-remarks="<?= htmlspecialchars($row['remarks']) ?>"
				onclick="loadInOutHistory('<?= htmlspecialchars($row['prodcode']) ?>', '<?= htmlspecialchars($row['item_name']) ?>', '<?= htmlspecialchars($row['specification']) ?>', '<?= htmlspecialchars($row['remarks']) ?>');">
				<td class="text-center"><?= $start_num ?></td>
				<td class="text-start fw-bold text-primary"><?= $row['prodcode'] ?></td>
				<td class="text-start fw-bold "><?= $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-success">
					<?php if (is_numeric($row['total_in'])) : ?>
						<?= number_format($row['total_in']) ?>
					<?php else : ?>
						<?= htmlspecialchars($row['total_in']) ?>
					<?php endif; ?>
				</td>
				<td class="text-end fw-bold text-danger">
					<?php if (is_numeric($row['total_out'])) : ?>
						<?= number_format($row['total_out']) ?>
					<?php else : ?>
						<?= htmlspecialchars($row['total_out']) ?>
					<?php endif; ?>
				</td>
				<td class="text-end fw-bold text-primary">
					<?php if (is_numeric($row['current_stock'])) : ?>
						<?= number_format($row['current_stock']) ?>
					<?php else : ?>
						<?= htmlspecialchars($row['current_stock']) ?>
					<?php endif; ?>
				</td>
				<td class="text-start text-secondary"><?= $row['material_no'] ?></td>
				<td class="text-center"><?= $row['manufacturer'] ?></td>
				<td class="text-start"><?= $row['remarks'] ?></td>
				<td class="text-end">
					<?= is_numeric($row['purchase_price_excl_vat']) ? number_format($row['purchase_price_excl_vat']) : '' ?>
				</td>
				
				<?php
				$weight_kg = $row['weight_kg'];
				$weight_kg = str_replace(',', '', $weight_kg);

				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>

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

function loadInOutHistory(prodcode, itemname, spec, remarks) {
    $.ajax({
        type: "POST",
        url: "fetch_inout_history.php",
        data: { 
            prodcode: prodcode, 
            itemname: itemname, 
            spec: spec, 
            remarks: remarks,
            fromdate: $("#fromdate").val(),
            todate: $("#todate").val()
        },
        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', '.close').on('click', '.close', function() {
                $("#myModal").hide();
            });
            
            // ESC 키로 닫기
            $(document).on('keydown', function(e) {
                if (e.keyCode === 27) { // ESC key
                    $("#myModal").hide();
                }
            });


        },
        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": [ 50, 100, 200, 500, 1000],
        "language": {
            "lengthMenu": "Show _MENU_ entries",
            "search": "Live Search:"
        },
        "order": [[1, 'asc']],
        "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');
	if(loader) 
		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();
    });

    $("#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 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>

<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/instock/common/viewJS.php'; ?> <!--공통 JS -->

</body>
</html> 