<?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 = '인수인계 보고서 목록';   
?>  
<title><?=$title_message?></title>
</head>
<body>
<?php require_once($_SERVER['DOCUMENT_ROOT'] . '/myheader1.php'); ?>   
<?php require_once($_SERVER['DOCUMENT_ROOT'] . '/mymodal.php'); ?>

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

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

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

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

$statusStr = '';

$common= "h." . trim($SettingDate) . " between '$fromdate' and '$Transtodate' and h.is_deleted = 'N' " . $statusStr ;		

// SQL 쿼리 작성
$orderby = " order by h.num desc ";

$andPhrase= " and " . $common  . $orderby ;
$wherePhrase= " where " . $common  . $orderby ;

$sql = "SELECT h.*, w.subject as work_subject, w.workplacename as work_workplacename FROM $DB.$tablename h LEFT JOIN $DB.work w ON h.parentnum = w.num " . $wherePhrase; 	

if (!empty($search)) {
    $sql = "SELECT h.*, w.subject as work_subject, w.workplacename as work_workplacename FROM $DB.$tablename h LEFT JOIN $DB.work w ON h.parentnum = w.num where (h.workplacename LIKE '%$search%' OR h.firstord LIKE '%$search%' OR h.secondord LIKE '%$search%' OR h.regist_user LIKE '%$search%') and h.is_deleted = 'N' "  . $andPhrase ;	
}

if ($find!=='all' && $search) {
    $sql = "SELECT h.*, w.subject as work_subject, w.workplacename as work_workplacename FROM $DB.$tablename h LEFT JOIN $DB.work w ON h.parentnum = w.num WHERE h.$find LIKE '%$search%' and h.is_deleted = 'N' "  . $andPhrase ;	
}

try {
		$stmh = $pdo->query($sql);
		$total_row = $stmh->rowCount(); // 총 행 수 계산
} catch (PDOException $Exception) {
    print "오류: " . $Exception->getMessage();
}

?>
  
<form id="board_form"  name="board_form"  method="post" action="handover_list.php?mode=search">      
    <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">  
	<div class="card mb-2 mt-2">  
	<div class="card-body">  	 
			 
	<div class="d-flex  p-1 m-1 mt-1 justify-content-center align-items-center "> 		
		 <span class="text-dark fs-5" >  <?=$title_message?>  </span> 
		<!-- 새로고침 버튼 -->
		<button type="button" class="btn btn-outline-secondary btn-sm ms-2" onclick="location.reload();">
			<i class="bi bi-arrow-clockwise"></i> 
		</button>
	</div>	
	 
<div class="d-flex  p-1 m-1 mt-1 mb-1 justify-content-center align-items-center"> 	  
			<i class="bi bi-caret-right"></i> <?= $total_row ?> 건, &nbsp; 	
           
                <label for="SettingDate">(날짜)기준</label> &nbsp;
                <select id="SettingDate" name="SettingDate" class="form-select mx-1 d-block w-auto" style="font-size: 0.8rem; height: 32px;">
				
				 
                    <option value="regist_day" <?php if($SettingDate == 'regist_day') echo 'selected'; ?>>등록일</option>
                    <option value="update_day" <?php if($SettingDate == 'update_day') echo 'selected'; ?>>최근수정일</option>
                    <option value="completion_date" <?php if($SettingDate == 'completion_date') echo 'selected'; ?>>준공일</option>
                </select>
             &nbsp;
			<!-- 기간부터 검색까지 연결 묶음 start -->
				<span id="showdate" class="btn btn-dark btn-sm " > 기간 </span>	&nbsp; 

				<div id="showframe" class="card">
					<div class="card-header " style="padding:2px;">
						<div class="d-flex justify-content-center align-items-center">  
							기간 설정
						</div>
					</div>
					<div class="card-body">
						<div class="d-flex justify-content-center align-items-center">  	
							<button type="button" class="btn btn-outline-success btn-sm me-1 change_dateRange"   onclick='alldatesearch()' > 전체 </button>  							
							<button type="button" class="btn btn-dark btn-sm me-1  change_dateRange"  onclick='yesterday()' > 전일 </button> 						
							<button type="button" class="btn btn-outline-danger btn-sm me-1  change_dateRange"  onclick='this_today()' > 오늘 </button>							
							<button type="button" class="btn btn-dark btn-sm me-1  change_dateRange"  onclick='this_year()' > 당해년도 </button> 
						</div>
					</div>
				</div>		

	   <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> 
			
		

	   <select id="find" name="find" class="form-select mx-1 d-block w-auto" style="font-size: 0.8rem; height: 32px;">
			<?php
			$options = [
				"all" => "전체",
				"workplacename" => "현장명",
				"firstord" => "발주처",
				"secondord" => "시공사",
				"regist_user" => "등록자"
			];

			foreach ($options as $value => $label) {
				$selected = ($find == $value || ($find == "" && $value == "all")) ? "selected" : "";
				echo "<option value='$value' $selected>$label</option>";
			}
			?>
		</select>
					
			
		<div class="inputWrap">
            <input type="text" id="search" name="search" value="<?=$search?>" onkeydown="JavaScript:SearchEnter();" autocomplete="off"  class="form-control text-start me-1" style="width:150px;" >
            <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> 	
		  <!-- <button type="button" class="btn btn-dark  btn-sm me-1" id="writeBtn"> <i class="bi bi-pencil-fill"></i> 신규  </button> 		  		   -->
         </div> 	 		 		 
   </div> <!--card-body-->
   </div> <!--card -->   
