<?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'; 

// 권한 부여
$authorities = ["개발자","전진","노완호","이세희","함신옥","손금주","이은진","이경호","이세희","함신옥"];

$option = $_REQUEST['option'] ?? ''; // 조회시 조건 부여
if($option == '미출고') {	
	$title_message = '미출고 수주 List';   	
	$existing_status=$_REQUEST["status_option"] ?? '미출고' ;     
} 
else {	
	$title_message = '경동기업 수주 List';   	
	$existing_status=$_REQUEST["status_option"] ?? '전체' ;     
} 

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$developer_filter =  $_REQUEST['developer_filter'] ?? '';

// echo '개발자 모드 ' . $developer_filter;

?>  
<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";

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

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

// 개발모드인 경우는 일자를 1년전에서 시작한다.
if (in_array($user_name, $authorities, true) && $developer_filter === 'on') {
    $fromdate = date("Y-m-d", strtotime("-1 year", strtotime($currentDate)));
}


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' or is_deleted is null) " ;
    $searchwhere = " where is_deleted = '0' and searchtag like '%$search%'" ;
} else if ($existing_status == '미출고') {    
    $where = " where " . $SettingDate . " between date('$fromdate') and date('$Transtodate') and (is_deleted = '0' or is_deleted is null) and regist_state != '완료' " ;
    $searchwhere = " where is_deleted = '0' and regist_state != '완료' and searchtag like '%$search%'" ;
}
 else {    
    $where = " where " . $SettingDate . " between date('$fromdate') and date('$Transtodate') and (is_deleted = '0' or is_deleted is null) and regist_state = '$existing_status'" ;
    $searchwhere = " where is_deleted = '0' and regist_state = '$existing_status' and searchtag like '%$search%'" ;
}

// 개발모드에 따라 검색하는 로직
if(in_array($user_name, $authorities, true) && $developer_filter == 'on') {
    $where .= " and devMode = '1' ";
    $searchwhere .= " and devMode = '1' ";
} 
else
{
    $where .= " and  (devMode <> '1' OR devMode IS NULL) ";
    $searchwhere .= " and (devMode <> '1' OR devMode IS NULL) ";
} 


$where .= $orderby; 
$searchwhere .=  $orderby;

// 수정된 쿼리: outputnum이 존재하는 자료만 선택
if ($search == "") {
		$sql = "select * from $DB.$tablename " . $where;                         
	} else { 
		$sql = "select * from $DB.$tablename " . $searchwhere;
}

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

// print $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?>">  
    <input type="hidden" id="option" name="option" value="<?=$option?>">   	
<div class="container-fluid">  
	<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>  	  
			   <?php if($user_id == "pro") : ?>
					<button type="button" class="btn btn-danger btn-sm mx-3" onclick="location.href='list1.php'">개발자 list1.php </button>
			   <?php endif; ?>			   
			   <?php 
			//    // 권한 검사: $user_id 가 $authorities 배열에 있으면 버튼 출력
			// 	if (in_array($user_name, $authorities, true)) :
			// 	echo '<button type="button" class="btn btn-outline-danger btn-sm mx-3" onclick="location.href=\'list1.php\'">
			// 	개발 화면
			//  </button>';
			// endif; ?>
		</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="col-sm-3"> 
  <?php if($option !== '미출고') : ?>
	<div class="d-flex p-1 m-1 mt-1 justify-content-start align-items-center">    					
			<label>
				<input type="radio" name="status_option" value="전체" onclick="submitForm('전체');" <?php if($existing_status == '전체') echo 'checked'; ?>>
				<span class="badge bg-secondary me-2 " style="font-size:12px;" >전체</span>
			</label>  					
			<label>
				<input type="radio" name="status_option" value="등록" onclick="submitForm('등록');" <?php if($existing_status == '등록') echo 'checked'; ?>>
				<span class="badge bg-danger me-2 " style="font-size:12px;" >등록</span>
			</label>  					
			<label>
				<input type="radio" name="status_option" value="수정" onclick="submitForm('수정');" <?php if($existing_status == '수정') echo 'checked'; ?>>
				<span class="badge bg-warning me-2 " style="font-size:12px;" >수정</span>
			</label>
			<label>
				<input type="radio" name="status_option" value="접수" onclick="submitForm('접수');" <?php if($existing_status == '접수') echo 'checked'; ?>>
				<span class="badge bg-success me-2 " style="font-size:12px;">접수</span>
			</label>
			<label>
				<input type="radio" name="status_option" value="완료" onclick="submitForm('완료');" <?php if($existing_status == '완료') echo 'checked'; ?>>
				<span class="badge bg-dark me-2 " style="font-size:12px;" >완료</span>
			</label>  
			<label>
				<input type="radio" name="status_option" value="미출고" onclick="submitForm('미출고');" <?php if($existing_status == '미출고') echo 'checked'; ?>>
				<span class="badge bg-primary me-2 " style="font-size:12px;" >미출고</span>
			</label>    
	  </div>
	<?php endif; ?>
