<?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
// 세무사아이디면 다른 메뉴 연결
if($_SESSION["userid"] == '0266771300') {
	include $_SERVER['DOCUMENT_ROOT'] . '/myheader_accountant.php'; 
}
else {
	include $_SERVER['DOCUMENT_ROOT'] . '/myheader.php'; 
}
?>   

<?php
// Check if 'navibar' and 'menu' are set in the request and assign their values; if not, set them to an empty string
$navibar = isset($_REQUEST['navibar']) ? $_REQUEST['navibar'] : '';
$menu = isset($_REQUEST['menu']) ? $_REQUEST['menu'] : '';

$tablename = "carrecord";

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

// 기본값 설정
$mode = $_REQUEST["mode"] ?? "";
$search = $_REQUEST["search"] ?? "";

$base_sql = "SELECT * FROM {$DB}.{$tablename} WHERE 1";  // WHERE 1로 시작하면 AND 연결 쉬움
$search_sql = "";
$search_columns = [];
$bind_params = [];

if ($mode === "search" && !empty($search)) {
    try {
        $columns = $pdo->query("SHOW COLUMNS FROM {$DB}.{$tablename}")->fetchAll(PDO::FETCH_ASSOC);
        foreach ($columns as $column) {
            $field = $column['Field'];
            $type = strtolower($column['Type']);

            if (strpos($type, 'char') !== false || strpos($type, 'text') !== false || strpos($type, 'date') !== false) {
                $param = ":search_{$field}"; // 유니크한 바인딩 이름
                $search_columns[] = "{$field} LIKE {$param}";
                $bind_params[$param] = "%{$search}%";
            }
        }

        if (!empty($search_columns)) {
            $search_sql = " AND (" . implode(" OR ", $search_columns) . ")";
        }
    } catch (PDOException $e) {
        echo "컬럼 조회 오류: " . $e->getMessage();
        exit;
    }
}

$sql = $base_sql . $search_sql . " ORDER BY num DESC";

try {
    $stmh = $pdo->prepare($sql);

    foreach ($bind_params as $param => $value) {
        $stmh->bindValue($param, $value, PDO::PARAM_STR);  // 1:1로 바인딩
    }

    $stmh->execute();
    $total_row = $stmh->rowCount();
// } catch (PDOException $e) {
    // echo "오류: " . $e->getMessage();
// }

// var_dump($sql);	 
 // try{  
	// $stmh = $pdo->query($sql); 
 ?>

<form name="board_form" id="board_form"  method="post" action="list.php?mode=search&search=<?=$search?>">
<div class="container justify-content-center">  
  <input type="hidden" id="page" name="page" value="<?=$page?>"  > 
  <input type="hidden" id="scale" name="scale" value="<?=$scale?>"  > 
	<div class="card mt-2 mb-4">  
	<div class="card-body">  
		<div class="d-flex mt-3 mb-2 justify-content-center align-items-center">  
			<h5>  <?=$title_message?> </h5> 
			<button type="button" class="btn btn-dark btn-sm mx-2"  onclick='location.reload();' > <i class="bi bi-arrow-clockwise"></i> </button>  	   		  				
		</div>	   
		<div class="d-flex mt-3 mb-1 justify-content-center  align-items-center">   				
			▷  <?= $total_row ?> &nbsp; 			
			<div class="inputWrap">
				<input type="text" id="search" class="form-control mx-1" style="width:150px;" name="search" autocomplete="off" value="<?=$search?>" placeholder="검색어" onkeydown="JavaScript:SearchEnter();" >
				<button class="btnClear"></button>
			</div>				
			<button id="searchBtn" type="button" class="btn btn-dark btn-sm mx-1"><i class="bi bi-search"></i> 검색 </button>
			<button type="button" class="btn btn-dark  btn-sm mx-1" id="writeBtn"> <i class="bi bi-pencil"></i>  신규  </button> 			   
		</div>	
	   
 <div class="row d-flex"  >
 <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>
			 </tr>
       </thead>
	<tbody>  	
<?php  
 $start_num=$total_row;    // 페이지당 표시되는 첫번째 글순번 
			 
 while($row = $stmh->fetch(PDO::FETCH_ASSOC)) {
  $item_num=$row["num"];
  $item_id=$row["id"];  
  $item_nick=$row["nick"];
  $car_name=$row["car_name"] ?? '';
  $item_hit=$row["hit"];
  $item_date=$row["regist_day"];
  $item_date=substr($item_date, 0, 10);
  $item_subject=str_replace(" ", "&nbsp;", $row["subject"]);
   
  $sql="select * from ".$DB.".notice_ripple where parent=$item_num";
  $stmh1 = $pdo->query($sql); 
  $num_ripple=$stmh1->rowCount(); 
 ?>
 
   <tr onclick="redirectToView('<?=$item_num?>', '<?=$tablename?>')">  
	  <td class="text-center" >  <?= $start_num ?>   </td>
	  <td class="text-center" >  <?= $item_date ?>   </td>     
	  <td class="text-center" >  <?= $car_name ?>   </td>     
	  <td class="text-center" >  <?= $item_nick ?>   </td>	  
	  <td class="text-start">  <?= $item_subject ?>  </td>
	</tr>
 
 <?php
	$start_num--;
    }
  } catch (PDOException $Exception) {
  print "오류: ".$Exception->getMessage();
  }  
  
 ?>
		</tbody>
	</table>  
</div>

</div> <!--card-body-->
</div> <!--card -->
</div> <!--container-->

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

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

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

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

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

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

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

function restorePageNumber() {
    var savedPageNumber = getCookie('carrecordpageNumber');
    if (savedPageNumber) {
        dataTable.page(parseInt(savedPageNumber) - 1).draw('page');
    }
}


function redirectToView(num, tablename) {       	
    var url = "write_form.php?mode=view&num=" + num + "&tablename=" + tablename;          
	customPopup(url, '', 1300, 850); 		    
}

$(document).ready(function(){	
	$("#writeBtn").click(function(){ 		
		var tablename = '<?php echo $tablename; ?>';		
		var url = "write_form.php?tablename=" + tablename; 				
		customPopup(url, '', 1300, 850); 	
	 });			 
		
});	

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

</body> 
</html>