<?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> 
<style>
	/* 테이블의 총 너비를 강제로 키움 */
	#myTable table {
		min-width: 3000px; /* 부모 요소보다 큰 너비 설정 */
	}
</style>
</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) {
		$year = date("Y");
		$month = date("n");

		// 현재 월을 기준으로 분기 계산
		if ($month >= 1 && $month <= 3) {
			$quarter = 1;
			$fromdate = "$year-01-01";
			$todate = "$year-03-31";
		} elseif ($month >= 4 && $month <= 6) {
			$quarter = 2;
			$fromdate = "$year-04-01";
			$todate = "$year-06-30";
		} elseif ($month >= 7 && $month <= 9) {
			$quarter = 3;
			$fromdate = "$year-07-01";
			$todate = "$year-09-30";
		} else {
			$quarter = 4;
			$fromdate = "$year-10-01";
			$todate = "$year-12-31";
		}
    $Transtodate = $todate;
} else {
    // fromdate와 todate가 모두 설정된 경우 (기존 로직 유지)
    $Transtodate = $todate;
}

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

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

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

// 수정된 쿼리: ACIdoneDate이 존재하고 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-1 mt-1 p-1">  
	<div class="card-body">  	 
	<div class="row"> 		
		<div class="col-sm-12"> 		
			<div class="d-flex  p-1 mb-2 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>			
		<div class="d-flex justify-content-center"> 		
			<table class="table table-bordered text-center align-middle w-50">
				<tbody>
					<tr>
						<th class="text-center">상호(법인명)</th>
						<td>㈜경동기업</td>
					</tr>
					<tr>
						<th class="text-center">법인등록번호</th>
						<td>124411-0174300</td>
					</tr>
					<tr>
						<th class="text-center">사업자등록번호</th>
						<td>139-87-00333</td>
					</tr>
					<tr>
						<th class="text-center">제조현장(공장) 소재지</th>
						<td>김포시 통진읍 옹정로 45-22</td>
					</tr>
					<tr>
						<th class="text-center">전화번호</th>
						<td>031-983-5130</td>
					</tr>
				</tbody>
			</table>
		</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" class="btn btn-outline-secondary btn-sm me-1" onclick="setLastYearQuarter(1)">작년 1분기</button>
        <button type="button" class="btn btn-outline-secondary btn-sm me-1" onclick="setLastYearQuarter(2)">작년 2분기</button>
        <button type="button" class="btn btn-outline-secondary btn-sm me-1" onclick="setLastYearQuarter(3)">작년 3분기</button>
        <button type="button" class="btn btn-outline-secondary btn-sm me-1" onclick="setLastYearQuarter(4)">작년 4분기</button>
        <!-- 올해 분기 버튼 -->
        <button type="button" class="btn btn-outline-dark btn-sm me-1" onclick="setQuarter(1)">1분기</button>
        <button type="button" class="btn btn-outline-dark btn-sm me-1" onclick="setQuarter(2)">2분기</button>
        <button type="button" class="btn btn-outline-dark btn-sm me-1" onclick="setQuarter(3)">3분기</button>
        <button type="button" class="btn btn-outline-dark btn-sm me-1" onclick="setQuarter(4)">4분기</button>

        <!-- 반기 버튼 -->
        <button type="button" class="btn btn-dark btn-sm me-1" onclick="setHalfYear(1)">상반기</button>
        <button type="button" class="btn btn-dark btn-sm me-1" onclick="setHalfYear(2)">하반기</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 mx-1" style="width:150px;height:30px;" > &nbsp;			
			<button class="btnClear"></button>		</div>
        <button id="searchBtn" type="button" class="btn btn-dark btn-sm"> <i class="bi bi-search"></i> 검색 </button>
    </div>
</div>


</div>				
</div>				
</div>				
 
