<%@ 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");
%>
<%!
	public String getRequiredLabel(String label) {
		return label + " <span class=\"required-mark\">*</span>";
	}
%>
<html>
<head>
	<title>이용약관 상세</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<jsp:include page="/jsp/common/include/css.jsp"/>
	<link rel="stylesheet" type="text/css" href="<c:url value="/css/editor-content.css"/>"/>
	<style>
		.file-link {
			color: #0049b4;
			text-decoration: none;
		}
		.file-link:hover {
			text-decoration: underline;
		}
		.file-size {
			color: #888;
			font-size: 12px;
		}
		.btn-file-delete {
			background: none;
			border: none;
			cursor: pointer;
			color: #dc3545;
			padding: 2px 4px;
			margin-left: 8px;
			vertical-align: middle;
		}
		.btn-file-delete:hover {
			color: #a71d2a;
		}
		.btn-file-delete .material-icons {
			font-size: 16px;
			vertical-align: middle;
		}
	</style>
	<jsp:include page="/jsp/common/include/script.jsp"/>
	<jsp:include page="/jsp/common/include/portal.jsp"/>
	<script language="javascript">
		var url = '<c:url value="/onl/apim/portalterms/portalTermsMan.json" />';
		var url_view = '<c:url value="/onl/apim/portalterms/portalTermsMan.view" />';
		var imageUploadUrl = '<c:url value="/onl/apim/editor/image/upload.json" />';
		var imageViewUrl = '<c:url value="/onl/apim/editor/image/view.do" />';
		var fileDownloadUrl = '<c:url value="/file/download.do" />';
		var isDetail = false;
		var currentAttachedFileId = null;

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

		function formatFileSize(bytes) {
			if (!bytes || bytes === 0) return '0 B';
			var k = 1024;
			var sizes = ['B', 'KB', 'MB', 'GB'];
			var i = Math.floor(Math.log(bytes) / Math.log(k));
			return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
		}

		function showAttachedFile(fileId, fileName, fileSize) {
			var downloadLink = fileDownloadUrl + '?fileId=' + fileId + '&fileSn=1';
			var html = '<a href="' + downloadLink + '" class="file-link" title="다운로드">' +
				'<i class="material-icons" style="vertical-align: middle; font-size: 18px;">attach_file</i> ' +
				fileName + '</a>';
			if (fileSize) {
				html += ' <span class="file-size">(' + formatFileSize(fileSize) + ')</span>';
			}
			html += ' <button type="button" class="btn-file-delete" onclick="deleteAttachedFile()" title="삭제">' +
				'<i class="material-icons">close</i></button>';
			$('#attachedFileInfo').html(html).show();
			$('#attachedFileInput').hide();
		}

		function hideAttachedFile() {
			$('#attachedFileInfo').html('').hide();
			$('#attachedFileInput').show();
			$('#attachedFile').val('');
		}

		function deleteAttachedFile() {
			if (confirm('첨부파일을 삭제하시겠습니까?')) {
				currentAttachedFileId = null;
				$('#deleteAttachment').val('true');
				hideAttachedFile();
			}
		}

		function init() {
			$.ajax({
				type: "POST",
				url: url,
				dataType: "json",
				data: {cmd: 'LIST_INIT_COMBO'},
				success: function(json) {
					new makeOptions("CODE", "NAME")
							.setObj($("select[name=agreementsType]"))
							.setData(json.termsTypeRows)
							.setFormat(nameOptionFormat)
							.rendering();

					if (isDetail && "${param.agreementsType}" && "${param.revision}") {
						detail("${param.agreementsType}", "${param.revision}");
					}
				},
				error: function(e) {
					alert(e.responseText);
				}
			});
		}

		function detail(agreementsType, revision) {
			if (!isDetail) {
				$('#revisionHidden').val("0");
				return;
			}
			$.ajax({
				type: "POST",
				url: url,
				dataType: "json",
				data: {cmd: 'DETAIL', agreementsType: agreementsType, revision: revision},
				success: function (data) {
					$("#agreementsType").val(data.agreementsType);
					$("#revision").text(data.revision);
					$("#revisionHidden").val(data.revision);
					$("#name").val(data.name);
					$("#status").val(data.status);

					var decodedContent = decodeHTMLEntities(data.contents);
					// 플레이스홀더를 이미지 태그로 변환하여 에디터에 표시
					var htmlContent = convertPlaceholdersToImages(decodedContent, imageViewUrl);
					$('#contents').summernote('code', htmlContent);

					if (data.publishedOn) {
						$("#publishedOnDisplay").val(gridDateFormat(data.publishedOn));
						$("#publishedOn").val(data.publishedOn);
					}
					if (data.status !== 'DRAFT') {
						$("#publishedOnDisplay").prop('disabled', true);
					}
					$("#createdByName").text(data.createdByName);
					$("#createdDate").text(timeStampFormat(data.createdDate));
					$("#lastModifiedDate").text(timeStampFormat(data.lastModifiedDate));
					$("#lastModifiedByName").text(data.lastModifiedByName);

					// 첨부파일 정보 표시
					currentAttachedFileId = data.attachedFileId;
					if (data.attachedFileId && data.attachedFileName) {
						showAttachedFile(data.attachedFileId, data.attachedFileName, data.attachedFileSize);
					} else {
						hideAttachedFile();
					}
				},
				error: function (e) {
					alert(e.responseText);
				}
			});
		}

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

			isDetail = agreementsType != "" && agreementsType != "null" && revision != "" && revision != "null";

			if (isDetail) {
				$("#title").append(" 수정");
				$("#agreementsType").prop('disabled', true);
				buttonControl(true);
			} else {
				$("#title").append(" 등록");
				$("#revisionHidden").val("0");
				$("#btn_modify").html('<i class="material-icons">save</i> <%= localeMessage.getString("button.register") %>');
				buttonControl(false);
			}

			init();

			$("#publishedOnDisplay").datepicker({
				format: 'yyyy-mm-dd',
				language: 'ko',
				autoclose: true,
				minDate: 0,
			}).on('changeDate', function(e) {
				var formattedDate = e.format('yyyymmdd') + '000000';
				$("#publishedOn").val(formattedDate); // 변경된 날짜만 설정
			}).on('hide', function(e) {
				if (!$("#publishedOnDisplay").val()) {
					$("#publishedOnDisplay").val(gridDateFormat($("#publishedOn").val()));
				}
			});

			// Summernote 에디터 초기화 (파일 업로드 방식, 리사이징 지원)
			initSummernote('#contents', {
				placeholder: '여기에 약관 내용을 입력하세요.',
				height: 300,
				useFileUpload: true,
				uploadUrl: imageUploadUrl,
				imageViewUrl: imageViewUrl
			});

			if (agreementsType && revision) {
				detail(agreementsType, revision);
			}

			$("#btn_modify").click(function() {
				if (!checkRequired("ajaxForm")) return;

				// Summernote 에디터 내용 검증
				var contents = $('#contents').summernote('code');
				if (contents === "" || contents === "<p><br></p>" || contents === "<p></p>") {
					alert("약관 내용을 입력하여 주십시오.");
					$('#contents').summernote('focus');
					return;
				}

				if (confirm("<%= localeMessage.getString("common.checkSave")%>") != true)
					return;

				$("#agreementsType").prop('disabled', false);

				// 이미지 태그를 플레이스홀더로 변환 (저장 시)
				var contentsWithPlaceholders = convertImagesToPlaceholders(contents);
				// 현재 사용 중인 파일 ID 목록 추출
				var usedFileIds = extractFileIdsFromContent(contentsWithPlaceholders);

				// FormData로 전송 (첨부파일 포함)
				var formData = new FormData();
				formData.append('cmd', isDetail ? "UPDATE" : "INSERT");
				formData.append('agreementsType', $("#agreementsType").val());
				formData.append('revision', $("#revisionHidden").val());
				formData.append('publishedOn', $("#publishedOn").val());
				formData.append('contents', contentsWithPlaceholders);
				formData.append('usedFileIds', usedFileIds.join(','));

				// 첨부파일 추가
				var attachedFile = $('#attachedFile')[0].files[0];
				if (attachedFile) {
					formData.append('attachedFile', attachedFile);
				}

				// 첨부파일 삭제 플래그
				formData.append('deleteAttachment', $('#deleteAttachment').val() || 'false');

				$.ajax({
					type: "POST",
					url: url,
					data: formData,
					processData: false,
					contentType: false,
					success: function (json) {
						alert("<%= localeMessage.getString("common.saveMsg") %>");
						goNav(returnUrl);
					},
					error: function (e) {
						var errorMsg = e.responseText || e.statusText || "저장 중 오류가 발생했습니다.";
						alert(errorMsg);
					}
				});
			});

			$("#btn_delete").click(function () {
				if (confirm("<%= localeMessage.getString("common.confirmMsg")%>")) {
					var deleteData = {
						cmd: "DELETE",
						agreementsType: $("#agreementsType").val(),
						revision: $("#revisionHidden").val()
					};

					$.ajax({
						type: "POST",
						url: url,
						data: deleteData,
						success: function (args) {
							alert("<%= localeMessage.getString("common.deleteMsg") %>");
							goNav(returnUrl);
						},
						error: function (e) {
							alert(e.responseText);
						}
					});
				}
			});

			$("#btn_previous").click(function() {
				goNav(returnUrl);
			});
		});
	</script>