</div> 
<div class="col-sm-9"> 	
<div class="d-flex  p-1 m-1 mt-1 mb-1 justify-content-start align-items-center"> 
▷  <?= $total_row ?> &nbsp; 		
	<label>&nbsp; 출고일 <input type="radio" name="separate_date" value="1" <?= $separate_date == "1" ? 'checked' : '' ?>></label>
	<label>&nbsp; 접수일 <input type="radio" name="separate_date" class="me-3" value="2" <?= $separate_date == "2" ? 'checked' : '' ?>></label>

	<?php if(in_array($user_name, $authorities, true) ): ?>
	<?php
	$checked = (isset($developer_filter) && $developer_filter === 'on') ? 'checked' : '';
	$checkMessage = (isset($developer_filter) && $developer_filter === 'on') ? '개발모드' : '개발모드';
	?>
	<label>&nbsp; <?= $checkMessage ?> 
	<input type="checkbox" id="developer_filter" name="developer_filter" class="mx-3" <?= $checked ?>>
	</label>
	<?php endif; ?>


	<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; 
   
	<!-- <button type="button" id ="Fromthistoday" type='button'  class="btn btn-dark btn-sm me-1   " onclick='Fromthis_today()' > 금일이후 </button>
	<button type="button" id ="Fromtomorrow" type='button'  class="btn btn-dark btn-sm me-1   " onclick='From_tomorrow()' > 익일이후 </button>
	-->
	
   </span>
	<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>
	<div id="autocomplete-list">						
	</div>	
	  &nbsp;
	  <button id="searchBtn" type="button" class="btn btn-dark  btn-sm" > <i class="bi bi-search"></i> 검색 </button> 		  
		  &nbsp;&nbsp;&nbsp;		    
		 <button type="button" class="btn btn-dark  btn-sm me-1" id="writeBtn"> <i class="bi bi-pencil-fill"></i> 신규  </button> 
		 <button type="button" class="btn btn-dark btn-sm me-1" onclick="popupCenter('delivery.php','경동 출고List',1800,900);">  <i class="bi bi-print"></i> </ion-icon> 화물/택배 출고List </button>   
		  							 				 
     </div> 	 		 
     </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 table-sm" id="myTable">
  <thead class="table-primary">
		<tr>
			<th class="text-center" style="width:30px;">번호</th>
			<th class="text-center" style="width:90px;">출고</th>
			<th class="text-center" style="width:40px;">접수</th>
			<th class="text-center" style="width:30px;">진행</th>
			<th class="text-center" style="width:40px;">절곡</th>
			<th class="text-center" style="width:30px;">모터</th>
			<th class="text-center" style="width:100px;">발주처</th>
			<th class="text-center" style="width:60px;">모델</th>
			<th class="text-center" style="width:140px;">현장명</th>
			<th class="text-center" style="width:80px;">수신자</th>
			<th class="text-center" style="width:120px;">수신 주소</th>
			<th class="text-center" style="width:90px;"><i class="bi bi-telephone-fill"> </i> 수신처</th>
			<th class="text-start" style="width:45px; "><i class="bi bi-truck"></i> 운송</th>
			<th class="text-center" style="width:40px;">담당</th>
			<th class="text-center" style="width:30px;">틀수</th>
			<th class="text-center" style="width:30px;">(㎡)</th>
			<!-- <th class="text-center" style="width:50px;">인정</th> -->
			<th class="text-center" style="width:250px;">비고</th>
		</tr>
    </thead>	
    <tbody>	
	<?php  	
        $start_num=$total_row;    // 페이지당 표시되는 첫번째 글순번          
		$total_m2_formatted = 0 ;
		$total_egi_m2_formatted = 0 ;
		
		$total_screen_sum = 0;		
		$total_screen_m2 = 0;		
		
		$total_egi_sum = 0;		
		$total_egi_m2 = 0;						

	if($total_row>10000) { 	   
	    echo '<tr> <td colspan="18"> <span class="text-primary fs-3"> 검색량이 10000개 넘어갑니다. 검색 기간을 변경 후 검색하세요! </span> </td><tr>';
	}
	else { 
	
       while($row = $stmh->fetch(PDO::FETCH_ASSOC)) {
			include '_row.php';	
		
		// 콤마를 제거하고 숫자로 변환
		$screen_su_cleaned = floatval(str_replace(',', '', $screen_su));
		$screen_m2_cleaned = floatval(str_replace(',', '', $screen_m2));

		$slat_su_cleaned = floatval(str_replace(',', '', $slat_su));
		$slat_m2_cleaned = floatval(str_replace(',', '', $slat_m2));

		$screenlists = json_decode($screenlist, true);
		// var_dump($screenlists["screen_m2"]);
	  					
        if($steel!="1")
			$bend_state="";			
		
        if($motor=="1")
        $motor="모터";			

        if($root=="주일") 
        $root_font="text-dark";
        else			
        $root_font="text-primary";						

        $date_font="text-dark";  // 현재일자 Red 색상으로 표기
        if($today==$outdate) {
        $date_font="text-danger";
        }

        $font="text-dark";
        switch ($delivery) {
        case   "상차(선불)"             :  $font="text-dark"; break;
        case   "상차(착불)"              :$font="color-grey" ; break;
        case   "경동화물(선불)"          :$font="color-brown"; break;
        case   "경동화물(착불)"          :$font="color-brown"; break;
        case   "경동택배(선불)"          :$font="color-brown"; break;
        case   "경동택배(착불)"          :$font="color-brown"; break;
        case  "직접배차"                 :$font="color-purple"; break;
        case  "직접수령"                 :$font="text-danger"; break;
        case  "대신화물(선불)"           :$font="color-blue"; break; 
        case  "대신화물(착불)"           :$font="color-blue"; break;
        case  "대신택배(선불)"           :$font="color-blue"; break;
        case  "대신택배(착불)"           :$font="color-blue"; break;
        }	
        
        if($outdate!="") {
        $week = array("(일)" , "(월)"  , "(화)" , "(수)" , "(목)" , "(금)" ,"(토)") ;
        $outdate = $outdate . $week[ date('w',  strtotime($outdate)  ) ] ;
        $formatedoutdate = $outdate;
        $formatedindate = date("m-d",strtotime($indate));
        }  
      ?>
		<tr onclick="redirectToView('<?= $num ?>', '<?= $tablename ?>')">
			<td class="text-center" ><?= $start_num ?></td>
			<td class="text-center" data-outdate="<?=$outdate ?>"> <?= $formatedoutdate ?></td>
			<td class="text-center" data-indate="<?=$indate ?>">   <?= $formatedindate ?></td>
			<td class="text-center" > 
				<?php			
				  switch ($regist_state) {
					case   "등록"     :  
						$regist_word="등록"; 
						echo '<span class="badge bg-danger">' .$regist_word . '</span>';
						break;
					case   "수정"     :  
						 $regist_word="수정"; 
						 echo '<span class="badge bg-warning blink">' .$regist_word . '</span>';
						 break;	
					case   "접수"     :  
						 $regist_word="접수"; 
						 echo '<span class="badge bg-success">' .$regist_word . '</span>';
						 break;	
					case   "완료"     :  
						 $regist_word="완료"; 
						 echo '<span class="badge bg-dark">' .$regist_word . '</span>';
						break;					
				}						
			  ?>							
			</td>			
			<td class="text-center"><?= $bend_state ?></td>
			<td class="text-center"><?= $motor ?></td>
			<td class="text-start" ><?= $secondord ?></td>
			<td class="text-center" ><?= $prodCode ?></td>
			<td class="text-start" ><?= $outworkplace ?></td>
			<td class="text-start" ><?= $receiver ?></td>
			<td class="text-start" ><?= $outputplace ?></td>
			<td class="text-start" ><?= $phone ?></td>
			<td class="text-start" >
			<?php			
				if (strpos($delivery, '경동') !== false) {
					echo '<span class="text-primary">' . $delivery . '</span>';
				} else if (strpos($delivery, '대신') !== false) {
					echo '<span class="text-success">' . $delivery . '</span>';
				} else {
					switch ($delivery) {
						case "직접배차":
							echo '<span class="badge bg-secondary">' . $delivery . '</span>';
							break;
						case "직접수령":
							echo '<span class="badge bg-dark">' . $delivery . '</span>';
							break;
						case "상차(선불)":									
							echo '<span class="badge bg-info">' . $delivery . '</span>';
							break;
						case "상차(착불)":																	
							echo '<span class="badge bg-warning">' . $delivery . '</span>';
							break;
						default:
							echo '<span class="text-dark">' . $delivery . '</span>';
							break;
					}
				}					
			?>
		</td>
			
		<td class="text-center"><?= $orderman ?></td>
          <?php		
			$row_sum = $screen_su_cleaned + $slat_su_cleaned ;
			$row_m2 = $screen_m2_cleaned + $slat_m2_cleaned ;	

			$row_sum_formatted = number_format($row_sum);			
			$row_m2_formatted = number_format($row_m2, 1);			
						  
			if ($row_sum_formatted > 0) 
				print '<td class="text-end" style=>' . $row_sum_formatted . '</td>';
			else
				print '<td class="text-end" style=>&nbsp;</td>'; 

			if ($row_m2_formatted > 0) 
				print '<td class="text-end" style=>' . $row_m2_formatted . '</td>';
			else
				print '<td class="text-end" style=>&nbsp;</td>';
				
			$total_sum += $screen_su_cleaned;
			$total_m2 += $screen_m2_cleaned;
			$total_egi += $slat_su_cleaned;
			$total_egi_m2 += $slat_m2_cleaned;
		
			// // 소수점 첫째자리까지만 포맷팅
			$total_m2_formatted = number_format($total_m2, 1);
			$total_egi_m2_formatted = number_format($total_egi_m2, 1);
		   ?>
		<!-- <td class="text-center"></td>   -->
		<td class="text-start">
			<?= $comment ?>
			<?php if (!empty($updatecomment) && $regist_state !== '완료'): ?>
				<span class="text-danger fw-bold blink"><?= $updatecomment ?></span>
			<?php else: ?>
				<span class="text-danger fw-bold"><?= $updatecomment ?></span>
			<?php endif; ?>
		</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');
    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);
        }
    });
	
    // // 검색 버튼 클릭 이벤트 처리 (form submit)
    // $('#board_form').on('submit', function(e) {
        // e.preventDefault();
      
    // });	
	
});

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

