var ajaxRequest5 = null;

$(document).ready(function() {
    let todo_currentMonth = new Date().getMonth();
    let todo_currentYear = new Date().getFullYear();

    function todo_fetchCalendarData(month, year) {
		var search = $('#searchTodo').val(); 
		// 선택된 라디오 버튼 정보를 배열로 변환 (_all 제외)
		var radioarray = [];
		$('.filter-radio').each(function(index) {
			// console.log(`index ${index}`); // 템플릿 리터럴 수정
			var id = $(this).attr('id');
			if (id) {
				var splitItem = id.split('_')[1]; // "_"로 분리하여 두 번째 요소 가져오기
				if (splitItem && splitItem !== 'all') { // 'all'은 제외
					radioarray.push(splitItem); // 배열에 추가
				}
			}
		});	
		
		// 필터에 따라 데이터 표시
		let selectedFilter = $('input[name="filter"]:checked').attr('id');	
		// let filteredData = filterDataByProcess(response.todo_data, selectedFilter);	

		// radioarray 결과 확인
		// console.log(radioarray);	
			
		// showWaitingModal();
		ajaxRequest5 = $.ajax({
            url: "/todo/fetch_todo.php",
            type: "post",
            data: { month: month + 1, year: year, selectedFilter : selectedFilter, search : search, radioarray : radioarray },
            dataType: "json",
			success: function(response) {                			
			      // console.log(response);
                let calendarHtml = todo_generateCalendarHtml(
                    response.leave_data,
                    response.holiday_data,
                    response.todo_data,
                    response.shutter_data,
                    response.registration_data,
                    selectedFilter  
                );				

                $('#todo-calendar-container').html(calendarHtml);					
				
					var showTodoView = getCookie("showTodoView");
					var todoCalendarContainer = $("#todo-list");
					if (showTodoView === "show") {
						todoCalendarContainer.css("display", "inline-block");
					} else {
						todoCalendarContainer.css("display", "none");
					}		
					
			// 검색 결과를 부트스트랩 테이블로 렌더링
			if (search && response.integratedData.length > 0) {
				$('#todosMain-list').empty();
				renderTodosMainTable(response.integratedData);
			} else if (search) {
				$('#todosMain-list').html('<p class="text-center">검색 결과가 없습니다.</p>');
			} else
			  {
				$('#todosMain-list').empty();  
			  }					

			ajaxRequest5 = null;
			hideSavingModal();					
				
            },
            error: function() {
                console.log('Failed to fetch data');
				ajaxRequest5 = null;
				hideSavingModal();
            }
        });
    }
		
// 테이블 생성 함수
function renderTodosMainTable(data) {
    let tableHtml = `
    <table class="table table-bordered table-hover">
        <thead class="table-secondary">
            <tr>
                <th class="text-center" style="width:100px;">구분</th>                                    
                <th class="text-center" style="width:100px;">접수일</th>                    
                <th class="text-center" style="width:100px;">출고일</th>                    
                <th class="text-center text-primary" style="width:200px;">발주처</th>                    
                <th class="text-center">현장명</th>
                <th class="text-center">주소</th>
            </tr>
        </thead>
        <tbody>
    `;

    data.forEach(item => {
        // item.table 값에 따라 텍스트 변경
        let tableType = '-';
        if (item.table === 'shutter') {
            tableType = '<span class="badge bg-primary"> ' + item.secondord + ' </span>';
        } else if (item.table === 'registration') {
            tableType = '<span class="badge bg-secondary"> ' + item.secondord + ' </span>';
        } else if (item.table === 'outorder') {
            tableType = '<span class="badge bg-info"> 외주 </span>';
        }

        tableHtml += `
        <tr data-num="${item.num}" data-table="${item.table}" class="todosMain-row" style="cursor:pointer;">
            <td class="text-center">${tableType}</td>                            
            <td class="text-center">${item.indate || '-'}</td>
            <td class="text-center">${item.outdate || '-'}</td>
            <td class="text-center text-primary">${item.secondord || '-'}</td>
            <td class="text-center">${item.outworkplace || '-'}</td>
            <td class="text-center">${item.receiver || '-'}</td>
        </tr>
        `;
    });

    tableHtml += `</tbody></table>`;
    $('#todosMain-list').html(tableHtml);
}	

// 테이블 행 클릭 시 모달 표시
$('#todosMain-list').on('click', '.todosMain-row', function () {
    let num = $(this).data('num');
    let table = $(this).data('table');

    if (num && table) {
        let url = '';
        let title = '';

        // 테이블에 따라 적절한 URL 및 타이틀 설정
        if (table === 'output') {
            url = '../output/write_form.php?tablename=output&mode=view&num=' + num;
            title = '수주내역';
        } else if (table === 'indate') {
            url = '../output/write_form.php?tablename=output&mode=view&num=' + num;
            title = '수주내역';
        } else if (table === 'outorder') {
            url = '../outorder/view.php?menu=no&num=' + num;
            title = '외주 내역';
        }
		
        if (url) {
            popupCenter(url, title, 1900, 950);
        }
    }
});

function filterDataByProcess(data, selectedFilter) {
    if (selectedFilter === "filter_all") {
        return data; // 전체 데이터 반환
    }

	const processMapping = {
		filter_all: "전체",
		filter_al: "연차",
		filter_registration: "접수",
		filter_shutter: "출고",
		filter_etc: "기타"
	};

    const selectedProcess = processMapping[selectedFilter];
    if (!selectedProcess) return [];
}	


// ① 연차 HTML 생성 함수
function generateLeaveHtml(leaveDataForDay) {
    const maxDisplay = 1;                           // 화면에 바로 보여줄 개수
    const total = leaveDataForDay.length;           
    let html = `<div class="leave-container" style="position:relative;">`;
    
    // ② 앞쪽 maxDisplay개는 바로 출력
    leaveDataForDay.slice(0, maxDisplay).forEach(item => {
      html += `
        <div class="leave-info text-start" style="border:1px dashed brown; padding:2px 4px;">
          <span class="text-secondary">
            ${item.author} (<i class="bi bi-tree-fill"></i>${item.al_item})
          </span>
        </div>`;
    });
  
    // ③ 남는 항목이 있으면 축약 표시 + 숨겨진 목록 생성
    if (total > maxDisplay) {
      const remaining = total - maxDisplay;
      html += `
        <div class="leave-info leave-more text-danger fw-bold" 
             style="cursor:pointer; padding:2px 4px;">
          (연차) 위 신청외 ${remaining}건
        </div>
        <div class="leave-more-list" 
             style="display:none;position:absolute; top:100%; left:0; z-index:10;
                    background:#fff; border:1px solid #ccc; box-shadow:0 2px 6px rgba(0,0,0,0.1);">
      `;
      leaveDataForDay.slice(maxDisplay).forEach(item => {
        html += `
          <div class="leave-info text-start" style="border-bottom:1px dashed #eee; padding:2px 4px; width:150px; ">
            <span class="text-secondary">
              ${item.author} (<i class="bi bi-tree-fill"></i>${item.al_item})
            </span>
          </div>`;
      });
      html += `</div>`;
    }
  
    html += `</div>`;
    return html;
  }

function todo_generateCalendarHtml(leaveData, holidayData, todoData, shutterData, registrationData, selectedFilter) {
    const daysOfWeek = ['일', '월', '화', '수', '목', '금', '토'];
    let date = new Date(todo_currentYear, todo_currentMonth, 1);
    let firstDay = date.getDay();
    let lastDate = new Date(todo_currentYear, todo_currentMonth + 1, 0).getDate();
    let today = new Date();

    let todayYear = today.getFullYear();
    let todayMonth = today.getMonth();
    let todayDate = today.getDate();

    function convertToKST(dateString) {
        const utcDate = new Date(dateString + 'T00:00:00Z');
        const kstDate = new Date(utcDate.getTime() + 9 * 60 * 60 * 1000);
        kstDate.setHours(0, 0, 0, 0);
        return kstDate;
    }

    function truncateWorkplaceName(name, maxLength = 15) {
        return name.length > maxLength ? name.substring(0, maxLength) + '...' : name;
    }

    let calendarHtml = '<table id="todo-list" class="table text-center">';
    calendarHtml += '<thead class="table-primary text-start"><tr>';
    daysOfWeek.forEach((day) => {
        let width = (day === '일' || day === '토') ? '5.8%' : '17.2%';
        let textClass = (day === '일' || day === '토') ? 'text-danger' : '';
        calendarHtml += `<th class="fs-6 text-start ${textClass}" style="width: ${width};">${day}</th>`;
    });
    calendarHtml += '</tr></thead><tbody>';

    let day = 1;
    for (let i = 0; i < 6; i++) {
        calendarHtml += '<tr>';
        for (let j = 0; j < 7; j++) {
            if (i === 0 && j < firstDay || day > lastDate) {
                calendarHtml += '<td class="text-start"></td>';
            } else {
                let currentDate = new Date(todo_currentYear, todo_currentMonth, day);
                currentDate.setHours(0, 0, 0, 0);

                let dayData = todoData.filter(item => new Date(item.orderdate).toDateString() === currentDate.toDateString());
                let leaveDataForDay = leaveData.filter(item => {
                    let leaveStart = convertToKST(item.al_askdatefrom);
                    let leaveEnd = convertToKST(item.al_askdateto);
                    return currentDate >= leaveStart && currentDate <= leaveEnd;
                });

                let holidayForDay = holidayData.filter(item => {
                    let startDate = convertToKST(item.startdate);
                    let endDate = item.enddate && item.enddate !== '0000-00-00' ? convertToKST(item.enddate) : startDate;
                    return currentDate >= startDate && currentDate <= endDate;
                });

                let registrationforData = registrationData.filter(item => new Date(item.indate).toDateString() === currentDate.toDateString());
                let shutterforData = shutterData.filter(item => new Date(item.outdate).toDateString() === currentDate.toDateString());
                
                let dayClass = '';
                if (j === 0 || j === 6) dayClass += ' red-day';
                if (currentDate.toDateString() === today.toDateString()) dayClass += ' today-bg';
                if (holidayForDay.length > 0) dayClass += ' text-danger';

                calendarHtml += `
                    <td class="${dayClass}">
                        <div class="d-flex me-4"> 
                        <div class="fw-bold fs-6 dayHead" 
                             data-date='${formatLocalDate(currentDate)}'
                             data-todo='${JSON.stringify(dayData)}' 
                             data-leave='${JSON.stringify(leaveDataForDay)}' 
                             data-holiday='${JSON.stringify(holidayForDay)}'
                             data-registration='${JSON.stringify(registrationforData)}' 
                             data-shutter='${JSON.stringify(shutterforData)}' >
                            ${day} 
                        </div> &nbsp;&nbsp; <button type="button" data-date='${formatLocalDate(currentDate)}' class="event btn btn-outline-dark btn-sm ms-1" style="border:0px;"> 
                            <i class="bi bi-plus"></i></button> </div>`;

                // 휴일 표시
                holidayForDay.forEach(item => {
                    calendarHtml += `<div class="justify-content-start  text-start"  ><span class='badge bg-danger'>${item.comment}</span></div>`;
                });

				// 두번째행 공지사항
                dayData.forEach(item => {
                    let workStatus = item.work_status === '완료' ? '<span class="badge bg-danger">완료</span>' : '';
                    calendarHtml += `
                        <div class="justify-content-start  text-start todo-event event" data-id="${item.num}">
                            ${item.towhom ? `<span class="text-dark mx-1 mb-2 mt-2">${item.towhom}</span>` : ''}
                            ${item.title ? `<h6> <span class="text-primary mx-1 mb-2 mt-2"> <i class="bi bi-megaphone"></i> ${item.title}</span> </h6>` : ''}
                            ${workStatus}
                        </div>`;
                });
				// 세번째행 연차휴가
				// leaveDataForDay.forEach(item => {
				// 	if(j != 0 && j != 6) { // 토요일, 일요일 제외
				// 		calendarHtml += `<div class="leave-info justify-content-start  text-start" style="border: 1px dashed brown;"><span class="text-secondary">${item.author} (<i class="bi bi-tree-fill"></i>${item.al_item})</span></div>`;
				// 	}
				// });

                // 주말(토,일)이 아니고 휴일이 아닌 경우에만 generateLeaveHtml 호출
                if (j !== 0 && j !== 6 && holidayForDay.length === 0) {
                    const leaveHtml = generateLeaveHtml(leaveDataForDay);
                    calendarHtml += leaveHtml;
                }

                // 해당날짜의 접수 표시
                registrationforData.forEach(item => {
                    // 원본 값
                    let title = item.secondord;
                    let placeName = item.outworkplace;

                    // combined 길이 체크 후 축약
                    if ((title.length + placeName.length) > 20) {
                        title = title.length > 8
                            ? title.substring(0, 8) + '..'
                            : title;
                        placeName = placeName.length > 8
                            ? placeName.substring(0, 8) + '..'
                            : placeName;
                    }

                    // 화면에 표시할 작업장 이름
                    const outworkplace = placeName;

                    // 기본 HTML 구조 시작
                    calendarHtml +=
                    `<div style="font-size:11px;" class="registration-event text-start justify-content-start" ` +
                    `title="${item.outworkplace}" data-id="${item.num}">`;

                    // 배지(순서)
                    calendarHtml += `<span class="badge bg-secondary">${title}</span>`;

                    // 조건에 따른 텍스트 색상 및 스타일
                    if (item.indate && item.indate !== '0000-00-00') {
                        calendarHtml += `<span class="text-dark">${outworkplace}</span>`;
                    } else {
                        calendarHtml += `<span class="text-secondary fw-bold">${outworkplace}</span>`;
                    }

                    // 기본 HTML 구조 종료
                    calendarHtml += '</div>';
                });


                // 해당날짜의 출고 표시
                shutterforData.forEach(item => {
                    // 원본 값
                    let title = item.secondord;
                    let placeName = item.outworkplace;

                    // combined 길이 체크 후 축약 (합이 20자 초과 시)
                    if ((title.length + placeName.length) > 20) {
                        title = title.length > 8
                            ? title.substring(0, 8) + '..'
                            : title;
                        placeName = placeName.length > 8
                            ? placeName.substring(0, 8) + '..'
                            : placeName;
                    }

                    // 화면에 표시할 작업장 이름
                    const outworkplace = placeName;

                    // 기본 HTML 구조 시작
                    calendarHtml +=
                    `<div style="font-size:11px;" class="shutter-event text-start justify-content-start" ` +
                    `title="${item.outworkplace}" data-id="${item.num}">`;

                    // 배지(순서)
                    calendarHtml += `<span class="badge bg-success">${title}</span>`;

                    // 조건에 따른 텍스트 색상 및 스타일
                    if (item.outdate && item.outdate !== '0000-00-00') {
                        calendarHtml += `<span class="text-secondary">${outworkplace}</span>`;
                    } else {
                        calendarHtml += `<span class="text-success fw-bold">${outworkplace}</span>`;
                    }

                    // 기본 HTML 구조 종료
                    calendarHtml += '</div>';
                });


                calendarHtml += '</td>';
                day++;
            }
        }
        calendarHtml += '</tr>';
    }

    calendarHtml += '</tbody></table>';

    $('#todo-current-period').text(`${todo_currentYear}/${('0' + (todo_currentMonth + 1)).slice(-2)}`);
    return calendarHtml;
}

// 요소 클릭 이벤트 추가
$('#dayModal').on('click', '.todo-event', function () {
    let num = $(this).data('id');
    let date = $(this).data('date');
    loadForm(num, date);
});

$('#dayModal').on('click', '.registration-event', function () {
    let num = $(this).data('id');
    popupCenter('../output/write_form.php?tablename=output&mode=view&num=' + num, '수주 내역', 1900, 950);
});

$('#dayModal').on('click', '.shutter-event', function () {
    let num = $(this).data('id');
    popupCenter('../output/write_form.php?tablename=output&mode=view&num=' + num, '수주 내역', 1900, 950);
});

$('#todo-calendar-container').on('click', '.event', function() {
	let num = $(this).data('id');
	let date = $(this).data('date');
	loadForm(num, date);
});

$('#todo-calendar-container').on('click', '.registration-event', function() {
	let num = $(this).data('id');
	 popupCenter('../output/write_form.php?tablename=output&mode=view&num=' + num  , '수주 내역', 1900, 950);	
});

$('#todo-calendar-container').on('click', '.shutter-event', function() {
	let num = $(this).data('id');
	 popupCenter('../output/write_form.php?tablename=output&mode=view&num=' + num  , '수주 내역', 1900, 950);	
});

function loadForm(num, date) {
    let mode = num == 'undefined' ||  num ==  null ? 'insert' : 'update';
    // console.log(date);
        console.log(num);
        console.log(mode);
        $("#mode").val(mode);
        $("#num").val(num);
    $.ajax({
        type: "POST",
        url: "/todo/fetch_modal.php",
        data: { mode: mode, num: num, seldate : date },
        dataType: "html",
        success: function(response) {                
            document.querySelector(".modal-body .custom-card").innerHTML = response;
            $("#todoModal").show();

            
            $(".todo-close, .modal-close-btn").off('click').on('click', function() {
                $("#todoModal").hide(); // 제이쿼리 모달 닫기 함수
            });

            // Bootstrap's data-dismiss="modal" handles modal closing automatically
            // Removed custom click handlers to prevent conflicts

            // Log 파일보기
            $("#showlogBtn").click( function() {     	
                var num	= $("#num").val();
                // table 이름을 넣어야 함
                var workitem =  'todos' ;
                // 버튼 비활성화
                var btn = $(this);						
                    popupCenter("/Showlog.php?num=" + num + "&workitem=" + workitem , '로그기록 보기', 500, 500);									 
                btn.prop('disabled', false);					 					 
            });	

            // 요청처리일을 입력하면 진행상태를 '완료'로 변경하고, 날짜를 지우면 '작성'으로 변경
            $('#deadline').change(function() {
                if ($(this).val()) {
                    $('#work_status').val('완료');
                } else {
                    $('#work_status').val('작성');
                }
            });

            // 저장 버튼
            $("#saveBtn").off('click').on("click", function() {
                var formData = $("#board_form").serialize();

                $.ajax({
                    url: "/todo/process.php",
                    type: "post",
                    data: formData,
                    success: function(response) {
                        // console.log(response);
                        Toastify({
                            text: "저장완료",
                            duration: 3000,
                            close: true,
                            gravity: "top",
                            position: "center",
                            backgroundColor: "#4fbe87",
                        }).showToast();
                        $("#todoModal").hide();
                        todo_fetchCalendarData(todo_currentMonth, todo_currentYear); // 변경된 데이터만 다시 로드
                    },
                    error: function(jqxhr, status, error) {
                        console.log(jqxhr, status, error);
                    }
                });
            });

            // 삭제 버튼
            $("#deleteBtn").off('click').on("click", function() {                    
                var user_name = $("#user_name").val();
                var first_writer = $("#first_writer").val();

                if (user_name !== first_writer) {
                    Swal.fire({
                        title: '삭제불가',
                        text: "작성자만 삭제 가능합니다.",
                        icon: 'error',
                        confirmButtonText: '확인'
                    });
                    return;
                }

                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: "/todo/process.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();

                                $("#todoModal").hide();
                                todo_fetchCalendarData(todo_currentMonth, todo_currentYear); // 변경된 데이터만 다시 로드
                            },
                            error: function(jqxhr, status, error) {
                                console.log(jqxhr, status, error);
                            }
                        });
                    }
                });
            });
        
            // 체크박스 클릭시 처리
                function updateApproversInput() {
                    let approvers = [];
                    $('.approver-checkbox:checked').each(function() {
                        approvers.push($(this).data('user-name'));
                    });
                    $('#towhom').val(approvers.join(', '));
                }

                $('.approver-checkbox').change(function() {
                    updateApproversInput();
                });

                // 기존에 선택된 사용자를 반영합니다.
                let selectedApprovers = $('#towhom').val().split(', ');
                $('.approver-checkbox').each(function() {
                    if (selectedApprovers.includes($(this).data('user-name'))) {
                        $(this).prop('checked', true);
                    }
                });				
        
        },
        error: function(jqxhr, status, error) {
            console.log("AJAX Error: ", status, error);
        }
    });
}
	
	
// 로컬 날짜를 YYYY-MM-DD 형식으로 반환하는 함수
function formatLocalDate(date) {
    const year = date.getFullYear();
    const month = ('0' + (date.getMonth() + 1)).slice(-2); // 월은 0부터 시작하므로 +1
    const day = ('0' + date.getDate()).slice(-2);
    return `${year}-${month}-${day}`;
}

