<?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 = '작업 List';   
$title_prefix = '절곡';   

?>  
<title>  <?=$title_prefix?> <?=$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();  

// 검색 조건 설정
$option = $_REQUEST['option'] ?? ''; // 조회시 조건 부여
$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 ";  

$separate_date=$_REQUEST["separate_date"] ?? '';	 
$existing_status=$_REQUEST["status_option"] ?? '전체';	 
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;
	}
} 

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'  AND (devMode <> '1' or devMode IS NULL) and steel = '1' " . $orderby;
	$searchwhere = " where " . $SettingDate . " between date('$fromdate') and date('$Transtodate') and is_deleted = '0'  AND (devMode <> '1' or devMode IS NULL) and steel = '1' and searchtag like '%$search%' " . $orderby;
}
else if ($existing_status == '미출고') 
{
	$where = " where " . $SettingDate . " between date('$fromdate') and date('$Transtodate') and is_deleted = '0'  AND (devMode <> '1' or devMode IS NULL) and steel = '1' and bend_state != '완료' " . $orderby;
	$searchwhere = " where " . $SettingDate . " between date('$fromdate') and date('$Transtodate') and is_deleted = '0'  AND (devMode <> '1' or devMode IS NULL) nd steel = '1' and bend_state != '완료' and searchtag like '%$search%' " . $orderby;
}
else
{	
	$where = " where " . $SettingDate . " between date('$fromdate') and date('$Transtodate') and is_deleted = '0'  AND (devMode <> '1' or devMode IS NULL) and steel = '1' and bend_state = '$existing_status' " . $orderby;
	$searchwhere = " where " . $SettingDate . " between date('$fromdate') and date('$Transtodate') and is_deleted = '0'  AND (devMode <> '1' or devMode IS NULL) and steel = '1' and bend_state = '$existing_status' and searchtag like '%$search%' " . $orderby;
}

	

if($search==""){
	$sql="select * from $DB.$tablename " . $where; 						
} 
else if($search!="") { // 각 필드별로 검색어가 있는지 쿼리주는 부분						
	$sql ="select * from $DB.$tablename " . $searchwhere ;
}

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

// print $sql;
// print ' existing_status : ' . $existing_status;

