<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.io.*"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ include file="/jsp/common/include/localemessage.jsp" %>
<%
	response.setHeader("Pragma", "No-cache");
	response.setHeader("Cache-Control", "no-cache");
	response.setHeader("Expires", "0");
%>
<html>
<head>
	<title>Q&A 문의</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<jsp:include page="/jsp/common/include/css.jsp"/>
	<jsp:include page="/jsp/common/include/script.jsp"/>
	<style>
		.inquiry-section {
			margin-bottom: 15px;
			border: 1px solid #e0e0e0;
			padding: 20px;
			border-radius: 5px;
		}

		.response-section {
			margin-bottom: 30px;
			border: 1px solid #e0e0e0; /* 동일한 박스 스타일 */
			padding: 20px;
			border-radius: 5px;
		}

		.section-title {
			font-size: 18px;
			font-weight: bold;
			margin-bottom: 15px;
			padding-bottom: 10px;
			border-bottom: 2px solid #e0e0e0; /* 제목 아래 줄 긋기 */
		}
		
		.comment-section {
			margin-bottom: 30px;
			border: 1px solid #e0e0e0; /* 동일한 박스 스타일 */
			padding: 20px;
			border-radius: 5px;
		}

		.info-row {
			margin-bottom: 10px;
			display: flex;
		}

		.info-label {
			font-weight: bold;
			width: 80px;
		}

		.info-content {
			flex: 1;
			padding-left: 5px;
			border-radius: 4px;
		}

		#responseDetail {
			width: 100%;
			min-height: 200px;
		}
		
		#commentDetail {
			min-height: 100px;
			border: 1px solid #00000032;
			border-radius: 4px; 
			padding: 10px;
			flex: 1;
			font-family: '맑은고딕'
		}

		.required-mark {
			color: red;
			margin-left: 2px;
			font-weight: bold;
		}

		.reason-modal-overlay {
			display: none;
			position: fixed;
			top: 0; left: 0;
			width: 100%; height: 100%;
			background: rgba(0, 0, 0, 0.4);
			z-index: 1000;
		}
		.reason-modal-box {
			position: absolute;
			top: 50%; left: 50%;
			transform: translate(-50%, -50%);
			background: #fff;
			border-radius: 6px;
			padding: 20px;
			width: 400px;
			box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
		}
		.reason-modal-box h3 {
			margin: 0 0 12px;
			font-size: 16px;
		}
		.reason-modal-box textarea {
			width: 100%;
			min-height: 80px;
			box-sizing: border-box;
		}
		.reason-modal-actions {
			margin-top: 12px;
			text-align: right;
		}
	</style>
	<script language="javascript">
		var url = '<c:url value="/onl/apim/portalinquiry/portalInquiryMan.json" />';
		var url_view = '<c:url value="/onl/apim/portalinquiry/portalInquiryMan.view" />';
		var file_download = '<c:url value="/file/download.do" />';
		var inquiryStatus = 'PENDING';
		var originalVisibility = 'ORG';
		var reasonModalCallback = null;

		function decodeHTMLEntities(text) {
			var textArea = document.createElement('textarea');
			textArea.innerHTML = text;
			return textArea.value;
		}

		function detail(key) {
			$.ajax({
				type: "POST",
				url: url,
				dataType: "json",
				data: {cmd: 'DETAIL', id: key},
				success: function (data) {
										
					
					$("#id").val(key);
					
					$("#inquirySubject").text(data.inquirySubject);
					$("#inquiryDetail").html(data.inquiryDetail);
					
					inquiryStatus = data.inquiryStatus;
					if (data.inquiryStatus == 'PENDING') {
						$("#inquiryStatus").text('문의중');
					} else if (data.inquiryStatus == 'REVIEWING') {
						$("#inquiryStatus").text('문의검토중');
					} else if (data.inquiryStatus == 'RESPONDED') {
						$("#inquiryStatus").text('답변완료');
					} else if (data.inquiryStatus == 'CLOSED') {
						$("#inquiryStatus").text('답변종료');
					}
					$("#inquirer").text(data.inquirer.userName);
					$("#createdDate").text(timeStampFormat(data.createdDate));
					$("#responder").text(data.responderName || '');
					$("#responseDate").text(timeStampFormat(data.responseDate));

					var decodedContent = decodeHTMLEntities(data.responseDetail);
					$("#responseDetail").summernote('code', decodedContent || '');

					// 공개범위 / 조회수
					$('#visibilitySelect').val(data.visibility || 'ORG');
					originalVisibility = data.visibility || 'ORG';
					$('#viewCount').text(data.viewCount || 0);

					// 조회수 증가 (sessionStorage dedup — 새로고침 시 중복 증가 억제)
					var viewedKey = 'inquiry_viewed_' + key;
					if (!sessionStorage.getItem(viewedKey)) {
						$.ajax({
							type: "POST",
							url: url,
							data: {cmd: 'INCREMENT_VIEW', id: key},
							success: function () {
								sessionStorage.setItem(viewedKey, 'true');
							}
						});
					}

					// 댓글 표시
					listComment(key);

					// 첨부 파일 표시
					displayAttachFiles(data.fileInfo);

				},
				error: function (e) {
					alert(e.responseText);
				}
			});
		}
		
		function listComment(inquiryId) {
			$.ajax({
				type: "POST",
				url: url,
				dataType: "json",
				data: {cmd: 'LIST_COMMENT', id: inquiryId},
				success: function (data) {
					var $commentList = $('#commentList');
					$commentList.empty();
					if (!data || data.length === 0) return;
					$.each(data, function (i, comment) {
						var date = comment.createdDate ? timeStampFormat(comment.createdDate) : '';
						var isPrivate = comment.visibility === 'PRIVATE';
						var row = $('<div>').addClass('info-row');
						if (isPrivate) {
							// 비공개 댓글은 색상으로 구별
							row.css({'background-color': '#FFF5F5', 'border-radius': '4px', 'padding': '4px'});
						}
						var labelDiv = $('<div>').addClass('info-label').css('color', '#555').text(comment.writerName || '');
						if (isPrivate) {
							$('<span>').text(' 비공개').css({'color': '#c0392b', 'font-size': '0.85em', 'font-weight': 'bold'}).appendTo(labelDiv);
						}
						labelDiv.appendTo(row);
						var content = $('<div>').addClass('info-content');
						$('<div>').css('white-space', 'pre-wrap').text(comment.commentDetail).appendTo(content);
						var meta = $('<div>').css({'font-size': '0.9em', 'color': '#999', 'margin-top': '2px'});
						$('<span>').text(date).appendTo(meta);
						$('<button>').attr('type', 'button').addClass('cssbtn smallBtn2').css({'margin-left': '8px', 'font-size': '0.85em', 'padding': '1px 6px'})
							.text('delete').on('click', (function(id, inquiryId) {
								return function() { deleteComment(id, inquiryId); };
							})(comment.id, comment.inquiryId))
							.appendTo(meta);
						meta.appendTo(content);

						// 댓글 공개범위 변경 컨트롤 (사유 필수)
						var visCtrl = $('<div>').css({'margin-top': '4px', 'font-size': '0.85em'});
						var sel = $('<select>').append('<option value="ALL">공개</option>').append('<option value="PRIVATE">비공개</option>');
						sel.val(comment.visibility || 'ALL');
						var reasonInput = $('<input>').attr({'type': 'text', 'placeholder': '변경 사유'}).css({'margin-left': '4px'});
						var applyBtn = $('<button>').attr('type', 'button').addClass('cssbtn smallBtn2').css({'margin-left': '4px', 'font-size': '0.85em', 'padding': '1px 6px'})
							.text('공개범위변경').on('click', (function(id, inquiryId, selEl, reasonEl) {
								return function() { changeCommentVisibility(id, inquiryId, selEl.val(), reasonEl.val()); };
							})(comment.id, comment.inquiryId, sel, reasonInput));
						visCtrl.append(sel).append(reasonInput).append(applyBtn);
						visCtrl.appendTo(content);

						content.appendTo(row);
						row.appendTo($commentList);
					});
				},
				error: function (e) {
					alert(e.responseText);
				}
			});
		}

		function openReasonModal(callback) {
			reasonModalCallback = callback;
			$('#reasonModalInput').val('');
			$('#reasonModal').show();
			$('#reasonModalInput').focus();
		}

		function closeReasonModal() {
			$('#reasonModal').hide();
			reasonModalCallback = null;
		}

		// 답변(summernote) 내용이 실제로 입력됐는지 확인
		function hasAnswerContent() {
			var v = $('#responseDetail').summernote('code');
			var text = $('<div>').html(v || '').text().replace(/ /g, ' ').trim();
			return text.length > 0;
		}

		function saveInquiryAnswer(returnUrl) {
			var postData = $('#ajaxForm').serializeArray();
			postData.push({name: "cmd", value: "INSERT"});
			$.ajax({
				type: "POST",
				url: url,
				data: postData,
				success: function (json) {
					alert("<%= localeMessage.getString("common.saveMsg") %>");
					goNav(returnUrl);
				},
				error: function (e) {
					alert(e.responseText);
				}
			});
		}

		// 게시물 공개범위 변경(사유 필수). 성공 후 답변 내용이 있으면 이어서 저장.
		function changeInquiryVisibility(newVis, reason, returnUrl, thenSaveAnswer) {
			$.ajax({
				type: "POST",
				url: url,
				data: {cmd: 'VISIBILITY', serviceType: 'APIGW', targetType: 'INQUIRY', id: $('#id').val(),
					visibility: newVis, auditReason: reason},
				success: function () {
					originalVisibility = newVis;
					if (thenSaveAnswer) {
						saveInquiryAnswer(returnUrl);
					} else {
						alert('변경되었습니다.');
						goNav(returnUrl);
					}
				},
				error: function (e) {
					alert(e.responseText);
				}
			});
		}

		function changeCommentVisibility(commentId, inquiryId, visibility, reason) {
			if (!reason || !reason.trim()) {
				alert('공개범위 변경 사유를 입력하세요.');
				return;
			}
			if (!confirm('댓글 공개범위를 변경하시겠습니까?')) return;
			$.ajax({
				type: "POST",
				url: url,
				data: {cmd: 'VISIBILITY', serviceType: 'APIGW', targetType: 'COMMENT', id: commentId, visibility: visibility, auditReason: reason},
				success: function () {
					alert('변경되었습니다.');
					listComment(inquiryId);
				},
				error: function (e) {
					alert(e.responseText);
				}
			});
		}

		function deleteComment(commentId, inquiryId) {
			if (inquiryStatus == 'CLOSED') {
				alert('답변이 종료되어 삭제할 수 없습니다');
				return;
			}
			if (!confirm("댓글을 삭제하시겠습니까?")) return;
			$.ajax({
				type: "POST",
				url: url,
				data: {cmd: 'DELETE_COMMENT', id: commentId},
				success: function () {
					listComment(inquiryId);
				},
				error: function (e) {
					alert(e.responseText);
				}
			});
		}

		$(document).ready(function () {
			var returnUrl = getReturnUrlForReturn();
			var key = "${param.id}";

			// Summernote 에디터 초기화 (이미지 붙여넣기 data-uri 방식, 리사이징 지원)
			initSummernote('#responseDetail', {
				placeholder: '여기에 답변을 입력하세요.',
				height: 200
			});
			

			if (key) {
				detail(key);
			}

			$("#btn_modify").click(function () {
				if (inquiryStatus == 'CLOSED') {
					alert('답변이 종료되어 수정할 수 없습니다');
					return;
				}

				var newVis = $('#visibilitySelect').val();
				var visChanged = (newVis !== originalVisibility);

				if (visChanged) {
					// 공개범위 변경 감지 → 사유 입력 모달 (답변 내용이 있으면 함께 저장)
					var saveAnswerToo = hasAnswerContent();
					openReasonModal(function (reason) {
						changeInquiryVisibility(newVis, reason, returnUrl, saveAnswerToo);
					});
					return;
				}

				// 공개범위 변경 없음 → 기존 답변 저장
				if (!checkRequired("ajaxForm")) return;
				if (!confirm("<%= localeMessage.getString("common.checkSave")%>")) return;
				saveInquiryAnswer(returnUrl);
			});

			$("#reasonModalOk").click(function () {
				var reason = ($('#reasonModalInput').val() || '').trim();
				if (!reason) {
					alert('변경 사유를 입력하세요.');
					return;
				}
				var cb = reasonModalCallback;
				closeReasonModal();
				if (cb) cb(reason);
			});

			$("#reasonModalCancel").click(function () {
				closeReasonModal();
			});
			
			$("#btn_comment").click(function () {
				if (inquiryStatus == 'CLOSED') {
					alert('답변이 종료되어 댓글을 등록할 수 없습니다');
					return;
				}
				if (!confirm("<%= localeMessage.getString("common.checkSave")%>")) return;

				$.ajax({
					type: "POST",
					url: url,
					data: {
						cmd: "INSERT_COMMENT",
						inquiryId: $('#id').val(),
						commentDetail: $('#commentDetail').val(),
					},
					success: function (json) {
						alert("<%= localeMessage.getString("common.saveMsg") %>");
						$('#commentDetail').val('');
						listComment(key);
					},
					error: function (e) {
						alert(e.responseText);
					}
				});
			});

			$("#btn_previous").click(function () {
				goNav(returnUrl);
			});
		});

		function displayAttachFiles(fileInfo) {
			var $attachFileRow = $('#attachFileRow');
			var $attachFiles = $('#attachFiles');

			if (fileInfo && fileInfo.fileDetails && fileInfo.fileDetails.length > 0) {
				var attachFilesHtml = '';
				fileInfo.fileDetails.forEach(function(file) {
					attachFilesHtml += '<span style="cursor: pointer;" onclick="downloadFile(\'' + file.fileId + '\', \'' + file.fileSn + '\')">';
					attachFilesHtml += file.originalFileName + '.' + file.fileExtension;
					var iconPath = '${pageContext.request.contextPath}/images/icon_file.png';
					attachFilesHtml += '<img src="' + iconPath + '" style="vertical-align: middle; margin-left: 5px; height: 1.2em">';
					attachFilesHtml += '</span><br>';
				});
				$attachFiles.html(attachFilesHtml);
				$attachFileRow.show().css("cursor", "pointer");
			} else {
				$attachFileRow.hide();
			}
		}

		function downloadFile(fileId, fileSn) {
			window.location.href = file_download + '?fileId=' + fileId + '&fileSn=' + fileSn;
		}
	</script>