// 클릭 이벤트와 모달 표시
$(document).on('click', '.dayHead', function () {
    const selectedDate = $(this).data('date');
    let todoData = $(this).data('todo') || [];
    const leaveData = $(this).data('leave') || [];
    const shutterData = $(this).data('shutter') || [];
    const registrationData = $(this).data('registration') || [];
    
    console.log(`선택된 날짜: ${selectedDate}`);
    console.log('Todo 데이터:', todoData);
    console.log('Leave 데이터:', leaveData);
    console.log('shutter 데이터:', shutterData);
    console.log('registration 데이터:', registrationData);
    
    // JSON 파싱 처리
    try {
        todoData = typeof todoData === 'string' ? JSON.parse(todoData.replace(/[\r\n\t]/g, '')) : todoData;
    } catch (e) {
        console.error("todoData를 JSON으로 파싱하는 중 오류 발생:", e);
        todoData = []; // 파싱 실패 시 빈 배열로 설정
    }

    let modalContent = `<h4 class="fw-bold mb-4">${selectedDate} 일정</h4>`;
    if (todoData.length > 0 || leaveData.length > 0 || shutterData.length > 0  || registrationData.length > 0 ) {
        modalContent += '<ul class="list-group">';

        if (leaveData.length > 0) {
            modalContent += `<li class="list-group-item bg-dark text-light">연차 사용</li>`;
            leaveData.forEach(item => {
                modalContent += `
                    <li class="list-group-item leave-event" data-id="${item.num}" data-date="${selectedDate}">
                        <strong>${item.author}</strong><br>
                    </li>`;
            });
        }
        if (todoData.length > 0) {
            modalContent += `<li class="list-group-item bg-primary text-light">해야할일</li>`;
            todoData.forEach(item => {
                modalContent += `
                    <li class="list-group-item todo-event" data-id="${item.num}" data-date="${selectedDate}">
                        <strong>${item.title || '제목 없음'}</strong><br>
                    </li>`;
            });
        }
        if (registrationData.length > 0) {
            modalContent += `<li class="list-group-item bg-secondary text-light">접수내역</li>`;
            registrationData.forEach(item => {
                modalContent += `
                    <li class="list-group-item registration-event" data-id="${item.num}">
                        <strong>${item.outworkplace}</strong><br>
                    </li>`;
            });
        }
        if (shutterData.length > 0) {
            modalContent += `<li class="list-group-item bg-success text-light">수주내역</li>`;
            shutterData.forEach(item => {
                modalContent += `
                    <li class="list-group-item shutter-event" data-id="${item.num}">
                        <strong>${item.outworkplace}</strong><br>
                    </li>`;
            });
        }

        modalContent += '</ul>';
    } else {
        modalContent += '<p class="text-muted">이 날짜에 데이터가 없습니다.</p>';
    }
	
    $('#dayModal .modal-body').html(modalContent).css('font-size', '20px'); // 글자 크기 설정
    $('#dayModal').modal('show');
});

