<?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;
}
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include $_SERVER['DOCUMENT_ROOT'] . '/load_header.php'; 
$title_message = '철재스라트 작업일지';   
?>  
<title>  <?=$title_message?>  </title> 
</head>
<body> 

<?php require_once($_SERVER['DOCUMENT_ROOT'] . '/myheader.php'); ?>   
<?php require_once($_SERVER['DOCUMENT_ROOT'] . '/mymodal.php'); ?>       	 
<?php
$tablename = 'output'; 
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();  

// 검색 조건 설정
$search = isset($_REQUEST['search']) ? $_REQUEST['search'] : '';
$fromdate = isset($_REQUEST['fromdate']) ? $_REQUEST['fromdate'] : '';  
$todate = isset($_REQUEST['todate']) ? $_REQUEST['todate'] : '';  
$mode = isset($_REQUEST['mode']) ? $_REQUEST['mode'] : '';  
$SettingDate = isset($_REQUEST['SettingDate']) ? $_REQUEST['SettingDate'] :  " regist_day ";  

if (isset($_REQUEST["separate_date"])) {
    $separate_date = $_REQUEST["separate_date"];
} else {
    $separate_date = "";
}
require_once("../lib/mydb.php");
$pdo = db_connect();	

if ($separate_date == "") {
    $separate_date = "1";
}

if (isset($_REQUEST["status_option"])) {
    $existing_status = $_REQUEST["status_option"];
} else {
    $existing_status = '전체';
}

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

// fromdate 또는 todate가 빈 문자열이거나 null인 경우
if ($fromdate === "" || $fromdate === null || $todate === "" || $todate === null) {
    $fromdate = date("Y-m-d", strtotime("-1 weeks", strtotime($currentDate))); // 1주 전 날짜
    $todate = date("Y-m-d", strtotime("+3 months", strtotime($currentDate))); // 3개월 후 날짜
    $Transtodate = $todate;
} else {
    // fromdate와 todate가 모두 설정된 경우 (기존 로직 유지)
    $Transtodate = $todate;
}

if ($separate_date == "1") {
    $SettingDate = "outdate";
} else {
    $SettingDate = "indate";
}

// 진행상태에 대한 검색
$orderby = " ORDER BY " . $SettingDate . " DESC, num DESC";    // 내림차순 정렬

if ($existing_status == '전체') {    
    $where = " WHERE " . $SettingDate . " BETWEEN date('$fromdate') AND date('$Transtodate') AND is_deleted = '0' AND recordslat IS NOT NULL AND recordslat != '' " . $orderby;
    $searchwhere = " WHERE is_deleted = '0' AND recordslat IS NOT NULL AND recordslat != '' AND searchtag LIKE '%$search%'" . $orderby;
} else {    
    $where = " WHERE " . $SettingDate . " BETWEEN date('$fromdate') AND date('$Transtodate') AND is_deleted = '0' AND regist_state = '$existing_status' AND recordslat IS NOT NULL AND recordslat != '' " . $orderby;
    $searchwhere = " WHERE is_deleted = '0' AND regist_state = '$existing_status' AND recordslat IS NOT NULL AND recordslat != '' AND searchtag LIKE '%$search%'" . $orderby;
}

// 수정된 쿼리: recordslat이 존재하고 is_deleted가 0인 자료만 선택
if ($search == "") {
    $sql = "SELECT * FROM $DB.$tablename " . $where;                         
} else { 
    $sql = "SELECT * FROM $DB.$tablename " . $searchwhere;
}

// 현재일자 변수지정
$today = date("Y-m-d");   

// SQL 실행 및 데이터 처리