</head>
<body>
<div class="right_box">
<div class="content_top">
		<ul class="path">
			<li><a href="#">${rmsMenuPath}</a></li>
		</ul>
	</div>
	<div class="content_middle">
		<div class="search_wrap">
			<button type="button" class="cssbtn" id="btn_modify" level="W" status="DETAIL,NEW"><i class="material-icons">save</i> <%= localeMessage.getString("button.modify") %></button>
			<button type="button" class="cssbtn" id="btn_previous" level="R" status="DETAIL,NEW"><i class="material-icons">arrow_back</i> <%= localeMessage.getString("button.previous") %></button>
		</div>
		<div class="title">Q&A 상세</div>
		<form id="ajaxForm">
			<div class="inquiry-section">
				<div class="section-title" id="inquirySubject"></div>
				<div class="info-row">
					<div class="info-label">작성자</div>
					<div id="inquirer" class="info-content"></div>
				</div>
				<div class="info-row">
					<div class="info-label">작성일</div>
					<div id="createdDate" class="info-content"></div>
				</div>
				<div class="info-row">
						<div class="info-label">조회수</div>
						<div id="viewCount" class="info-content">0</div>
					</div>
					<div class="info-row">
						<div class="info-label">공개범위</div>
						<div class="info-content" style="display:flex; gap:8px; align-items:center;">
							<select id="visibilitySelect">
								<option value="ALL">전체공개</option>
								<option value="ORG">법인공개</option>
								<option value="PRIVATE">비공개</option>
							</select>
							<span style="font-size:0.85em; color:#999;">변경 후 상단 [수정] 버튼을 누르면 사유 입력창이 표시됩니다.</span>
						</div>
					</div>
					<div class="info-row" id="attachFileRow" style="display: none;">
					<div class="info-label">첨부파일</div>
					<div id="attachFiles" class="info-content"></div>
				</div>
				<div class="info-row">
					<div class="info-label">문의 내용</div>
					<div id="inquiryDetail" class="info-content" style="white-space: pre-line;"></div>
				</div>
			</div>

			<!-- 답변 작성 부분 -->
			<div class="response-section">
				<div class="info-row">
					<div class="info-label">상태</div>
					<div id="inquiryStatus" class="info-content"></div>
				</div>			
				<div class="info-row">
					<div class="info-label">답변자</div>
					<div id="responder" class="info-content"></div>
				</div>
				<div class="info-row">
					<div class="info-label">답변일</div>
					<div id="responseDate" class="info-content"></div>
				</div>
				<div class="info-row">
					<div class="info-label">답변 내용<span class="required-mark">*</span></div>
					<div style="flex: 1; padding-top: 5px;">
						<textarea id="responseDetail" name="responseDetail" data-required data-warning="답변 내용을 입력하여 주십시오."></textarea>
					</div>
				</div>
			</div>
			
			<!-- 댓글 작성 부분 -->
			<div class="comment-section">
				<div id="commentList"></div>
				<div class="info-row">
					<div class="info-label">${sessionScope.login.userName}</div>
					<div style="flex:1; display: flex; gap: 8px; align-items: stretch;">
						<textarea id="commentDetail" name="commentDetail" data-required data-warning="댓글 내용을 입력하여 주십시오."></textarea>
						<button type="button" class="cssbtn" id="btn_comment" level="W" style="width:100px; height: 100px; text-align:center; ">댓글등록</button>
					</div>
				</div>
			</div>
			
			<input type="hidden" name="id" id="id">
		</form>
	</div>
</div>

<!-- 공개범위 변경 사유 입력 모달 -->
<div id="reasonModal" class="reason-modal-overlay">
	<div class="reason-modal-box">
		<h3>공개범위 변경 사유</h3>
		<textarea id="reasonModalInput" placeholder="변경 사유를 입력하세요."></textarea>
		<div class="reason-modal-actions">
			<button type="button" class="cssbtn" id="reasonModalOk">확인</button>
			<button type="button" class="cssbtn" id="reasonModalCancel">취소</button>
		</div>
	</div>
</div>
</body>
</html>