<?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"] : '';
$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 = date("Y-m-d", strtotime("-32 weeks", strtotime($currentDate))); // 16주 전
    $todate = date("Y-m-d", strtotime("+3 months", strtotime($currentDate)));  // 3개월 후
    $Transtodate = $todate;
} else {
    $Transtodate = $todate;  // 설정된 기간
}

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

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  inspection_date BETWEEN date('$fromdate') AND date('$Transtodate') AND  searchtag LIKE '%$search%' AND is_deleted IS NULL " . $order;    
} else {
    $sql = "SELECT * FROM ".$DB.".".$tablename . " WHERE inspection_date BETWEEN date('$fromdate') AND date('$Transtodate') AND 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">        
		<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>
    <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; 		
			<button type="button" id="premonth" class="btn btn-dark btn-sm me-1   "  onclick='yesterday()' > 전일 </button> 						
			<button type="button" class="btn btn-outline-dark btn-sm me-1   "  onclick='this_today()' > 금일 </button>
			<button type="button" class="btn btn-dark btn-sm me-1   "  onclick='this_tomorrow()' > 익일  </button>	  						   			
			<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" style="width:150px;" > &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:60px;" >번호</th>
                 <th class="text-center" style="width:120px;" >로트번호</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: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';               
				$specification_clean = preg_replace('/\s+/', ' ', $specification); // 연속된 공백을 하나의 공백으로 변경			
				$remarks_clean = preg_replace('/\s+/', ' ', $remarks); // 연속된 공백을 하나의 공백으로 변경			

				// JSON을 배열로 디코딩
				$iListArray = json_decode($iList, true);

				// resultJudgement 값을 찾기 위한 루프
				$resultJudgement = null;

				foreach ($iListArray as $item) {
					// 배열에서 inputItems를 가진 항목이 있는지 확인
					if (isset($item['inputItems']['resultJudgement'])) {
						$resultJudgement = $item['inputItems']['resultJudgement'];
						break; // 값을 찾으면 루프 종료
					}
				}

				
            ?>                     
            <tr onclick="viewBoardInstock( '<?= addslashes($num) ?>', '<?= addslashes($item_name) ?>', '<?= addslashes($specification_clean) ?>', '<?= addslashes($remarks_clean) ?>');" data-num="<?=$num?>">
                <td class="text-center"><?= $start_num ?></td>
                <td class="text-center fw-bold text-success "><?= $row['lot_no'] ?></td>
				<?php
					// resultJudgement 값이 "합격"이면 text-dark, 아니면 text-danger로 설정
					$class = ($resultJudgement === '합격') ? 'text-dark' : 'text-danger';
				?>
				<td class="text-center fw-bold resultJudgement <?= $class ?>"><?= $resultJudgement ?></td>
                <td class="text-center "><?= $row['lotDone'] ?></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"><?= $specification_clean ?></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-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);

				// 결과값이 숫자 형태인지 확인하고, 숫자일 경우 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>

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

var selectedRow;

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() {		
        viewBoardInstock('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(){    
   // 방문기록 남김
   var title_message = '<?php echo $title_message ; ?>';
   saveMenuLog(title_message);
});


// 팝업 창 닫기 시 데이터를 전달하고 열 갱신
function closePopupAndUpdateRow(updatedData) {
    if (selectedRow) {
        // selectedRow.find('.text-center.text-primary').eq(0).text(updatedData.rawLot);
        // selectedRow.find('.text-center.text-primary').eq(1).text(updatedData.fabric_lot);
        // selectedRow.find('.fw-bold.text-success').text(updatedData.lot_number);
        selectedRow.find('.resultJudgement').text(updatedData.resultJudgement);

        // // 추가적으로 다른 필드도 업데이트 필요 시 설정
        // selectedRow.find('.text-center').eq(1).text(updatedData.reg_date);
        // selectedRow.find('.text-center').eq(6).text(updatedData.prodDisplay);
        // selectedRow.find('.text-center').eq(7).text(updatedData.specDisplay);
        // selectedRow.find('.text-center').eq(8).text(updatedData.slengthDisplay);
        // selectedRow.find('.text-center').eq(9).text(updatedData.surang);
        // selectedRow.find('.text-center').eq(10).text(updatedData.author);
        // selectedRow.find('.text-start').eq(0).text(updatedData.remark);
    }
}
	
</script>
<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/instock/common/viewJS.php'; ?> <!--공통 JS -->
</body>
</html>
