<?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 
$header = isset($_REQUEST['header']) ? $_REQUEST['header'] :  "";  
// 검색 조건 설정
$search = isset($_REQUEST['search']) ? $_REQUEST['search'] : '';
if($header !== 'header')
	require_once($_SERVER['DOCUMENT_ROOT'] . '/myheader.php'); 
?>   
<?php require_once($_SERVER['DOCUMENT_ROOT'] . '/mymodal.php'); ?>       	 
<?php

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

$fromdate = $_REQUEST['fromdate'] ?? '';
$todate = $_REQUEST['todate'] ?? '';
$seconditem = $_REQUEST['seconditem'] ?? '' ;
$model_name = $_REQUEST['model_name'] ?? '' ;
$major_category = $_REQUEST['major_category'] ?? '' ;
$mode = $_REQUEST['mode'] ?? '' ;
$search = $_REQUEST['search'] ?? '' ;

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

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

// fromdate 또는 todate가 없을 경우 기본값 설정 (과거 5개월 ~ 미래 3개월)
if (empty($fromdate) || empty($todate)) {
    $fromdate = date("Y-m-d", strtotime("-10 months", strtotime($currentDate)));
    $todate = date("Y-m-d", strtotime("+1 months", strtotime($currentDate)));
}

$SettingDate = "indate";
$tablename = "estimate";
$order_by = "ORDER BY num DESC";

// 기본 조건 (is_deleted가 NULL인 경우)
$conditions = ["is_deleted IS NULL"];
$bindParams = [];

// 날짜 범위 필터 추가
$conditions[] = "$SettingDate BETWEEN :fromdate AND :todate";
$bindParams[":fromdate"] = $fromdate;
$bindParams[":todate"] = $todate;

// model_name 필터 추가
if (!empty($model_name)) {
    $conditions[] = "model_name = :model_name";
    $bindParams[":model_name"] = $model_name;
}

// major_category 필터 추가 (대분류)
if (!empty($major_category)) {
    $conditions[] = "major_category = :major_category";
    $bindParams[":major_category"] = $major_category;
}

// seconditem 필터 추가 (중분류)
if (!empty($seconditem)) {
    $conditions[] = "seconditem = :seconditem";
    $bindParams[":seconditem"] = $seconditem;
}

// 테이블 컬럼 목록 가져오기
$searchConditions = [];
if (!empty($search)) {
    $columnQuery = $pdo->query("SHOW COLUMNS FROM {$DB}.{$tablename}");
    $columns = $columnQuery->fetchAll(PDO::FETCH_COLUMN);
    
    foreach ($columns as $column) {
        $searchConditions[] = "$column LIKE :search";
    }
    
    if (!empty($searchConditions)) {
        $conditions[] = "(" . implode(" OR ", $searchConditions) . ")";
        $bindParams[":search"] = "%{$search}%";
    }
}

// 최종 WHERE 조건 조립
$sqlWhere = implode(" AND ", $conditions);
$sql = "SELECT * FROM {$DB}.{$tablename} WHERE {$sqlWhere} {$order_by}";