</head>
<body>
<div class="right_box">
	<div class="content_top">
		<ul class="path">
			<li><a href="#">${rmsMenuPath}</a></li>
		</ul>
	</div><!-- end content_top -->
	<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_delete" level="W" status="DETAIL"><i class="material-icons">delete</i> <%= localeMessage.getString("button.delete") %></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" id="title">약관</div>
		<form id="ajaxForm" enctype="multipart/form-data">
			<input type="hidden" name="revision" id="revisionHidden">
			<input type="hidden" id="deleteAttachment" value="false">
			<table class="table_row" cellspacing="0">
				<tr>
					<th style="width:10%;"><%= getRequiredLabel("약관명") %></th>
					<td  style="width:40%;" colspan="1">
						<div class="select-style" >
							<select type="text" id="agreementsType" name="agreementsType" style="width:100%"
									data-required data-warning="약관명을 선택하여 주십시오."></select>
						</div>
					</td>
					<th style="width:10%;">버전</th>
					<td style="width:40%;" colspan="1" id="revision"></td>
				</tr>
				<tr>
					<th>등록자</th>
					<td id="createdByName"></td>
					<th style="width:10%;">수정자</th>
					<td id="lastModifiedByName"></td>
				</tr>
				<tr>
					<th>등록일</th>
					<td id="createdDate"></td>
					<th>수정일</th>
					<td id="lastModifiedDate"></td>
				</tr>
				<tr>
					<th><%= getRequiredLabel("약관 시행일") %></th>
					<td colspan="3" >
						<!-- 표시용 날짜 필드 -->
						<input type="text" id="publishedOnDisplay" style="width:200px;"  data-required data-warning="약관시행일을 입력하여 주십시오."/>
						<input type="hidden" id="publishedOn" name="publishedOn"/>
					</td>
				</tr>
				<tr>
					<th>첨부파일</th>
					<td colspan="3">
						<div id="attachedFileInfo" style="display:none; padding: 5px 0;"></div>
						<div id="attachedFileInput">
							<input type="file" id="attachedFile" name="attachedFile" style="width:400px;">
							<span class="file-help" style="color:#666; font-size:12px; margin-left:10px;">약관 원본 문서를 첨부할 수 있습니다.</span>
						</div>
					</td>
				</tr>
				<tr>
					<th><%= getRequiredLabel("약관 내용") %></th>
					<td colspan="3">
						<textarea id="contents" name="contents" style="width:100%;height:300px" data-required data-warning="약관내용을 입력하여 주십시오."></textarea>
					</td>
				</tr>
			</table>
		</form>
	</div>
</div>
</body>
</html>