<div class="container-fluid">
	<div class="table-responsive"> 	
		<div class="row justify-content-center align-items-center">
            <table class="table table-hover" id="myTable">
                <thead class="table-primary">
                    <tr>
                        <th class="text-center">일련번호</th>
                        <th class="text-center">품질관리서번호</th>
                        <th class="text-center">작성일자</th>
                        <th class="text-center">인정품목</th>
                        <th class="text-center">품질인정번호</th>
                        <th class="text-center">내화성능시간</th>
                        <th class="text-center">상품명</th>
                        <th class="text-center">구조 또는 제품명</th>
                        <th class="text-center">사용부위</th>
                        <th class="text-center">로트번호</th>
                        <th class="text-center">규격</th>
                        <th class="text-center">수량</th>
                        <th class="text-center">현장명</th>
                        <th class="text-center">대지위치</th>
                        <th class="text-center">지번</th>
                        <th class="text-center">성명</th>
                        <th class="text-center">사무소명</th>
                        <th class="text-center">사무소주소</th>
                        <th class="text-center">사무소전화번호</th>
                        <th class="text-center">성명</th>
                        <th class="text-center">회사명</th>
                        <th class="text-center">회사주소</th>
                        <th class="text-center">회사전화번호</th>
                        <th class="text-center">성명</th>
                        <th class="text-center">회사명</th>
                        <th class="text-center">회사주소</th>
                        <th class="text-center">회사전화번호</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 데이터를 배열로 디코딩
		$eList_screenData = json_decode($eList_screen, true);
		$eList_slatData = json_decode($eList_slat, true);
		
		// echo '<pre>';
		// print_r($eList_screen);
		// echo '</pre>';			
		// echo '<pre>';
		// print_r($eList_slat);
		// echo '</pre>';		
		
		// 반복문을 통해 col14 값을 누적
		if (is_array($eList_screenData)) {
			foreach ($eList_screenData as $item) {
				$shutterSurang += isset($item['col14']) ? (int)$item['col14'] : 0;
			}
		}	
		// slat 반복문을 통해 col15 값을 누적 slat
		if (is_array($eList_slatData)) {
			foreach ($eList_slatData as $item) {
				$shutterSurang_slat += isset($item['col15']) ? (int)$item['col15'] : 0;
			}
		}		
		// 스크린,철재스라트 구분하기 JSON 데이터가 비어있는지 확인하여 값 설정
		if (!empty(json_decode($eList_screen, true))) {
			$separate_item = '스크린';
		} elseif (!empty(json_decode($eList_slat, true))) {
			$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"><?= $outworkplace ?></td>       
		<td class="text-start"><?= $outworkplace ?></td>       
		<td class="text-start"><?= $outworkplace ?></td>       
		<td class="text-start"><?= $outworkplace ?></td>       
		<td class="text-start"><?= $outworkplace ?></td>       
		<td class="text-start"><?= $outworkplace ?></td>       
		<td class="text-start"><?= $outworkplace ?></td>       
		<td class="text-start"><?= $outworkplace ?></td>       
		<td class="text-start"><?= $outworkplace ?></td>       
		<td class="text-start"><?= $outworkplace ?></td>       
		<td class="text-start"><?= $outworkplace ?></td>       
		<td class="text-start"><?= $outworkplace ?></td>       
		<td class="text-start"><?= $ACImemo ?></td>    
		<td class="text-start"><?= $ACImemo ?></td>    
		<td class="text-start"><?= $ACImemo ?></td>    
		<td class="text-start"><?= $ACImemo ?></td>    
		<td class="text-start"><?= $ACImemo ?></td>    
		<td class="text-start"><?= $ACImemo ?></td>    
	</tr>
		<?php
				$start_num--;  
			} 
			} catch (PDOException $Exception) {
			  print "오류: " . $Exception->getMessage();
			}           
		?>
		  </tbody>
		</table>
    </div>
    </div>
</div> <!--container-->
	
</form>

<script>
// 페이지 로딩
$(document).ready(function(){	
    var loader = document.getElementById('loadingOverlay');
	if(loader)
		loader.style.display = 'none';
});

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

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

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

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

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

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

function restorePageNumber() {
    var savedPageNumber = getCookie('QClistpageNumber');
    // 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 = "view_requestACI.php?num=" + num + "&tablename=" + tablename;
    } else {
        url = "view_requestACI.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>