// 실행 및 데이터 가져오기
try {
    $stmh = $pdo->prepare($sql);
    $stmh->execute($bindParams);
    $total_row = $stmh->rowCount();
 		
?>
<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-12"> 		
		<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>				 
<div class="row"> 			 
	<div class="col-sm-12">
	<div class="d-flex justify-content-center align-items-center"> 
		<div class="alert alert-primary p-2" role="alert">
			기존 견적데이터를 기반으로 단가변화에 따른 비교견적 산출!
		</div>		 
	</div>		 
		
	<div class="d-flex  p-1 m-1 mt-1 mb-1 justify-content-center align-items-center"> 
	▷   <?= $total_row ?> 건, &nbsp;접수일&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="mx-2">                
			<div class="btn-group" role="group" aria-label="대분류 선택">
				<input type="radio" class="btn-check" name="major_category" id="major_category_all" value="" <?= empty($major_category) ? 'checked' : '' ?>>
				<label class="btn btn-outline-secondary btn-sm" for="major_category_all">전체</label>
				
				<input type="radio" class="btn-check" name="major_category" id="major_category_screen" value="스크린" <?= ($major_category == '스크린') ? 'checked' : '' ?>>
				<label class="btn btn-outline-primary btn-sm" for="major_category_screen">스크린</label>
				
				<input type="radio" class="btn-check" name="major_category" id="major_category_steel" value="철재" <?= ($major_category == '철재') ? 'checked' : '' ?>>
				<label class="btn btn-outline-primary btn-sm" for="major_category_steel">철재</label>
			</div>
		</div>
		
		<!-- 제품모델(KSS01 등) 선택 -->
		<?php  selectModel('model_name', $model_name);  ?>
		
		<div class="inputWrap">
			<input type="text" id="search" name="search" value="<?=$search?>" onkeydown="JavaScript:SearchEnter();" autocomplete="off"  class="form-control text-start" 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 me-2" > <i class="bi bi-search"></i> 검색 </button> 		  
			<?php if($header!=='header') { ?>
			<button type="button" class="btn btn-dark  btn-sm me-1" id="writeBtn"> <i class="bi bi-pencil-fill"></i> 신규  </button> 	
			<?  }  ?>				 
			<?php if($header=='header') { ?>
				<button type="button" class="btn btn-outline-dark  btn-sm " onclick="self.close();" > <i class="bi bi-box-arrow-left"></i> 창닫기 </button>	&nbsp; 				
			<?  }  ?>				 
		 </div> 	 		 
		 </div> 	 		 
     </div> 	 		 
   </div> <!--card-body-->
   </div> <!--card -->   
  </div> <!--container -->   
<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:100px;">접수일</th>
			<th class="text-center" style="width:100px;">견적번호</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:150px;">발주처</th>
			<th class="text-center" style="width:80px;">담당자</th>
			<th class="text-center" style="width:120px;">연락처</th>
			<th class="text-center" style="width:200px;">현장명</th>					
			<th class="text-center" style="width:80px;">작성자</th>		
			<th class="text-center" style="width:300px;">비고</th>
		</tr>
		</thead>
	<?php  
      $start_num=$total_row;    // 페이지당 표시되는 첫번째 글순번          

      while($row = $stmh->fetch(PDO::FETCH_ASSOC)) {
			include '_row.php';	
		        
        if($outdate!="") {
        $week = array("(일)" , "(월)"  , "(화)" , "(수)" , "(목)" , "(금)" ,"(토)") ;
        $outdate = $outdate . $week[ date('w',  strtotime($outdate)  ) ] ;
        }  
		
		 $contents  = '';
		 
		$shutterSurang = 0; // 셔터 수량 합계를 저장할 변수 초기화
		$shutterSurang_slat = 0; //  철재

		// JSON 데이터를 배열로 디코딩
		$estimateListData = json_decode($estimateList, true);
		$estimateSlatListData = json_decode($estimateSlatList, true);

		// $screen_prodcode = '';
		// $slat_prodcode = '';
		// // 반복문을 통해 col14 값을 누적
		// if (is_array($estimateListData)) {
			// foreach ($estimateListData as $item) {
				// $shutterSurang += isset($item['col14']) ? (int)$item['col14'] : 0;
				// if(intval(isset($item['col14']))>0)
					// $screen_prodcode = isset($item['col4']) ? $item['col4'] : '' ;
			// }
		// }	
		// // slat 반복문을 통해 col15 값을 누적 slat
		// if (is_array($estimateSlatListData)) {
			// foreach ($estimateSlatListData as $item) {
				// $shutterSurang_slat += isset($item['col15']) ? (int)$item['col15'] : 0;
				// if(intval(isset($item['col15']))>0)
					// $slat_prodcode = isset($item['col4']) ? $item['col4'] : '' ;
			// }
		// }	
		
		// $prodcode = $screen_prodcode . $slat_prodcode;
		 
      ?>
		<tr onclick="redirectToView('<?= $num ?>', '<?= $tablename ?>' , '<?= $major_category ?>' )">
			<td class="text-center"><?= $start_num ?></td>			
			<td class="text-center"> <?= $indate ?></td>
			<td class="text-center"> <?= $pjnum ?></td>
			<td class="text-center"> <?= $major_category ?></td>
			<td class="text-center"> <?= $model_name ?></td>
			<td class="text-center"> <?= $estimateSurang ?></td>
			<td class="text-end fw-bold">
				<?= is_numeric($estimateTotal) ? number_format($estimateTotal) : '' ?>
			</td>
			<td class="text-center"> <?= $secondord ?></td>
			<td class="text-center" ><?= $secondordman ?></td>
			<td class="text-start" ><?= $secondordmantel ?></td>
			<td class="text-start" ><?= $outworkplace ?></td>						
			<td class="text-center" ><?= $orderman ?></td>			
			<td class="text-start"><?= $comment ?></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';
});
</script>
<script> 
var dataTable; // DataTables 인스턴스 전역 변수
var estimatepageNumver; // 현재 페이지 번호 저장을 위한 전역 변수

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

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

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

        // 변경 후 현재 페이지 번호 복원
        savedPageNumber = getCookie('estimatepageNumver');
        if (savedPageNumber) {
            dataTable.page(parseInt(savedPageNumber) - 1).draw(false);
        }
    });
	
    // 대분류 라디오 버튼 변경 시 검색 실행
    $("input:radio[name=major_category]").change(function() {
        $("#board_form").submit();
    });
    
    // 검색 버튼 클릭 시 검색 실행
    $("#searchBtn").click(function() {
        $("#board_form").submit();
    });
    
    // 날짜 입력 필드 변경 시 검색 실행
    $("#fromdate, #todate").change(function() {
        $("#board_form").submit();
    });
    
    // 제품모델 선택 필드 변경 시 검색 실행
    $("#model_name").change(function() {
        $("#board_form").submit();
    });
	
    // // 검색 버튼 클릭 이벤트 처리 (form submit)
    // $('#board_form').on('submit', function(e) {
        // e.preventDefault();
      
    // });	
	
});

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

function reloadlist() {    
	location.reload(true);
}

function redirectToView(num, tablename, major_category) {
	let url = '/estimate/compare.php?num=' + num + '&tablename=' + tablename + '&major_category=' + major_category;
	customPopup(url, '비교견적 시뮬레이션', 1850, 900);
}

// 검색 입력 필드에서 Enter 키 입력 시 검색 실행
function SearchEnter() {
	if (event.keyCode == 13) {
		$("#board_form").submit();
	}
}

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