<?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 = '업무용승용차 운행기록부'; 
?>

<link href="css/style.css" rel="stylesheet">   
<title> <?=$title_message?> </title>

</head>
<body>

<?php
$header = isset($_REQUEST['header']) ? $_REQUEST['header'] : '';  

if($user_id === '0266771300' ) {
         require_once($_SERVER['DOCUMENT_ROOT'] . '/myheader_accountant1.php'); // 경리
	} else {
	     require_once($_SERVER['DOCUMENT_ROOT'] . '/myheader1.php'); 
	}

$search = $_REQUEST['search'] ?? '';  
$mode = $_REQUEST["mode"] ?? '';
$fromdate = $_REQUEST["fromdate"] ?? '' ;
$todate = $_REQUEST["todate"] ?? '' ;

$car_table = 'juilcar';
// 차량 리스트 불러오기
$car_sql = "SELECT vehicle_number FROM " . $DB . "." . $car_table . " WHERE is_deleted IS NULL ORDER BY manufacturing_date ASC, purchase_date ASC";
$car_stmh = $pdo->query($car_sql);
$car_list = $car_stmh->fetchAll(PDO::FETCH_ASSOC);

$tablename = 'juilcarlog'; 

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

// fromdate 또는 todate가 빈 문자열이거나 null인 경우
if ($fromdate === "" || $todate === "" ) {
    // $fromdate = date("Y-m-d", strtotime("-4 weeks", strtotime($currentDate))); // 1주일 전
    $fromdate = date("Y-m-01");
   // $fromdate = $currentDate;
   // $todate = $currentDate; // 현재 날짜
   $todate = date("Y-m-t"); // 현재 월의 마지막 날
}

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

$order_by = "ORDER BY l.use_date DESC, l.num DESC";

// 1. 테이블 컬럼 목록 가져오기
$column_query = "SHOW COLUMNS FROM " . $DB . "." . $tablename;
$column_stmh = $pdo->query($column_query);
$columns = $column_stmh->fetchAll(PDO::FETCH_COLUMN);

// 2. SQL 기본 구조 (날짜 범위 필터링 추가)
$sql = "SELECT l.*, 
        IFNULL(c.initial_distance, 0) as initial_distance,
        (IFNULL(c.initial_distance, 0) + (
            SELECT IFNULL(SUM(l2.driving_distance), 0) 
            FROM " . $DB . ".juilcarlog l2 
            WHERE l2.car_number = l.car_number 
            AND l2.is_deleted = 0 
            AND l2.num <= l.num
        )) as total_cumulative_distance
        FROM ".$DB.".".$tablename." l
        LEFT JOIN ".$DB.".juilcar c ON l.car_number = c.vehicle_number
        WHERE l.is_deleted = 0  
        AND l.use_date BETWEEN :fromdate AND :todate";

// 3. 검색어가 있을 경우 모든 컬럼에서 검색 (각 컬럼별 LIKE 추가)
$bindParams = [];
if (!empty($search)) {
    $searchConditions = [];
    foreach ($columns as $index => $col) {
        $paramName = ":search" . $index;
        $searchConditions[] = "l.$col LIKE $paramName";
        $bindParams[$paramName] = "%{$search}%";
    }
    $sql .= " AND (" . implode(" OR ", $searchConditions) . ")";
}

$sql .= " " . $order_by;

// print $sql;

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

    // 4. 바인딩 (날짜 범위)
    $stmh->bindValue(":fromdate", $fromdate, PDO::PARAM_STR);
    $stmh->bindValue(":todate", $todate, PDO::PARAM_STR);

    // 5. 바인딩 (검색어: 각 컬럼별 LIKE 검색 적용)
    foreach ($bindParams as $paramName => $paramValue) {
        $stmh->bindValue($paramName, $paramValue, PDO::PARAM_STR);
    }

    $stmh->execute();
    $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="tablename" name="tablename" value="<?= $tablename ?>">
	
