<?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 CAST(" . $SettingDate . " AS CHAR) NOT IN ('', '0000-00-00') AND " . $SettingDate . " BETWEEN '$fromdate' AND '$Transtodate' AND is_deleted = '0' AND ACIregDate IS NOT NULL AND CAST(ACIregDate AS CHAR) NOT IN ('', '0000-00-00') " . $orderby;
    $searchwhere = " WHERE is_deleted = '0' AND ACIregDate IS NOT NULL AND CAST(ACIregDate AS CHAR) NOT IN ('', '0000-00-00') AND searchtag LIKE '%$search%'" . $orderby;
} else {
    $where = " WHERE CAST(" . $SettingDate . " AS CHAR) NOT IN ('', '0000-00-00') AND " . $SettingDate . " BETWEEN '$fromdate' AND '$Transtodate' AND is_deleted = '0' AND regist_state = '$existing_status' AND ACIregDate IS NOT NULL AND CAST(ACIregDate AS CHAR) NOT IN ('', '0000-00-00') " . $orderby;
    $searchwhere = " WHERE is_deleted = '0' AND regist_state = '$existing_status' AND ACIregDate IS NOT NULL AND CAST(ACIregDate AS CHAR) NOT IN ('', '0000-00-00') AND searchtag LIKE '%$search%'" . $orderby;
}

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

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

// SQL 실행 및 데이터 처리
print 'SQL ' . $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_screen" class="text-primary me-2"></span> 
				   <span id="total_screen_m2" class="badge bg-primary me-5"></span> 
				  <span id="total_egi" class="text-secondary me-2"></span> 
				  <span id="total_egi_m2" class="badge bg-secondary me-2"></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:50px;">번호</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:100px;">발주처</th>
	<th class="text-center" style="width:100px;">제품종류 </th>
	<th class="text-center" style="width:80px;">제품코드</th>
	<th class="text-center" style="width:50px;">수량(틀)</th>				
	<th class="text-center" style="width:250px;">현장명</th>				
	<th class="text-center" style="width:200px;">메모</th>				
</tr>
</thead>
<?php  
      $start_num=$total_row;    // 페이지당 표시되는 첫번째 글순번          
	
      while($row = $stmh->fetch(PDO::FETCH_ASSOC)) {
		include '_row.php';					        
    
        if($ACIregDate!="") {
			$week = array("(일)" , "(월)"  , "(화)" , "(수)" , "(목)" , "(금)" ,"(토)") ;
			$ACIregDate = $ACIregDate . $week[ date('w',  strtotime($ACIregDate)  ) ] ;
        }  		
		 
		$shutterSurang = 0; // 셔터 수량 합계를 저장할 변수 초기화
		$shutterSurang_slat = 0; //  철재

		// JSON 데이터를 배열로 디코딩
		$estimateListData = json_decode($estimateList, true);
		$estimateSlatListData = json_decode($estimateSlatList, true);
		
		// echo '<pre>';
		// print_r($estimateList);
		// echo '</pre>';			
		// echo '<pre>';
		// print_r($estimateSlatList);
		// echo '</pre>';		
		
		// 반복문을 통해 col14 값을 누적
		if (is_array($estimateList)) {
			foreach ($estimateList as $item) {
				$shutterSurang += isset($item['col14']) ? (int)$item['col14'] : 0;
			}
		}	
		// slat 반복문을 통해 col15 값을 누적 slat
		if (is_array($estimateSlatList)) {
			foreach ($estimateSlatList as $item) {
				$shutterSurang_slat += isset($item['col15']) ? (int)$item['col15'] : 0;
			}
		}		
		// 스크린,철재스라트 구분하기 JSON 데이터가 비어있는지 확인하여 값 설정
		$separate_item = '';
		// 스크린,철재스라트 구분하기 JSON 데이터가 비어있는지 확인하여 값 설정
		if (!empty(json_decode($estimateList, true))) {
			$separate_item = '스크린';
		} elseif (!empty(json_decode($estimateSlatList, true))) {
			$separate_item = '철재스라트';
		}		
		if(!empty($separate_item))
		{
      ?>
	<tr onclick="redirectToView('<?= $num ?>', '<?= $tablename ?>', '<?= $prodCode ?>')">
		<td class="text-center"><?= $start_num ?></td>
		<td class="text-center"><?= $ACIregDate ?></td>
		<td class="text-center"><?= $ACIaskDate === '0000-00-00' ? '' : $ACIaskDate ?></td>
		<td class="text-center"><?= $ACIdoneDate === '0000-00-00' ? '' : $ACIdoneDate ?></td>
		<td class="text-center"><?= $secondord ?></td>
		<td class="text-center<?= $separate_item === '철재스라트' ? ' text-primary' : '' ?>">
			<?= $separate_item ?>
		</td>
        <td class="text-center"><?= $prodCode ?></td>
		<td class="text-center"> <?= ($shutterSurang + $shutterSurang_slat) ?></td>
		<td class="text-start"><?= $outworkplace ?></td>       
		<td class="text-start"><?= $ACImemo ?></td>    
	</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';
});

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

$(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('ACIpageNumber');
    if (savedPageNumber) {
        dataTable.page(parseInt(savedPageNumber) - 1).draw(false);
    }

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

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

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

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

function redirectToView(num, tablename, prodcode) {
    let prodName, arrayWidth, arrayHeight, url; 

    // prodcode에 따라 URL 설정
    if (prodcode.startsWith('KS') || prodcode.startsWith('KW')) {
        url = "write_ACI.php?num=" + num + "&tablename=" + tablename;
    } else {
        url = "write_ACI_slat.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(){    
   // 방문기록 남김
   var title = '<?php echo $title_message; ?>';
   saveMenuLog(title);
});
 
</script>
</body>
</html>