</div> <!--container-fluid -->   
     <div class="container-fluid">
        <div class="d-flex justify-content-center align-items-center">
            <div class="table-responsive">
            <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:250px;">현장명</th>
                        <th class="text-center" style="width:150px;">발주처</th>
                        <th class="text-center" style="width:150px;">시공사</th>
                        <th class="text-center" style="width:110px;">준공일</th>
                        <th class="text-center w100px" >계약금액</th>
                        <th class="text-center w100px" >기준</th>
                        <th class="text-center w80px" >등록자</th>       
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $start_num = $total_row;
                    while ($row = $stmh->fetch(PDO::FETCH_ASSOC)) {
                        $displayworkplacename = mb_strlen($row['workplacename'] ?: $row['work_workplacename']) > 25 ? mb_substr($row['workplacename'] ?: $row['work_workplacename'], 0, 25) . '...' : ($row['workplacename'] ?: $row['work_workplacename']);
                    ?>
				<tr onclick="redirectToView('<?= $row['num'] ?>', '<?= $tablename ?>')" data-num="<?=$row['num']?>">
					<td class="text-center start_num"><?= $start_num ?></td>
					<td class="text-center regist_day"><?= $row['regist_day'] ?></td>
					<td class="text-center update_day"><?= $row['update_day'] ?: '-' ?></td>
					<td class="text-start displayworkplacename"><?= $displayworkplacename ?></td>
					<td class="text-center firstord"><?= $row['firstord'] ?: '-' ?></td>
					<td class="text-center secondord"><?= $row['secondord'] ?: '-' ?></td>
					<td class="text-center completion_date"><?= $row['completion_date'] ?: '-' ?></td>
					<td class="text-end contract_amount"><?= $row['contract_amount'] ?: '-' ?></td>                    
					<td class="text-center supply_amount"><?= $row['priceIncludesVat'] ?: '-' ?></td>
					<td class="text-center regist_user"><?= $row['regist_user'] ?></td>					
				</tr>
                    <?php
                        $start_num--;
                    }
                    ?>
                </tbody>
            </table> 
        </div>
        </div>
    </div> <!--container-->
		
  </form> 
  
<script>
// 페이지 로딩 - 기본 JavaScript 코드
$(document).ready(function(){	
    var loader = document.getElementById('loadingOverlay');
    if(loader)
        loader.style.display = 'none';
});

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

$(document).ready(function() {			
    // DataTables 초기 설정
    dataTable = $('#myTable').DataTable({
        "paging": true,
        "ordering": true,
        "searching": true,
        "pageLength": 100,
        "lengthMenu": [100, 200, 500, 1000, 2000],
        "language": {
            "lengthMenu": "Show _MENU_ entries",
            "search": "Live Search:"
        },
        "order": [[0, 'desc']] // 번호 기준 내림차순
    });

    // 검색 버튼 클릭 이벤트
    $('#searchBtn').click(function() {
        var searchValue = $('#search').val();
        var findValue = $('#find').val();
        var fromdateValue = $('#fromdate').val();
        var todateValue = $('#todate').val();
        var settingDateValue = $('#SettingDate').val();
        
        var url = 'handover_list.php?';
        if (searchValue) url += 'search=' + encodeURIComponent(searchValue) + '&';
        if (findValue && findValue !== 'all') url += 'find=' + encodeURIComponent(findValue) + '&';
        if (fromdateValue) url += 'fromdate=' + fromdateValue + '&';
        if (todateValue) url += 'todate=' + todateValue + '&';
        if (settingDateValue) url += 'SettingDate=' + settingDateValue + '&';
        
        // 마지막 & 제거
        url = url.replace(/&$/, '');
        
        window.location.href = url;
    });

    // 신규 버튼 클릭 이벤트
    $('#writeBtn').click(function() {
        // 신규 인수인계 보고서 작성 팝업창으로 열기
        var url = 'handover_doc.php';
        customPopup(url, '인수인계 보고서 작성', 800, 900);
    });

    // 기간 설정 버튼들
    $('.change_dateRange').click(function() {
        var buttonText = $(this).text().trim();
        var fromdate = $('#fromdate');
        var todate = $('#todate');
        var currentDate = new Date();
        
        switch(buttonText) {
            case '전체':
                fromdate.val('2012-01-01');
                todate.val(currentDate.toISOString().split('T')[0]);
                break;
            case '전일':
                var yesterday = new Date(currentDate);
                yesterday.setDate(currentDate.getDate() - 1);
                fromdate.val(yesterday.toISOString().split('T')[0]);
                todate.val(yesterday.toISOString().split('T')[0]);
                break;
            case '오늘':
                var today = currentDate.toISOString().split('T')[0];
                fromdate.val(today);
                todate.val(today);
                break;
            case '당해년도':
                var yearStart = currentDate.getFullYear() + '-01-01';
                fromdate.val(yearStart);
                todate.val(currentDate.toISOString().split('T')[0]);
                break;
        }
    });

    // Enter 키 검색
    function SearchEnter() {
        if (event.keyCode == 13) {
            $('#searchBtn').click();
        }
    }
    window.SearchEnter = SearchEnter;
});

// 행 클릭 시 상세보기로 이동
function redirectToView(num, tablename) {
    // 작업 버튼이 있는 경우 클릭 이벤트 방지
    if (event.target.tagName === 'A' || event.target.tagName === 'BUTTON') {
        return;
    }
    
    // 인수인계 보고서 상세보기로 팝업창으로 열기
    var url = 'handover_doc.php?handover_num=' + num;
    customPopup(url, '인수인계 보고서', 800, 900);
}
</script>
  
</body>
</html>  
  