try {   
$stmh = $pdo->query($sql);            // 검색조건에 맞는글 stmh
$total_row = $stmh->rowCount();
 
$total_sum=0;
$total_m2=0;			
$total_egi=0;
$total_egi_m2=0;			
?>
<form id="board_form"  name="board_form"  method="post">      
<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">  
	<div class="card mb-2 mt-2">  
	<div class="card-body">  	 
<div class="row"> 		
	<div class="col-sm-7"> 		
		<div class="d-flex  p-1 m-1 mt-1 justify-content-end 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="col-sm-5"> 		
		<div class="d-flex  justify-content-end align-items-center "> 				   
			  <h5> <span id="total_egi" class="text-primary me-2"></span> 
				   <span id="total_egi_m2" class="badge bg-primary me-5"></span>  
			  </h5>
		</div>				 
	</div>				 
</div>				 
<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;    
</span> 		
	<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> <!--card-body-->
   </div> <!--card -->   
</div> <!--container-fluid -->   
<div class="container-fluid">  
<div class="d-flex justify-content-center align-items-center"> 		
<table class="table table-hover" id="myTable">
  <thead class="table-primary">
    <tr>
		<th class="text-center" style="width:30px;">번호</th>
		<th class="text-center" style="width:120px;">출고일</th>
		<th class="text-center" style="width:100px;">접수일</th>
		<th class="text-center" style="width:50px;">완료여부 </th>		
		<th class="text-center" style="width:90px;">작성일</th>		
		<th class="text-center" style="width:100px;">발주처</th>
		<th class="text-center" style="width:200px;">현장명</th>
		<th class="text-center" style="width:100px;">수신자</th>
		<th class="text-center" style="width:50px;">담당</th>
		<th class="text-center" style="width:50px;">틀수</th>
		<th class="text-center" style="width:50px;">(㎡)</th>		
    </tr>
    </thead>
	<?php  
      $start_num=$total_row;    // 페이지당 표시되는 첫번째 글순번          

		$total_m2_formatted = 0 ;
		$total_egi_m2_formatted = 0 ;
		
		$total_egi_sum = 0;		
		$total_egi_m2 = 0;				
		

      while($row = $stmh->fetch(PDO::FETCH_ASSOC)) {
			include '_row.php';	
		
        // recordslat에서 작성일 및 작성자 추출
        $recordslatData = json_decode($row['recordslat'], true);
        $writerDate = isset($recordslatData[0]['approval']['writer']['date']) ? $recordslatData[0]['approval']['writer']['date'] : '';        
				
		$slat_su_cleaned = floatval(str_replace(',', '', $slat_su));
		$slat_m2_cleaned = floatval(str_replace(',', '', $slat_m2));

		$slatlists = json_decode($slatlist, true);
		// var_dump($slatlists["screen_m2"]);
	  					

        $date_font="text-dark";  // 현재일자 Red 색상으로 표기
        if($today==$outdate) {
        $date_font="text-danger";
        }
    
        if($outdate!="") {
        $week = array("(일)" , "(월)"  , "(화)" , "(수)" , "(목)" , "(금)" ,"(토)") ;
        $outdate = $outdate . $week[ date('w',  strtotime($outdate)  ) ] ;
        }  
      ?>
	  <tr onclick="redirectToView('<?= $num ?>', '<?= $tablename ?>')">
        <td class="text-center"><?= $start_num ?></td>
        <td class="text-center"><?= $outdate ?></td>
        <td class="text-center"><?= $indate ?></td>
		<td class="text-center">
			<?php
			// recordslat에서 각 로트의 상태를 검사
			$recordslatData = json_decode($row['recordslat'], true);

			// 기본값 설정
			$state = '등록전';
			$allCompleted = true; // 모든 LOT 번호가 입력되었는지 확인
			$hasInProgress = false; // 하나라도 입력된 상태가 있는지 확인

			// recordslat 데이터가 유효할 경우 상태 확인
			if (is_array($recordslatData)) {
				// LOT 번호 배열이 있는지 확인
				$lotNumbers = isset($recordslatData[2]['lotNumbers']) ? $recordslatData[2]['lotNumbers'] : [];
				$wireLotNumbers = isset($recordslatData[3]['wireLotNumbers']) ? $recordslatData[3]['wireLotNumbers'] : [];

				// 모든 LOT 번호가 입력되었는지 확인
				foreach ($lotNumbers as $lot) {
					if (trim($lot) === '') {
						$allCompleted = false;
					} else {
						$hasInProgress = true;
					}
				}

				// 모든 내화실 LOT 번호가 입력되었는지 확인
				foreach ($wireLotNumbers as $lot) {
					if (trim($lot) === '') {
						$allCompleted = false;
					} else {
						$hasInProgress = true;
					}
				}

				// 모든 LOT 번호가 입력된 경우 '완료'
				if ($allCompleted && $hasInProgress) {
					$state = '완료';
				}
				// 일부는 입력되었지만 모두 완료되지 않은 경우 '진행중'
				elseif ($hasInProgress) {
					$state = '진행중';
				}
			}

			// 상태에 따라 출력
			switch ($state) {
				case "등록전":
					echo '<span class="badge bg-danger">등록전</span>';
					break;
				case "진행중":
					echo '<span class="badge bg-warning blink">진행중</span>';
					break;
				case "완료":
					echo '<span class="badge bg-dark">완료</span>';
					break;
			}
			?>                          
		</td>

        <td class="text-center"><?= htmlspecialchars($writerDate) ?></td>
        <td class="text-center"><?= $secondord ?></td>
        <td class="text-start"><?= $outworkplace ?></td>
        <td class="text-start"><?= $receiver ?></td>
        <td class="text-center"><?= $orderman ?></td>
        <?php        

            $row_sum_formatted = number_format($slat_su_cleaned);            
            $row_m2_formatted = number_format($slat_m2_cleaned, 1);            
                          
            if ($row_sum_formatted > 0) {
                echo '<td class="text-end">' . $row_sum_formatted . '</td>';
            } else {
                echo '<td class="text-end">&nbsp;</td>'; 
            }

            if ($row_m2_formatted > 0) {
                echo '<td class="text-end">' . $row_m2_formatted . '</td>';
            } else {
                echo '<td class="text-end">&nbsp;</td>';
            }
            
            $total_egi += $slat_su_cleaned;
            $total_egi_m2 += $slat_m2_cleaned;
        
            // 소수점 첫째 자리까지만 포맷팅            
            $total_egi_m2_formatted = number_format($total_egi_m2, 1);
        ?>
    </tr>
  <?php
        $start_num--;  
    } 
  } catch (PDOException $Exception) {
      print "오류: " . $Exception->getMessage();
  }           
  ?>
  </tbody>