function redirectToView(num, tablename) {	
    var url = "write_form.php?mode=view&num=" + num + "&tablename=" + tablename;          
	customPopup(url, '수주 내역', 1900, 920); 		    
}

$(document).ready(function() { 
	$("input:radio[name=separate_date]").click(function() { 
		process_list(); 
	}) 
}); 

function process_list(){   // 접수일 출고일 라디오버튼 클릭시
      document.getElementById('search').value=null; 
	  //  dataTable.page(0).draw(false); // 검색 후 첫 페이지로 이동   
      document.getElementById('board_form').submit();  // form의 검색버튼 누른 효과  
} 
  
$(document).ready(function(){	
	$("#writeBtn").click(function(){ 		
		var tablename = '<?php echo $tablename; ?>';		
		var url = "write_form.php?tablename=" + tablename; 				
		customPopup(url, '수주내역', 1900, 920); 	
	 });	  
});	  

function submitForm(status) {
    $('input[name=status_option]').val(status);
    document.getElementById('board_form').submit();
}
 
$(document).ready(function(){	    
	document.getElementById('total_screen').textContent = '스크린 : <?= $total_sum ?>';
	document.getElementById('total_screen_m2').textContent = '면적 : <?= $total_m2_formatted ?> ㎡';
	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);
});
 
$(document).ready(function() {
    $("#developer_filter").change(function() {
        if (this.checked) {
            $('input[name=developer_filter]').val('on');
        } else {
            $('input[name=developer_filter]').val('');
            
            // 현재 날짜에서 1주일 전 계산
            const today = new Date();
            today.setDate(today.getDate() - 7);
            const year = today.getFullYear();
            const month = String(today.getMonth() + 1).padStart(2, '0');
            const day = String(today.getDate()).padStart(2, '0');
            const oneWeekAgo = `${year}-${month}-${day}`;

            // #fromdate 필드에 값 설정
            $('#fromdate').val(oneWeekAgo);
        }
        document.getElementById('board_form').submit();
    });
});

 
</script>
</body> 
</html>