try {   
$stmh = $pdo->query($sql);            // 검색조건에 맞는글 stmh
$total_row = $stmh->rowCount();
 
$total_sum=0;
$total_m2=0;			
?>

<form id="board_form"  name="board_form"  method="post" action="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?>">   
    <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="d-flex  p-1 m-1 mt-1 justify-content-center align-items-center "> 		
			   <span class="badge bg-dark fs-6 mx-2">  <?=$title_prefix?>  </span>  
			   <h5>  <?=$title_message?>  (<?=$existing_status?>)  </h5>  &nbsp;&nbsp;&nbsp;	&nbsp;	 
			   <button type="button" class="btn btn-dark btn-sm mx-3" onclick='location.href="list.php"'> 
                <i class="bi bi-arrow-clockwise"></i>
            </button>			   
		</div>	
	<div class="row"> 			 
	  <div class="col-sm-3"> 			 
		<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('전체');return false;" <?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('등록');return false;" <?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('접수');return false;" <?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('제작중');return false;" <?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('완료');return false;" <?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('미출고');return false;" <?php if($existing_status == '미출고') echo 'checked'; ?>>
					<span class="badge bg-primary me-2 " style="font-size:12px;" >미출고</span>
				</label>    			
		</div> 
	</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>

	<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" 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>
   </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:30px;">번호</th>
		<th class="text-center" style="width:75px;">출고일</th>
		<th class="text-center" style="width:65px;">접수일</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:200px;">현장명</th>
		<th class="text-center" style="width:100px;">수신자</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:50px;">인정</th>
		<th class="text-center" style="width:350px;">비고</th>
   </tr>
   </thead>
	<?php  
      $start_num=$total_row;    // 페이지당 표시되는 첫번째 글순번         
	  
      while($row = $stmh->fetch(PDO::FETCH_ASSOC)) {
        $item_num=$row["num"];
        $outdate=$row["outdate"];
        $item_indate=$row["indate"];
        $item_orderman=$row["orderman"];
        $item_outworkplace=$row["outworkplace"];
        $item_outputplace=$row["outputplace"];
        $item_receiver=$row["receiver"];
        $item_phone=$row["phone"];
        $comment=$row["comment"];	  
        $updatecomment=$row["updatecomment"];	  
        $root=$row["root"];	  
        $steel=$row["steel"];	  
        $motor=$row["motor"];	  
        $delivery=$row["delivery"];	  
        $regist_state=$row["regist_state"];	 
        $bend_state=$row["bend_state"];	 
        $secondord=$row["secondord"];	 
        $warranty=$row["warranty"];	 
        if($bend_state==null)
        $bend_state="1";

        $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;
        }	

        // switch ($bend_state) {
        // case   "1"     :  $font_state="text-danger"; $regist_word="등록"; break;
        // case   "2"     :  $font_state="color-green"  ; $regist_word="접수"; break;	
        // case   "3"     :  $font_state="color-green"  ; $regist_word="제작중"; break;	
        // case   "4"     :  $font_state="text-dark"  ; $regist_word="완료"; break;	
        // default:  $regist_word="등록"; break;
        // }								

        

        if($outdate!="") {
        $week = array("(일)" , "(월)"  , "(화)" , "(수)" , "(목)" , "(금)" ,"(토)") ;
        $outdate = $outdate . $week[ date('w',  strtotime($outdate)  ) ] ;
        }  
      ?>
		<tr onclick="redirectToView('<?= $item_num ?>', '<?= $tablename ?>')">
			<td class="text-center" ><?= $start_num ?></td>
			<td class="text-center" ><?= $outdate ?></td>
			<td class="text-center" > <?= $item_indate ?></td>
			<td class="text-center" > 
				<?php			
					  switch ($regist_state) {
						case   "등록"     :  
							$regist_word="등록"; 
							echo '<span class="text-dark">' .$regist_word . '</span>';
							break;
						case   "수정"     :  
							 $regist_word="수정"; 
							 echo '<span class="badge bg-warning blink">' .$regist_word . '</span>';
							 break;	
						case   "접수"     :  
							 $regist_word="접수"; 
							 echo '<span class="text-dark">' .$regist_word . '</span>';
							 break;	
						case   "완료"     :  
							 $regist_word="완료"; 
							 echo '<span class="text-dark">' .$regist_word . '</span>';
							break;					
					}						
				?>							
			</td>			
			<td class="text-center" > 
				<?php			
					  switch ($bend_state) {
						case   "등록"     :  
							$regist_word="등록"; 
							echo '<span class="badge bg-danger">' .$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-warning">' .$regist_word . '</span>';
							break;
						case   "완료"     :  
							 $regist_word="완료"; 
							 echo '<span class="badge bg-dark">' .$regist_word . '</span>';
							break;		
					}						
				?>							
			</td>
			<td class="text-start" ><?= $secondord ?></td>			
			<td class="text-start" ><?= $item_outworkplace ?></td>
			<td class="text-start" ><?= $item_receiver ?></td>
			<td class="text-start" ><?= $item_outputplace ?></td>
			<td class="text-start" ><?= $item_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" ><?= $item_orderman ?></td>	
		    <td class="text-center"><?= $warranty ?></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 bendingpageNumber; // 현재 페이지 번호 저장을 위한 전역 변수

$(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": [[0, 'desc']] // 출고예정기준 내림정렬
    });

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

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

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

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

function restorePageNumber() {
    var savedPageNumber = getCookie('bendingpageNumber');
    // 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, '절곡 수주내역', 1850, 900); 		    
}

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

function process_list(){   // 접수일 출고일 라디오버튼 클릭시
      document.getElementById('search').value=null; 
      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, '수주내역', 1850, 900); 	
	 });	  
});	  
  

function submitForm(status) {
    $('input[name=status_option]').val(status);
    document.getElementById('board_form').submit();
}

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