$('#dayModal').on('shown.bs.modal', function () {
    $(document).on('mouseenter', '.list-group-item', function () {
        $(this).css({
            'box-shadow': '0 .125rem .25rem rgba(0, 0, 0, .075)',
            'transition': 'box-shadow 0.2s ease-in-out',
            'cursor': 'pointer'
        });
    }).on('mouseleave', '.list-group-item', function () {
        $(this).css({
            'box-shadow': 'none'
        });
    });
});


    $('#todo-prev-month').click(function() {
        todo_currentMonth--;
        if (todo_currentMonth < 0) {
            todo_currentMonth = 11;
            todo_currentYear--;
        }
        todo_fetchCalendarData(todo_currentMonth, todo_currentYear);
    });

    $('#todo-next-month').click(function() {
        todo_currentMonth++;
        if (todo_currentMonth > 11) {
            todo_currentMonth = 0;
            todo_currentYear++;
        }
        todo_fetchCalendarData(todo_currentMonth, todo_currentYear);
    });

    $('#todo-current-month').click(function() {
        todo_currentMonth = new Date().getMonth();
        todo_currentYear = new Date().getFullYear();
        todo_fetchCalendarData(todo_currentMonth, todo_currentYear);
    });
	

   // 초기 라디오 버튼 상태 설정 및 필터 변경 이벤트
    function initializeRadioButtons() {
        let selectedFilter = getCookie("todoFilter") || 'filter_all';
        $('#' + selectedFilter).prop('checked', true);
        todo_fetchCalendarData(todo_currentMonth, todo_currentYear);
    }
	
	// 일정검색시
	$('#searchTodoBtn').off('click').on('click', function () {
		var search = $('#searchTodo').val();		
		// console.log(search);
		todo_fetchCalendarData(todo_currentMonth, todo_currentYear, search);
	});	

	// 라디오 버튼 변경 이벤트 핸들러
	$('input[name="filter"]').on('change', function () {
		let selectedFilter = $('input[name="filter"]:checked').attr('id');
		setCookie("todoFilter", selectedFilter, 10);
		var search = $('#searchTodo').val();
		// console.log(search);
		todo_fetchCalendarData(todo_currentMonth, todo_currentYear, search);
	});	

	// 팝업 창 열기 함수
	function popupCenter(url, title, w, h) {
		const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;
		const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;

		const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
		const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;

		const left = (width / 2) - (w / 2) + dualScreenLeft;
		const top = (height / 2) - (h / 2) + dualScreenTop;
		const newWindow = window.open(url, title, `scrollbars=yes, width=${w}, height=${h}, top=${top}, left=${left}`);

		if (window.focus) newWindow.focus();
	}
		

    //todo_fetchCalendarData(todo_currentMonth, todo_currentYear);
	// 초기 필터 위치가 저장된 곳을 보여준다. 달력 필터 라디오버튼
	initializeRadioButtons();
    
});

// ⑤ 마우스 hover 이벤트 (jQuery) 연차리스트에 마우스를 올리면 나타나는 효과
$(document)
  .on('mouseenter', '.leave-container', function() {
    $(this).find('.leave-more-list')
           .stop(true,true)
           .slideDown(100);
  })
  .on('mouseleave', '.leave-container', function() {
    $(this).find('.leave-more-list')
           .stop(true,true)
           .slideUp(100);
  });