<div class="container-fluid">
	<!-- Modal -->
	<div id="myModal" class="modal">
		<div class="modal-content" style="width:700px;">
			<div class="modal-header">
				<span class="modal-title">차량운행일지 등록/수정</span>
				<span class="close">&times;</span>
			</div>
			<div class="modal-body">
				<div class="custom-card" ></div>
			</div>
		</div>
	</div>
	
	<!-- 최초주행거리 설정 Modal -->
	<div id="initialDistanceModal" class="modal">
		<div class="modal-content" style="width:800px;">
			<div class="modal-header">
				<span class="modal-title">최초주행거리 설정</span>
				<span class="close">&times;</span>
			</div>
			<div class="modal-body">
				<div class="initial-distance-card"></div>
			</div>
		</div>
	</div>
</div>

<div class="container-fluid">
<div class="card text-center mt-5">

    <div class="card-header">
        <div class="d-flex justify-content-center align-items-center">   
            <span class="text-center fs-5"> <?=$title_message?> </span>         
            <button type="button" class="btn btn-dark btn-sm mx-3" onclick='location.reload();' title="새로고침"> <i class="bi bi-arrow-clockwise"></i> </button>   
        </div>
    </div>
    <div class="card-body">    
		<style>
		  .table-bordered.black-border th,
		  .table-bordered.black-border td {
			border: 1px solid #000 !important;
		  }
		</style>

		<div class="row">										 
		<div class="col-sm-6 col-md-6">										 
		<div class="d-flex justify-content-center text-center align-items-center mb-2">										 
		  <div class="alert alert-primary d-flex justify-content-start flex-column" role="alert" style="width:600px; padding:5px;">
			<table class="table table-bordered black-border" style="background-color: transparent;">
			  <tbody>
				<tr>
				  <th style="background-color: transparent;">사용목적</th>
				  <td style="background-color: transparent;">해당코드입력 1.출근 / 2.퇴근 / 3.현장 / 4.비업무용</td>
				</tr>
				<tr>
				  <th style="background-color: transparent;">주행거리, 도착누적거리</th>
				  <td style="background-color: transparent;">(소숫점 2자리) 부분 삭제, 정수만 입력</td>
				</tr>
			  </tbody>
			</table>
		  </div>

        </div>          
          <div class="d-flex justify-content-center text-center align-items-center mb-2">										 
          <div class="alert alert-success d-flex justify-content-start flex-column" role="alert" style="width:600px; padding:5px;">
                최초 일지 등록에는 주행거리 시작km를 넣어주세요. 이후 부터는 누적 계산됩니다.
          </div>
		</div>		
		</div>
        
        <div class="col-sm-6 col-md-6">										 
		<!-- 차량별 주행거리 요약 테이블 -->
		<div class="d-flex justify-content-center text-center align-items-center mb-3">
            <div class="card" style="width:80%;">
                <div class="card-header text-center">
                <div class="d-flex justify-content-center align-items-center mb-1"> 
                    <h6 class="mb-0">차량별 주행거리 요약 (<?= date('Y년 m월', strtotime($fromdate)) ?>)</h6>
                    <span class="text-success small mx-3"> ✔ 각 행 클릭시 목적별 상세내역이 나옵니다. </span>
                </div>                                     
				</div>
				<div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover table-sm mb-0" id="summaryTable">
                            <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>
									<th class="text-center">기간(월)주행거리</th>
									<th class="text-center">총누적주행거리</th>
								</tr>
							</thead>
							<tbody>
                                <?php
								// 차량별 주행거리 요약 데이터 가져오기
								$summary_sql = "SELECT 
									c.vehicle_number,
									c.responsible_person,
									c.vehicle_type,
									IFNULL(c.initial_distance, 0) as initial_distance,
									m.part as department,
									m.position,
									IFNULL(SUM(l.driving_distance), 0) as monthly_distance,
									(IFNULL(c.initial_distance, 0) + (
										SELECT IFNULL(SUM(l2.driving_distance), 0) 
										FROM " . $DB . ".juilcarlog l2 
										WHERE l2.car_number = c.vehicle_number 
										AND l2.is_deleted = 0
									)) as total_cumulative_distance,
									COUNT(l.num) as total_log_count
								FROM " . $DB . ".juilcar c
								LEFT JOIN " . $DB . ".member m ON c.responsible_person = m.name
								LEFT JOIN " . $DB . ".juilcarlog l ON c.vehicle_number = l.car_number 
                                AND l.use_date BETWEEN :fromdate AND :todate 
                                AND l.is_deleted = 0
								WHERE c.is_deleted IS NULL 
								AND IFNULL(c.initial_distance, 0) >= 1
								GROUP BY c.vehicle_number, c.responsible_person, c.vehicle_type, c.initial_distance, m.part, m.position
								HAVING (IFNULL(c.initial_distance, 0) + (
									SELECT IFNULL(SUM(l2.driving_distance), 0) 
									FROM " . $DB . ".juilcarlog l2 
									WHERE l2.car_number = c.vehicle_number 
									AND l2.is_deleted = 0
								)) >= 10
								ORDER BY c.manufacturing_date ASC, c.purchase_date ASC";
                                
								$summary_stmh = $pdo->prepare($summary_sql);
								$summary_stmh->bindValue(":fromdate", $fromdate, PDO::PARAM_STR);
								$summary_stmh->bindValue(":todate", $todate, PDO::PARAM_STR);
								$summary_stmh->execute();
								$summary_list = $summary_stmh->fetchAll(PDO::FETCH_ASSOC);
                                
								foreach ($summary_list as $summary): 
                                    ?>
								<tr class="summary-row"
                                    data-vehicle="<?= htmlspecialchars($summary['vehicle_number'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                                    data-user="<?= htmlspecialchars($summary['responsible_person'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                                    data-department="<?= htmlspecialchars($summary['department'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                                    data-position="<?= htmlspecialchars($summary['position'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                                    data-vehicletype="<?= htmlspecialchars($summary['vehicle_type'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                                    data-monthlydistance="<?= number_format($summary['monthly_distance'], 2) ?>"
                                    data-totalcumulative="<?= number_format($summary['total_cumulative_distance'], 2) ?>"
                                    onclick="showPurposeStats(this)">
                                    <td class="text-center"><?= htmlspecialchars($summary['responsible_person'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
									<td class="text-center"><?= htmlspecialchars($summary['department'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
									<td class="text-center"><?= htmlspecialchars($summary['position'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
									<td class="text-center"><?= htmlspecialchars($summary['vehicle_type'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
									<td class="text-center fw-bold"><?= htmlspecialchars($summary['vehicle_number'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
									<td class="text-end"><?= number_format($summary['monthly_distance']) ?></td>
									<td class="text-end fw-bold text-primary"><?= number_format($summary['total_cumulative_distance']) ?></td>
								</tr>
								<?php endforeach; ?>
							</tbody>
						</table>
					</div>
				</div>
			</div>
		</div>
		</div>
		</div>
        
        <div class="d-flex justify-content-center text-center align-items-center mb-2">                                      
            <i class="bi bi-caret-right"></i> <?= $total_row ?> &nbsp; 
            
			<!-- 기간부터 검색까지 연결 묶음 start -->
			<span id="showdate" class="btn btn-dark btn-sm mx-1" > 기간 </span>	&nbsp; 
			
			<div id="showframe" class="card" style="width:500px;">
				<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" id="preyear" class="btn btn-outline-primary btn-sm me-1 change_dateRange"   onclick='pre_year()' > 전년도 </button>  
						<button type="button" id="three_month" class="btn btn-dark btn-sm me-1  change_dateRange"  onclick='three_month_ago()' > M-3월 </button>
						<button type="button" id="prepremonth" class="btn btn-dark btn-sm me-1  change_dateRange"  onclick='prepre_month()' > 전전월 </button>	
						<button type="button" id="premonth" class="btn btn-dark btn-sm me-1  change_dateRange"  onclick='pre_month()' > 전월 </button> 						
						<button type="button" class="btn btn-outline-danger btn-sm me-1  change_dateRange"  onclick='this_today()' > 오늘 </button>
						<button type="button" id="thismonth" class="btn btn-dark btn-sm me-1  change_dateRange"  onclick='this_month()' > 당월 </button>
						<button type="button" id="thisyear" class="btn btn-dark btn-sm me-1  change_dateRange"  onclick='this_year()' > 당해년도 </button> 
					</div>
				</div>
			</div>		

		   <input type="date" id="fromdate" name="fromdate" size="12"  class="form-control"   style="width:100px;" value="<?=$fromdate?>" >  &nbsp;   ~ &nbsp;  
		   <input type="date" id="todate" name="todate" size="12"   class="form-control"   style="width:100px;" value="<?=$todate?>" >  &nbsp;     </span> 
		   &nbsp;&nbsp;		
		
		
		<div class="inputWrap30">            
			<input type="text" id="search" class="form-control" style="width:150px;" name="search" autocomplete="off" value="<?=$search?>" onKeyPress="if (event.keyCode==13){ enter(); }">
			<button class="btnClear"></button>
		</div>            
		<button class="btn btn-dark btn-sm mx-1" type="button" id="searchBtn"> <i class="bi bi-search"></i> </button>             
		<button class="btn btn-dark btn-sm mx-1" type="button" id="initialDistanceBtn" title="최초주행거리 설정"> <i class="bi bi-gear"></i> </button>             
		<button id="newBtn" type="button" class="btn btn-dark btn-sm mx-1"> <i class="bi bi-pencil-square"></i> 신규 </button>                		
	</div>        
        
        <div class="table-responsive">    
        <table class="table table-hover" id="myTable">         
            <thead class="table-primary">
                <th class="text-center w50px">번호</th>
                <th class="text-center w100px">사용일자</th>
                <th class="text-center w100px">차량번호</th>                   
                <th class="text-center w100px">부서</th>                   
                <th class="text-center w100px">직책</th>                   
                <th class="text-center w100px">사용자</th>
                <th class="text-center w120px">사용목적</th>
                <th class="text-center w120px">운행내역</th>
                <th class="text-center w100px">출발지</th>
                <th class="text-center w100px">도착지</th>
                <th class="text-center w100px">주행거리</th>
                <th class="text-center w100px">월간 누적거리</th>
                <th class="text-center w100px">총 누적거리</th>
                <th class="text-center w200px">비고</th>
            </thead>
            <tbody>       
            <?php       
            $start_num = $total_row;                
            while($row = $stmh->fetch(PDO::FETCH_ASSOC)) { 
			     include '_row.php';
			?>    
                  			
			<tr onclick="loadForm('modify', <?= $num ?>)">  
                <td class="text-center"> <?= $start_num ?> </td>
                <td class="text-center"> <?= htmlspecialchars($row['use_date'], ENT_QUOTES, 'UTF-8') ?> </td>
                <td class="text-center"> <?= htmlspecialchars($row['car_number'], ENT_QUOTES, 'UTF-8') ?> </td>
                <td class="text-center"> <?= htmlspecialchars($row['department'], ENT_QUOTES, 'UTF-8') ?> </td>
                <td class="text-center"> <?= htmlspecialchars($row['position'], ENT_QUOTES, 'UTF-8') ?> </td>
                <td class="text-center"> <?= htmlspecialchars($row['caruser_name'], ENT_QUOTES, 'UTF-8') ?> </td>
                <td class="text-center"> <?= htmlspecialchars($row['usage_purpose'], ENT_QUOTES, 'UTF-8') ?> </td>
                <td class="text-start"> <?= htmlspecialchars($row['operation_details'], ENT_QUOTES, 'UTF-8') ?> </td>
                <td class="text-start"> <?= htmlspecialchars($row['departure'], ENT_QUOTES, 'UTF-8') ?> </td>
                <td class="text-start"> <?= htmlspecialchars($row['destination'], ENT_QUOTES, 'UTF-8') ?> </td>
                <td class="text-end"> <?= number_format($row['driving_distance']) ?> </td>
                <td class="text-end"> <?= number_format($row['arrival_cumulative_distance']) ?> </td>
                <td class="text-end fw-bold text-primary"> <?= number_format($row['total_cumulative_distance']) ?> </td>
                <td class="text-start"> <?= htmlspecialchars($row['note'], ENT_QUOTES, 'UTF-8') ?> </td>
            </tr>
            <?php
                $start_num--;
            }
            } catch (PDOException $Exception) {
                print "오류: " . $Exception->getMessage();
            }  
            ?>         
            </tbody>            
        </table>
        </div>
    </div>
</div>       
</form>

<!-- 사용목적별 통계 모달 -->
<div id="purposeStatsModal" class="modal" style="display:none; position:fixed; z-index:9999; left:0; top:0; width:100vw; height:100vh; background:rgba(0,0,0,0.3);">
  <div class="modal-content" style="width:600px; margin:100px auto; background:#fff; border-radius:8px; box-shadow:0 2px 8px rgba(0,0,0,0.2); position:relative;">
    <div class="modal-header" style="display:flex; justify-content:space-between; align-items:center; padding:16px 24px; border-bottom:1px solid #eee;">
      <span class="modal-title">사용목적별 통계</span>
      <span class="close" style="cursor:pointer; font-size:24px;" onclick="$('#purposeStatsModal').hide();">&times;</span>
    </div>
    <div class="modal-body custom-purpose-stats" style="padding:24px;">
      <!-- AJAX 결과가 여기에 들어감 -->
    </div>
  </div>
</div>

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

var ajaxRequest_write = null;
var dataTable;

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

	var savedPageNumber = getCookie('carpageNumber');
	if (savedPageNumber) {
		dataTable.page(parseInt(savedPageNumber) - 1).draw(false);
	}

	dataTable.on('page.dt', function() {
		var carpageNumber = dataTable.page.info().page + 1;
		setCookie('carpageNumber', carpageNumber, 10);
	});

	$('#myTable_length select').on('change', function() {
		var selectedValue = $(this).val();
		dataTable.page.len(selectedValue).draw();
		savedPageNumber = getCookie('carpageNumber');
		if (savedPageNumber) {
			dataTable.page(parseInt(savedPageNumber) - 1).draw(false);
		}
	});

    // 기존 summaryTable tbody tr 클릭 이벤트 제거
    // $(document).on('click', '#summaryTable tbody tr', function() { ... });
    // 모달 닫기 기능은 유지
    $(document).on('click', '#purposeStatsModal .close', function() {
        $('#purposeStatsModal').hide();
    });

});

function restorePageNumber() {
	var savedPageNumber = getCookie('carpageNumber');
	location.reload(true);
}

function enter() {
	$("#board_form").submit();	       		
}

$(document).keydown(function(e){
	var code = e.keyCode || e.which;
	if (code == 27) { 
		self.close();
	}
});

$("#searchBtn").on("click", function() {
	$("#board_form").submit();
});	

$("#newBtn").on("click", function() {		
	loadForm('insert');
});	

$("#initialDistanceBtn").on("click", function() {
	loadInitialDistanceModal();
});

$("#closeBtn").on("click", function() {
	self.close();
});	
		
function reloadlist() {
	$("#board_form").submit();				
}	

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

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

function loadForm(mode, num = null) {
    $("#mode").val(mode);
    $("#num").val(num || ""); // `copy` 모드인 경우 num을 유지하지 않음

    $.ajax({
        type: "POST",
        url: "fetch_modal.php",
        data: { mode: mode, num: num },
        dataType: "html",
        success: function(response) {
            document.querySelector(".modal-body .custom-card").innerHTML = response;
            $("#myModal").show();

            $(".closeBtn, #closeBtn").off("click").on("click", function () {
                $("#myModal").hide();
            });

            // 로그 보기 버튼
            $("#showlogBtn").off("click").on("click", function () {
                var num = $(this).data("num");
                var tablename = $("#tablename").val();
                popupCenter("../Showlog.php?num=" + num + "&workitem=" + tablename, '로그기록 보기', 500, 500);
            });
						
			// 차량번호 변경 시 월간 누적 주행거리 가져오기
			$("#car_number").off("change").on("change", function () {
				let carNumber = $(this).val();
				let num = $("#num").val();
				if (carNumber) {
					$.ajax({
						url: "getMonthlydriving.php",
						type: "GET",
						data: { car_number: carNumber, num : num },
						dataType: "json",
						success: function (response) {
                            // console.log('response ajax :', response )
							let totalDistance = response.total_distance !== undefined ? response.total_distance : 0;							
                            let monthly_distance = response.monthly_distance !== undefined ? response.monthly_distance : 0;
                            let drivingDistance = $("#driving_distance").val() || 0;

                            let total = monthly_distance + drivingDistance;
                            console.log('total :', total )
							$("#arrival_cumulative_distance").val(total.toLocaleString('en-US', {minimumFractionDigits: 0, maximumFractionDigits: 0}));						
							
							// ✅ 차량번호가 변경된 후 주행거리 값을 다시 계산하도록 `trigger` 실행
							$("#driving_distance").trigger("input");
						},
						error: function () {
							console.error("월간 주행 거리 조회 오류");
						}
					});
				}
			});

			// 주행거리 입력 시 월간 누적 주행거리 업데이트
			$("#driving_distance").off("input").on("input", function () {
				let drivingDistance = parseFloat($(this).val()) || 0;

				let carNumber = $("#car_number").val();
				let num = $("#num").val();
				if (carNumber) {
					$.ajax({
						url: "getMonthlydriving.php",
						type: "GET",
						data: { car_number: carNumber, num : num },
						dataType: "json",
						success: function (response) {
							let totalDistance = response.total_distance !== undefined ? response.total_distance : 0;	
							let monthly_distance = response.monthly_distance !== undefined ? response.monthly_distance : 0;
							console.log('car_number ajax :', carNumber )
							console.log('월간주행거리 누계 ajax :', monthly_distance )
							console.log('총주행거리 ajax :', totalDistance )

							// let total = monthly_distance + drivingDistance;
							let total = monthly_distance + drivingDistance;
							//$("#arrival_cumulative_distance").val(total.toFixed(2));
                            $("#arrival_cumulative_distance").val(total.toLocaleString('en-US', {minimumFractionDigits: 0, maximumFractionDigits: 0}));						
						},
						error: function () {
							console.error("월간 주행 거리 조회 오류");
						}
					});
				}                
			});
		
            // 주행거리 자동계산 트리거 실행
            $("#driving_distance").click().trigger("input");

            let isSaving = false;

            // 저장 버튼 이벤트
            $("#saveBtn").off("click").on("click", function () {
                if (isSaving) return;
                isSaving = true;

                var formData = new FormData($("#board_form")[0]);

                $.ajax({
                    url: "insert.php",
                    type: "post",
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (response) {
                        Toastify({
                            text: "저장완료",
                            duration: 3000,
                            close: true,
                            gravity: "top",
                            position: "center",
                            backgroundColor: "#4fbe87",
                        }).showToast();

                        setTimeout(function () {
                            $("#myModal").hide();
                            location.reload();
                        }, 2000);
                    },
                    error: function (jqxhr, status, error) {
                        console.log(jqxhr, status, error);
                        isSaving = false;
                    }
                });
            });

            // 출발↔도착 변경 복사 버튼 이벤트
            $("#copyDestinationBtn").off("click").on("click", function () {
                var num = $("#num").val();
                $("#myModal").hide();
                setTimeout(function () {
                    loadForm("copyDestination", num);
                }, 500);
            });

            // 복사 버튼 이벤트
            $("#copyBtn").off("click").on("click", function () {
                var num = $("#num").val();
                $("#myModal").hide();
                setTimeout(function () {
                    loadForm("copy", num);
                }, 500);
            });

            // 삭제 버튼 이벤트
            $("#deleteBtn").off("click").on("click", function () {
                Swal.fire({
                    title: '자료 삭제',
                    text: "삭제는 신중! 정말 삭제하시겠습니까?",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: '삭제',
                    cancelButtonText: '취소'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $("#mode").val('delete');
                        var formData = $("#board_form").serialize();

                        $.ajax({
                            url: "insert.php",
                            type: "post",
                            data: formData,
                            success: function (response) {
                                Toastify({
                                    text: "파일 삭제완료",
                                    duration: 2000,
                                    close: true,
                                    gravity: "top",
                                    position: "center",
                                    style: {
                                        background: "linear-gradient(to right, #00b09b, #96c93d)"
                                    },
                                }).showToast();

                                $("#myModal").hide();
                                location.reload();
                            },
                            error: function (jqxhr, status, error) {
                                console.log(jqxhr, status, error);
                            }
                        });
                    }
                });
            });
        },
        error: function (jqxhr, status, error) {
            console.log("AJAX Error: ", status, error);
        }
    });
}

function loadInitialDistanceModal() {
    $.ajax({
        type: "POST",
        url: "fetch_initial_distance.php",
        dataType: "html",
        success: function(response) {
            document.querySelector(".initial-distance-card").innerHTML = response;
            $("#initialDistanceModal").show();

            // 모달 닫기 버튼
            $("#initialDistanceModal .close, #closeInitialDistanceBtn").off("click").on("click", function () {
                $("#initialDistanceModal").hide();
            });

            // 개별 저장 버튼 이벤트
            $(".save-initial-distance").off("click").on("click", function () {
                var vehicleNumber = $(this).data("vehicle");
                var initialDistance = $(".initial-distance-input[data-vehicle='" + vehicleNumber + "']").val();
                
                if (!initialDistance || initialDistance < 0) {
                    Toastify({
                        text: "유효한 주행거리를 입력해주세요.",
                        duration: 3000,
                        close: true,
                        gravity: "top",
                        position: "center",
                        backgroundColor: "#ff6b6b",
                    }).showToast();
                    return;
                }

                $.ajax({
                    url: "save_initial_distance.php",
                    type: "POST",
                    data: {
                        vehicle_number: vehicleNumber,
                        initial_distance: initialDistance
                    },
                    dataType: "json",
                    success: function (response) {
                        if (response.success) {
                            Toastify({
                                text: response.message,
                                duration: 3000,
                                close: true,
                                gravity: "top",
                                position: "center",
                                backgroundColor: "#4fbe87",
                            }).showToast();
                            
                            // 저장 버튼을 비활성화하여 중복 저장 방지
                            $(".save-initial-distance[data-vehicle='" + vehicleNumber + "']").prop('disabled', true);
                        } else {
                            Toastify({
                                text: response.message,
                                duration: 3000,
                                close: true,
                                gravity: "top",
                                position: "center",
                                backgroundColor: "#ff6b6b",
                            }).showToast();
                        }
                    },
                    error: function (jqxhr, status, error) {
                        console.log("AJAX Error: ", status, error);
                        Toastify({
                            text: "저장 중 오류가 발생했습니다.",
                            duration: 3000,
                            close: true,
                            gravity: "top",
                            position: "center",
                            backgroundColor: "#ff6b6b",
                        }).showToast();
                    }
                });
            });

            // 입력값 변경 시 저장 버튼 활성화
            $(".initial-distance-input").off("input").on("input", function () {
                var vehicleNumber = $(this).data("vehicle");
                $(".save-initial-distance[data-vehicle='" + vehicleNumber + "']").prop('disabled', false);
            });
        },
        error: function (jqxhr, status, error) {
            console.log("AJAX Error: ", status, error);
            Toastify({
                text: "모달 로드 중 오류가 발생했습니다.",
                duration: 3000,
                close: true,
                gravity: "top",
                position: "center",
                backgroundColor: "#ff6b6b",
            }).showToast();
        }
    });
}

// summary-row tr 클릭 시 사용목적별 통계 모달 표시 함수
function showPurposeStats(row) {
    var $row = $(row);
    var vehicle = $row.data('vehicle');
    var user = $row.data('user');
    var department = $row.data('department');
    var position = $row.data('position');
    var vehicletype = $row.data('vehicletype');
    var monthlydistance = Math.floor($row.data('monthlydistance').toString().replace(/,/g, '')).toLocaleString(); // 콤마 제거 후 소수점 제거, 다시 콤마 추가
    var totalcumulative = Math.floor($row.data('totalcumulative').toString().replace(/,/g, '')).toLocaleString(); // 콤마 제거 후 소수점 제거, 다시 콤마 추가
    var fromdate = $('#fromdate').val();
    var todate = $('#todate').val();

    // 상단 요약 테이블 HTML
    var infoTable = `
        <table class="table table-bordered mb-3">
            <tr>
                <th>사용자</th>
                <td>${user}</td>
                <th>부서</th>
                <td>${department}</td>
                <th>직위</th>
                <td>${position}</td>
            </tr>
            <tr>
                <th>차종</th>
                <td>${vehicletype}</td>
                <th>차량번호</th>
                <td>${vehicle}</td>
                <th>기간주행거리</th>
                <td>${monthlydistance}</td>
            </tr>
            <tr>
                <th>총누적주행거리</th>
                <td colspan="5">${totalcumulative}</td>
            </tr>
        </table>
    `;

    $.ajax({
        url: 'usage_purpose_stats.php',
        type: 'POST',
        data: {
            vehicle: vehicle,
            user: user,
            fromdate: fromdate,
            todate: todate
        },
        dataType: 'html',
        success: function(response) {
            $('.custom-purpose-stats').html(infoTable + response);
            $('#purposeStatsModal').show();
        }
    });
}

</script>

</body>
</html>