</table>
    </div>
</div> <!--container-->
	
</form>
<script>
// 페이지 로딩
$(document).ready(function(){	
    var loader = document.getElementById('loadingOverlay');
	if(loader)
		loader.style.display = 'none';
});
</script>

<script> 
var dataTable; // DataTables 인스턴스 전역 변수
var outputpageNumber; // 현재 페이지 번호 저장을 위한 전역 변수

$(document).ready(function() {			
    // DataTables 초기 설정
    dataTable = $('#myTable').DataTable({
        "paging": true,
        "ordering": true,
        "searching": false,
        "pageLength": 100,
        "lengthMenu": [100, 200, 500, 1000],
        "language": {
            "lengthMenu": "Show _MENU_ entries"
        },
        "order": [[1, 'desc']] // 출고예정기준 내림정렬
    });

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

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

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

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

function restorePageNumber() {
    var savedPageNumber = getCookie('outputpageNumber');
    // if (savedPageNumber) {
        // dataTable.page(parseInt(savedPageNumber) - 1).draw('page');
    // }
	location.reload(true);
}

function redirectToView(num, tablename) {	
    var url = "viewSlatWork.php?num=" + num + "&tablename=" + tablename;          
	 customPopup(url, '철재스라트 작업일지', 800, 900); 	    
}

function submitForm(status) {
    $('input[name=status_option]').val(status);
    document.getElementById('board_form').submit();
}
 
$(document).ready(function(){	    
	document.getElementById('total_egi').textContent = '철재스라트 : <?= $total_egi ?>';
	document.getElementById('total_egi_m2').textContent = '면적 : <?= $total_egi_m2_formatted ?> ㎡';	
}); 

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