<?php
// 이 페이지는 shop/partner/skin/Basic/itemlist.skin.php 에서 수정 버튼을 누르면 나오는 페이지 입니다

if (!defined('_GNUBOARD_')) exit;

# /shop/partner/itemform.php 264 Line 에서 include 됨
# 이 form은 /shop/partner/itemformupdate.php 으로 submit 됨

$pg_anchor ='<ul class="anchor">';
$pg_anchor .='<li><a href="#anc_sitfrm_ini">기본정보</a></li>';
$pg_anchor .='<li><a href="#anc_sitfrm_compact">요약정보</a></li>';
$pg_anchor .='<li><a href="#anc_sitfrm_cost">가격/재고/배송비</a></li>';
$pg_anchor .='<li><a href="#anc_sitfrm_img">이미지</a></li>';
$pg_anchor .='<li><a href="#anc_sitfrm_relation">관련상품</a></li>';
if($is_auth) { // 관리자일 때
	$pg_anchor .='<li><a href="#anc_sitfrm_event">관련이벤트</a></li>';

}
$pg_anchor .='<li><a href="#anc_sitfrm_opt">옵션사항</a></li>';
$pg_anchor .='<li><a href="#anc_sitfrm_attach">파일첨부</a></li>';
if($is_auth) { // 관리자일 때
	$pg_anchor .='<li><a href="#anc_sitfrm_optional">상하단내용</a></li>';
	$pg_anchor .='<li><a href="#anc_sitfrm_extra">여분필드</a></li>';
}
$pg_anchor .='</ul>';

$admin_only_badge = '<span class="admin-only-badge">관리자전용</span>';

$recent_itemform_configs = array();
if ($w == '') {
	$recent_itemform_file_vpn = G5_DATA_PATH . '/item/recent_itemform_configs_vpn_' . $member['mb_id'] . '.json';

	$is_vpn_preset = function($preset) {
		if (!is_array($preset)) {
			return false;
		}

		$values = (isset($preset['values']) && is_array($preset['values'])) ? $preset['values'] : array();
		$preset_scope = isset($preset['preset_scope']) ? trim((string)$preset['preset_scope']) : '';
		$summary_text = isset($preset['summary']) ? trim((string)$preset['summary']) : '';
		$it_spec_sales_type = isset($values['it_spec_sales_type']) ? trim((string)$values['it_spec_sales_type']) : '';
		$it_spec_cpu = isset($values['it_spec_cpu']) ? trim((string)$values['it_spec_cpu']) : '';
		$it_spec_gpu = isset($values['it_spec_gpu']) ? trim((string)$values['it_spec_gpu']) : '';
		$it_spec_ram = isset($values['it_spec_ram']) ? trim((string)$values['it_spec_ram']) : '';
		$ca_id = isset($values['ca_id']) ? trim((string)$values['ca_id']) : '';
		$has_remote_program = isset($values['remoteProgram']) && is_array($values['remoteProgram']) && count($values['remoteProgram']) > 0;

		$is_vpn_scope = ($preset_scope === 'vpn-mall');
		$is_vpn_type = ($it_spec_sales_type === 'vpn-mall');

		if ($preset_scope === 'rpc-mall') {
			return false;
		}

		if (!$is_vpn_scope && !$is_vpn_type) {
			if ($it_spec_sales_type !== '' && $it_spec_sales_type !== 'vpn-mall') {
				return false;
			}

			if (preg_match('/\bRPC-/i', $summary_text)) {
				return false;
			}
		}

		$is_probable_vpn_legacy = (
			$has_remote_program
			&& $it_spec_cpu === ''
			&& $it_spec_gpu === ''
			&& $it_spec_ram === ''
			&& ($ca_id === '' || preg_match('/^(30|40)/', $ca_id))
		);

		return ($is_vpn_scope || $is_vpn_type || $is_probable_vpn_legacy);
	};

	// 1) VPN 전용 파일 우선 로드
	if (is_file($recent_itemform_file_vpn)) {
		$recent_itemform_raw = @file_get_contents($recent_itemform_file_vpn);
		$recent_itemform_decoded = json_decode($recent_itemform_raw, true);
		if (is_array($recent_itemform_decoded)) {
			$recent_itemform_configs = array_values(array_filter($recent_itemform_decoded, $is_vpn_preset));
			$recent_itemform_configs = array_slice($recent_itemform_configs, 0, 100);
		}
	}
}

$recent_config_open_btn_html = '';
if ($w == '' && count($recent_itemform_configs) > 0) {
	$recent_config_open_btn_html = '<button type="button" class="recent-config-open-btn js-recent-config-open"><span class="icon">🧠</span>최근설정 불러오기</button>';
}
$frm_submit_with_recent = $frm_submit;
if ($recent_config_open_btn_html !== '') {
	$frm_submit_with_recent = preg_replace('/<\/div>\s*$/', $recent_config_open_btn_html . '</div>', $frm_submit, 1);
}

?>
<style>
	.sl { width:100% }
	.sm { width:100%; max-width:300px; }
	.helper { color:#5b747e; }
	.anchor li { width:14.285%; min-width:100px; max-width:140px;}
	.anchor li a { text-align:center; display:block; font-size:11px; letter-spacing:-1px; }
	.srel .srel_list, .srel .srel_sel { height:315px;max-height:315px; }
	.iframe iframe { min-height:370px; }
	.btn_confirm { margin-bottom:50px; }
    /* Removed conflicting padding styles */
</style>

<style>
    #it_price,
    #it_install_price,
    #ca_id,
    #it_spec_os_disp_lang,
    #it_spec_cpu,
    #it_spec_ram,
    #it_spec_ram_type,
    #it_spec_gpu,
    #it_spec_ssd,
    #it_spec_ssd_type,
	#it_spec_hdd,
	#it_spec_hdd_type,
	#it_10_day,
	#it_10_hour,
	#it_buy_min_qty,
	#it_buy_max_qty,
    #addProgram,
    .vpn-config-item .frm_input {
        background-color: #fef9c3; /* Soft Amber/Yellow */
		border-color: #fcd34d;
        color: #333;
    }
</style>

<style>
	/* -- Modern Flat UI Style (Sophisticated & Luxurious) -- */

	/* Unified Height & Typography */
	input[type="text"], input[type="number"], input[type="password"], input[type="email"], input[type="tel"], input[type="url"], input[type="search"], input[type="date"], input[type="datetime-local"], input[type="month"], input[type="week"], input[type="time"], input[type="datetime"], input[type="color"],
    select,
    .frm_input { /* Ensure class selector is included for specificity */
		height: 40px !important; /* Force height */
		padding: 0 12px;
		margin: 5px 0;
		display: inline-block;
		border: 1px solid #dce1e6; /* Soft gray border */
		border-radius: 4px;
		box-sizing: border-box;
		background-color: #fff;
		color: #333;
		font-size: 14px;
		line-height: 38px !important; /* Vertically center text (height - borders) */
		transition: border-color 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
		font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
        vertical-align: middle; /* Align with neighbors */
	}

	/* Select specific fix */
	select.frm_input {
		height: 40px !important;
		line-height: 38px !important;
        padding-right: 30px; /* Space for arrow if needed */
        -webkit-appearance: menulist; /* Ensure default arrow or custom if preferred */
	}

	/* Textarea exception */
	textarea, textarea.frm_input {
		height: auto !important;
		padding: 12px;
		line-height: 1.5 !important;
	}

	/* Focus State - Elegant Blue Glow */
	input:focus, select:focus, textarea:focus, .frm_input:focus {
		border-color: #3b82f6 !important;
		box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15); /* Subtle spread */
		outline: none;
	}

	/* Hover State */
	input:hover, select:hover, textarea:hover, .frm_input:hover {
		border-color: #a0aec0;
	}

	/* Disabled State */
	input:disabled, select:disabled, textarea:disabled, .frm_input:disabled {
		background-color: #f7fafc;
		color: #a0aec0;
		cursor: not-allowed;
		border-color: #edf2f7;
	}


	/* 플라이스홀더 스타일 */
	input[type="text"]::placeholder, input[type="number"]::placeholder, input[type="password"]::placeholder, input[type="email"]::placeholder, input[type="tel"]::placeholder, input[type="url"]::placeholder, input[type="search"]::placeholder, input[type="date"]::placeholder, input[type="datetime-local"]::placeholder, input[type="month"]::placeholder, input[type="week"]::placeholder, input[type="time"]::placeholder, input[type="datetime"]::placeholder, input[type="color"]::placeholder, select::placeholder, textarea::placeholder {
		color: #aaa;
		font-style: italic;
	}

	/* 전송 버튼 스타일 */
	input[type="submit"], input[type="button"], button {
		background-color: #4CAF50;
		color: white;
		padding: 14px 20px;
		margin: 8px 0;
		border: none;
		border-radius: 4px;
		cursor: pointer;
		transition: background-color 0.3s ease-in-out;
	}

	input[type="submit"]:hover, input[type="button"]:hover, button:hover {
		background-color: #45a049;
	}

	.recent-config-open-btn {
		height: 44px;
		padding: 0 22px;
		border-radius: 12px;
		border: 1px solid #4f7a31;
		background: linear-gradient(180deg, #6f8f4d 0%, #5f7f3f 100%);
		color: #ffffff;
		font-weight: 700;
		font-size: 15px;
		line-height: 1;
		cursor: pointer;
		transition: all .18s ease;
		margin-left: 8px !important;
		vertical-align: middle;
		box-shadow: 0 8px 16px rgba(27, 51, 15, 0.16);
	}

	.recent-config-open-btn:hover {
		transform: translateY(-1px);
		filter: brightness(1.04);
		box-shadow: 0 11px 20px rgba(27, 51, 15, 0.2);
		border-color: #456b2b;
	}

	.recent-config-open-btn .icon {
		margin-right: 6px;
		font-size: 14px;
		vertical-align: -1px;
	}

	.recent-config-open-btn:focus-visible {
		outline: none;
		box-shadow: 0 0 0 3px rgba(129, 164, 96, 0.28), 0 10px 18px rgba(27, 51, 15, 0.22);
	}

	.btn_confirm01.btn_confirm {
		display: flex;
		justify-content: center;
		align-items: center;
		gap: 8px;
		flex-wrap: wrap;
	}

	.btn_confirm01.btn_confirm > a,
	.btn_confirm01.btn_confirm > button,
	.btn_confirm01.btn_confirm > input[type="submit"],
	.btn_confirm01.btn_confirm > input[type="button"] {
		height: 44px;
		padding: 0 22px;
		border-radius: 12px;
		font-weight: 700;
		font-size: 15px;
		line-height: 42px;
		text-decoration: none;
		display: inline-flex;
		align-items: center;
		justify-content: center;
		border: 1px solid #4f7a31;
		box-shadow: 0 8px 16px rgba(27, 51, 15, 0.16);
		transition: transform .18s ease, filter .18s ease, box-shadow .18s ease;
	}

	.btn_confirm01.btn_confirm > input[type="submit"],
	.btn_confirm01.btn_confirm > .btn_submit,
	.btn_confirm01.btn_confirm > .btn_submit_ex,
	.btn_confirm01.btn_confirm > .btn_confirm,
	.btn_confirm01.btn_confirm > .btn_confirm01 {
		background: linear-gradient(180deg, #53ba55 0%, #44a646 100%);
		border-color: #3d943f;
		color: #fff;
	}

	.btn_confirm01.btn_confirm > a {
		background: linear-gradient(180deg, #6f8f4d 0%, #5f7f3f 100%);
		border-color: #4f7a31;
		color: #fff;
	}

	.btn_confirm01.btn_confirm > a:hover,
	.btn_confirm01.btn_confirm > button:hover,
	.btn_confirm01.btn_confirm > input[type="submit"]:hover,
	.btn_confirm01.btn_confirm > input[type="button"]:hover {
		transform: translateY(-1px);
		filter: brightness(1.04);
		box-shadow: 0 11px 20px rgba(27, 51, 15, 0.2);
	}

	.btn_confirm01.btn_confirm > a:focus-visible,
	.btn_confirm01.btn_confirm > button:focus-visible,
	.btn_confirm01.btn_confirm > input[type="submit"]:focus-visible,
	.btn_confirm01.btn_confirm > input[type="button"]:focus-visible {
		outline: none;
		box-shadow: 0 0 0 3px rgba(129, 164, 96, 0.28), 0 10px 18px rgba(27, 51, 15, 0.22);
	}

	.btn_confirm01.btn_confirm.rpc-floating-menu {
		position: fixed !important;
		top: 14px;
		left: 14px;
		z-index: 11000;
		margin: 0 !important;
		padding: 6px 8px;
		border-radius: 12px;
		border: 1px solid #dce7ce;
		background: rgba(255, 255, 255, 0.95);
		backdrop-filter: blur(4px);
		-webkit-backdrop-filter: blur(4px);
		box-shadow: 0 10px 20px rgba(22, 42, 11, 0.16);
		justify-content: flex-start;
		gap: 6px;
		flex-wrap: nowrap;
		white-space: nowrap;
		width: max-content;
		max-width: calc(100vw - 16px);
		overflow-x: auto;
		overflow-y: hidden;
		-ms-overflow-style: none;
		scrollbar-width: none;
	}

	.btn_confirm01.btn_confirm.rpc-floating-menu.rpc-floating-menu-horizontal {
		flex-direction: row;
		align-items: center;
	}

	.btn_confirm01.btn_confirm.rpc-floating-menu.rpc-floating-menu-vertical {
		flex-direction: column;
		align-items: stretch;
		width: auto;
		max-width: min(260px, calc(100vw - 16px));
		overflow: visible;
		white-space: normal;
	}

	.btn_confirm01.btn_confirm.rpc-floating-menu.rpc-floating-menu-vertical > a,
	.btn_confirm01.btn_confirm.rpc-floating-menu.rpc-floating-menu-vertical > button,
	.btn_confirm01.btn_confirm.rpc-floating-menu.rpc-floating-menu-vertical > input[type="submit"],
	.btn_confirm01.btn_confirm.rpc-floating-menu.rpc-floating-menu-vertical > input[type="button"] {
		width: 100%;
	}

	.btn_confirm01.btn_confirm.rpc-floating-menu::-webkit-scrollbar {
		display: none;
	}

	.btn_confirm01.btn_confirm.rpc-floating-menu .rpc-floating-drag-handle {
		display: inline-flex;
		align-items: center;
		height: 30px;
		padding: 0 9px;
		border-radius: 999px;
		font-size: 11px;
		font-weight: 700;
		color: #2f4c1d;
		background: #eef6e9;
		border: 1px solid #cfe2bf;
		cursor: grab;
		user-select: none;
		line-height: 1;
		flex: 0 0 auto;
		touch-action: none;
	}
	/* grip 점 패턴 — 드래그 가능 시각적 표시 */
	.btn_confirm01.btn_confirm.rpc-floating-menu .rpc-floating-drag-handle::before {
		content: '';
		display: inline-block;
		width: 10px;
		height: 16px;
		margin-right: 5px;
		flex-shrink: 0;
		background-image: radial-gradient(circle, #2f4c1d 1.5px, transparent 1.5px);
		background-size: 5px 5.5px;
		background-repeat: repeat;
		opacity: 0.5;
	}
	.btn_confirm01.btn_confirm.rpc-floating-menu.is-dragging .rpc-floating-drag-handle {
		cursor: grabbing;
	}
	.btn_confirm01.btn_confirm.rpc-floating-menu.is-dragging .rpc-floating-drag-handle::before {
		opacity: 0.8;
	}

	/* 모드토글: 아이콘 전용 소형 버튼 — 액션 버튼과 시각적 분리 */
	.btn_confirm01.btn_confirm.rpc-floating-menu .rpc-floating-mode-toggle {
		display: grid !important;
		place-items: center !important;
		width: 26px !important;
		min-width: 26px !important;
		height: 26px !important;
		padding: 0 !important;
		border-radius: 6px !important;
		font-size: 15px !important;
		font-weight: 400 !important;
		line-height: 1 !important;
		color: #3a6abf !important;
		background: #f0f5ff !important;
		border: 1px solid #c8ddff !important;
		cursor: pointer !important;
		flex: 0 0 26px !important;
		box-shadow: none !important;
		margin: 0 !important;
		transition: background .15s ease;
	}
	.btn_confirm01.btn_confirm.rpc-floating-menu .rpc-floating-mode-toggle:hover {
		background: #dceaff !important;
		filter: none !important;
		transform: none !important;
		box-shadow: none !important;
	}

	/* 컨트롤 영역 (드래그 핸들 + 모드토글 아이콘) */
	.btn_confirm01.btn_confirm.rpc-floating-menu .rpc-floating-control-row {
		display: flex !important;
		flex-direction: row !important;
		align-items: center !important;
		gap: 5px !important;
		flex: 0 0 auto !important;
		padding-right: 8px !important;
		border-right: 1px solid #d0e5c0 !important;
		margin-right: 4px !important;
	}
	.btn_confirm01.btn_confirm.rpc-floating-menu-vertical .rpc-floating-control-row {
		width: 100% !important;
		padding-right: 0 !important;
		border-right: none !important;
		margin-right: 0 !important;
		padding-bottom: 7px !important;
		border-bottom: 1px solid #d0e5c0 !important;
		margin-bottom: 4px !important;
	}
	.btn_confirm01.btn_confirm.rpc-floating-menu .rpc-floating-control-row .rpc-floating-drag-handle {
		flex: 1 1 auto !important;
		min-width: 0 !important;
	}
	/* 세로 모드에서 드래그핸들 width:100%/center override */
	.btn_confirm01.btn_confirm.rpc-floating-menu.rpc-floating-menu-vertical .rpc-floating-drag-handle {
		width: auto !important;
		justify-content: flex-start !important;
	}
	/* 세로 모드에서도 모드토글은 고정 26px + grid center 유지 */
	.btn_confirm01.btn_confirm.rpc-floating-menu.rpc-floating-menu-vertical .rpc-floating-mode-toggle {
		width: 26px !important;
		min-width: 26px !important;
		justify-content: center !important;
	}

	.btn_confirm01.btn_confirm.rpc-floating-menu.is-dragging .rpc-floating-drag-handle {
		cursor: grabbing;
	}

	.btn_confirm01.btn_confirm.rpc-floating-menu.is-dragging > a,
	.btn_confirm01.btn_confirm.rpc-floating-menu.is-dragging > button,
	.btn_confirm01.btn_confirm.rpc-floating-menu.is-dragging > input[type="submit"],
	.btn_confirm01.btn_confirm.rpc-floating-menu.is-dragging > input[type="button"] {
		transition: none !important;
	}

	.btn_confirm01.btn_confirm.rpc-floating-menu > a,
	.btn_confirm01.btn_confirm.rpc-floating-menu > button,
	.btn_confirm01.btn_confirm.rpc-floating-menu > input[type="submit"],
	.btn_confirm01.btn_confirm.rpc-floating-menu > input[type="button"] {
		height: 36px;
		padding: 0 14px;
		border-radius: 10px;
		font-size: 13px;
		line-height: 34px;
		flex: 0 0 auto;
		position: relative;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.btn_confirm01.btn_confirm.rpc-floating-menu > a,
	.btn_confirm01.btn_confirm.rpc-floating-menu > button {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		gap: 6px;
	}

	.btn_confirm01.btn_confirm.rpc-floating-menu .rpc-btn-icon {
		font-size: 13px;
		line-height: 1;
		flex: 0 0 auto;
	}

	.btn_confirm01.btn_confirm.rpc-floating-menu .rpc-btn-label {
		display: inline-block;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		max-width: 100%;
	}

	.btn_confirm01.btn_confirm.rpc-floating-menu > input.rpc-btn-apply,
	.btn_confirm01.btn_confirm.rpc-floating-menu > a.rpc-btn-list,
	.btn_confirm01.btn_confirm.rpc-floating-menu > button.rpc-btn-recent {
		transition: transform .22s ease, box-shadow .26s ease, filter .22s ease, background .26s ease;
	}

	.btn_confirm01.btn_confirm.rpc-floating-menu > input.rpc-btn-apply {
		background: linear-gradient(135deg, #1fb45c 0%, #19964d 100%);
		border-color: #198346;
		color: #fff;
	}

	.btn_confirm01.btn_confirm.rpc-floating-menu > a.rpc-btn-list {
		background: linear-gradient(135deg, #3f62d8 0%, #2f4fb7 100%);
		border-color: #2b469f;
		color: #fff;
	}

	.btn_confirm01.btn_confirm.rpc-floating-menu > button.rpc-btn-recent {
		background: linear-gradient(135deg, #7b5ad9 0%, #6242c2 100%);
		border-color: #563ab0;
		color: #fff;
	}

	.btn_confirm01.btn_confirm.rpc-floating-menu > input.rpc-btn-apply:hover,
	.btn_confirm01.btn_confirm.rpc-floating-menu > a.rpc-btn-list:hover,
	.btn_confirm01.btn_confirm.rpc-floating-menu > button.rpc-btn-recent:hover {
		transform: translateY(-2px);
		filter: saturate(1.08) brightness(1.04);
		box-shadow: 0 12px 22px rgba(19, 31, 56, 0.26);
	}

	.btn_confirm01.btn_confirm.rpc-floating-menu .recent-config-open-btn {
		margin-left: 0 !important;
		height: 36px;
		padding: 0 14px;
		font-size: 13px;
		line-height: 34px;
		border-radius: 10px;
	}

	.btn_confirm01.btn_confirm.rpc-floating-menu .recent-config-open-btn .icon {
		font-size: 12px;
		margin-right: 4px;
	}

	.btn_confirm01.btn_confirm.rpc-floating-menu-clone-hidden {
		display: none !important;
	}

	@media (max-width: 900px) {
		.btn_confirm01.btn_confirm.rpc-floating-menu {
			max-width: calc(100vw - 12px);
			padding: 6px;
			gap: 5px;
		}

		.btn_confirm01.btn_confirm.rpc-floating-menu > a,
		.btn_confirm01.btn_confirm.rpc-floating-menu > button,
		.btn_confirm01.btn_confirm.rpc-floating-menu > input[type="submit"],
		.btn_confirm01.btn_confirm.rpc-floating-menu > input[type="button"] {
			height: 34px;
			padding: 0 12px;
			font-size: 12px;
			line-height: 32px;
		}

		.btn_confirm01.btn_confirm.rpc-floating-menu .rpc-btn-icon {
			font-size: 12px;
		}

		.btn_confirm01.btn_confirm.rpc-floating-menu .recent-config-open-btn {
			height: 34px;
			padding: 0 12px;
			font-size: 12px;
			line-height: 32px;
		}

		.btn_confirm01.btn_confirm.rpc-floating-menu .rpc-floating-drag-handle {
			height: 28px;
			padding: 0 8px;
			font-size: 11px;
		}

		.btn_confirm01.btn_confirm.rpc-floating-menu .rpc-floating-mode-toggle {
			width: 24px !important;
			min-width: 24px !important;
			height: 24px !important;
			padding: 0 !important;
			font-size: 13px !important;
		}
	}

	#recent-config-layer {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, 0.55);
		z-index: 10000;
		display: none;
	}

	#recent-config-layer .recent-config-modal {
		position: absolute;
		top: 56px;
		left: 50%;
		transform: translateX(-50%);
		width: min(680px, calc(100% - 24px));
		min-width: 460px;
		min-height: 0;
		max-width: calc(100% - 24px);
		max-height: calc(100vh - 110px);
		overflow: auto;
		resize: both;
		background: #fff;
		border-radius: 10px;
		padding: 12px;
		box-shadow: 0 10px 25px rgba(0, 0, 0, 0.25);
		border: 1px solid #dde6f3;
	}

	#recent-config-layer .recent-config-modal.is-compact {
		height: auto;
		min-height: 0;
		max-height: min(240px, calc(100vh - 120px));
		resize: none;
	}

	#recent-config-layer .recent-config-modal.is-expanded {
		height: auto;
		min-height: 480px;
		max-height: calc(100vh - 90px);
		resize: both;
	}

	#recent-config-layer .recent-config-title {
		font-size: 16px;
		font-weight: 700;
		margin-bottom: 6px;
		padding: 6px 8px;
		border-radius: 6px;
		background: linear-gradient(180deg, #f8fbff 0%, #f1f5fb 100%);
		border: 1px solid #e1e8f4;
		cursor: move;
		user-select: none;
	}

	#recent-config-question {
		padding: 10px 12px;
		border-radius: 8px;
		background: #f8fafc;
		border: 1px solid #e5e7eb;
		line-height: 1.5;
		color: #374151;
	}

	#recent-config-layer .recent-config-btns {
		display: flex;
		gap: 8px;
		justify-content: flex-end;
		margin-top: 10px;
		flex-wrap: wrap;
	}

	#recent-config-layer .recent-config-btns .recent-btn {
		height: 38px !important;
		padding: 0 14px !important;
		border-radius: 10px !important;
		font-size: 13px !important;
		font-weight: 700 !important;
		border: 1px solid transparent !important;
		transition: all .16s ease;
		box-shadow: 0 2px 6px rgba(15, 23, 42, 0.08);
	}

	#recent-config-layer .recent-config-btns .recent-btn:hover {
		transform: translateY(-1px);
		box-shadow: 0 6px 14px rgba(15, 23, 42, 0.12);
	}

	#recent-config-layer .recent-config-btns .recent-btn-primary {
		background: linear-gradient(135deg, #1f6fd6, #1a56b5) !important;
		border-color: #1a56b5 !important;
		color: #fff !important;
	}

	#recent-config-layer .recent-config-btns .recent-btn-outline {
		background: #f7fbff !important;
		border-color: #8db7ec !important;
		color: #1f4f8a !important;
	}

	#recent-config-layer .recent-config-btns .recent-btn-ghost {
		background: #f3f4f6 !important;
		border-color: #d1d5db !important;
		color: #374151 !important;
	}

	#recent-config-layer .recent-config-btns .recent-btn-success {
		background: linear-gradient(135deg, #1ea97c, #158f68) !important;
		border-color: #117857 !important;
		color: #fff !important;
	}

	#recent-config-layer .recent-config-preview {
		border: 1px solid #ddd;
		border-radius: 6px;
		padding: 8px;
		background: #fafafa;
		max-height: 220px;
		overflow: auto;
	}

	#recent-config-layer .recent-config-modal.is-expanded .recent-config-preview {
		max-height: min(52vh, 520px);
	}

	#recent-config-layer table {
		width: 100%;
		border-collapse: collapse;
	}

	#recent-config-layer th,
	#recent-config-layer td {
		border-bottom: 1px solid #eee;
		padding: 5px 6px;
		font-size: 12px;
		text-align: left;
		vertical-align: top;
	}

	#recent-config-layer .recent-config-group-row td {
		background: #eef4ff;
		color: #1f4f8a;
		font-weight: 700;
		font-size: 12px;
		border-bottom: 1px solid #d7e3ff;
		padding: 6px 8px;
	}

	#recent-config-layer .recent-config-group-row {
		cursor: pointer;
		user-select: none;
	}

	#recent-config-layer .recent-config-group-row:hover td {
		background: #e2edff;
	}

	#recent-config-layer .recent-config-group-toggle {
		display: inline-block;
		width: 12px;
		margin-right: 6px;
		color: #315f9d;
		font-weight: 700;
	}

	#recent-config-layer .recent-config-resize-help {
		margin-top: 6px;
		font-size: 11px;
		color: #6b7280;
		text-align: right;
		user-select: none;
	}

	@media (max-width: 768px) {
		#recent-config-layer .recent-config-modal {
			left: 12px;
			top: 12px;
			transform: none;
			width: calc(100% - 24px);
			min-width: 0;
			min-height: 0;
			max-height: calc(100vh - 24px);
		}

		#recent-config-layer .recent-config-modal.is-compact {
			max-height: min(300px, calc(100vh - 24px));
		}

		#recent-config-layer .recent-config-modal.is-expanded {
			max-height: calc(100vh - 24px);
			min-height: 0;
		}

		#recent-config-layer .recent-config-preview {
			max-height: 180px;
		}
	}

	.admin-only-title {
		white-space: nowrap;
	}

	.admin-only-badge {
		display: inline-block;
		margin-left: 6px;
		padding: 0px 5px;
		font-size: 9px;
		font-weight: 600;
		line-height: 1.2;
		color: #1f4f8a;
		background: #e7f1ff;
		border: 1px solid #9fc3ef;
		border-radius: 999px;
		white-space: nowrap;
		vertical-align: middle;
	}

	.copilot-toast-wrap {
		position: fixed;
		top: 14px;
		left: 50%;
		transform: translateX(-50%);
		z-index: 12000;
		display: flex;
		flex-direction: column;
		gap: 8px;
		align-items: center;
		width: min(780px, calc(100vw - 24px));
		pointer-events: none;
	}

	.copilot-toast {
		min-width: 320px;
		max-width: min(720px, calc(100vw - 24px));
		padding: 10px 14px;
		border-radius: 10px;
		font-size: 12px;
		font-weight: 500;
		line-height: 1.45;
		color: #ffffff;
		background: rgba(31, 79, 138, 0.94);
		box-shadow: 0 8px 18px rgba(0, 0, 0, 0.16);
		opacity: 0;
		transform: translateY(-12px);
		transition: opacity .22s cubic-bezier(0.22, 1, 0.36, 1), transform .26s cubic-bezier(0.22, 1, 0.36, 1);
		text-align: center;
	}

	.copilot-toast .toast-icon {
		display: inline-block;
		margin-right: 6px;
		font-size: 14px;
		vertical-align: middle;
	}

	.copilot-toast .toast-text {
		vertical-align: middle;
	}

	.copilot-toast.show {
		opacity: 1;
		transform: translateY(0);
	}

	.copilot-toast.toast-success { background: rgba(25, 135, 84, 0.94); }
	.copilot-toast.toast-warn { background: rgba(214, 158, 46, 0.94); }
	.copilot-toast.toast-error { background: rgba(198, 40, 40, 0.94); }
	.copilot-toast.toast-info { background: rgba(31, 79, 138, 0.94); }

	.copilot-confirm-layer {
		position: fixed;
		inset: 0;
		background: rgba(15, 23, 42, 0.52);
		backdrop-filter: blur(2px);
		-webkit-backdrop-filter: blur(2px);
		z-index: 13000;
		display: flex;
		align-items: center;
		justify-content: center;
		opacity: 0;
		pointer-events: none;
		transition: opacity .2s ease;
	}

	.copilot-confirm-layer.open {
		opacity: 1;
		pointer-events: auto;
	}

	.copilot-confirm-box {
		width: min(560px, calc(100vw - 28px));
		background: linear-gradient(180deg, #ffffff 0%, #f9fbff 100%);
		border: 1px solid #d7e3ff;
		border-radius: 14px;
		box-shadow: 0 18px 38px rgba(15, 23, 42, 0.28);
		padding: 18px 18px 14px;
		transform: translateY(8px) scale(.985);
		transition: transform .24s cubic-bezier(0.22, 1, 0.36, 1);
	}

	.copilot-confirm-layer.open .copilot-confirm-box {
		transform: translateY(0) scale(1);
	}

	.copilot-confirm-title {
		font-size: 18px;
		font-weight: 700;
		margin-bottom: 10px;
		color: #1f2937;
	}

	.copilot-confirm-title.is-danger {
		color: #b91c1c;
	}

	.copilot-confirm-title.is-info {
		color: #1f4f8a;
	}

	.copilot-confirm-title.is-success {
		color: #0f766e;
	}

	.copilot-confirm-title.is-warn {
		color: #a16207;
	}

	.copilot-confirm-title.is-error {
		color: #b91c1c;
	}

	.copilot-confirm-message {
		font-size: 14px;
		line-height: 1.55;
		color: #111827;
		white-space: pre-line;
	}

	.copilot-confirm-actions {
		display: flex;
		justify-content: flex-end;
		gap: 10px;
		margin-top: 16px;
	}

	.copilot-confirm-actions .btn-cancel {
		background: #eef2ff !important;
		color: #4338ca !important;
		border: 1px solid #c7d2fe !important;
	}

	.copilot-confirm-actions .btn-ok {
		background: #4f46e5 !important;
		color: #fff !important;
		border: 1px solid #4338ca !important;
	}

	.copilot-confirm-actions .btn-ok.is-danger {
		background: #dc2626 !important;
		color: #fff !important;
		border: 1px solid #b91c1c !important;
	}

	.copilot-confirm-actions .btn-cancel,
	.copilot-confirm-actions .btn-ok {
		min-width: 88px;
		height: 40px;
		border-radius: 999px;
		font-weight: 600;
		transition: transform .15s ease, filter .15s ease;
	}

	.copilot-confirm-actions .btn-cancel:hover,
	.copilot-confirm-actions .btn-ok:hover {
		transform: translateY(-1px);
		filter: brightness(0.98);
	}

	.recent-applied-highlight {
		outline: 2px solid #22c55e !important;
		box-shadow: 0 0 0 3px rgba(34, 197, 94, 0.18) !important;
		transition: outline-color .2s ease, box-shadow .2s ease;
	}

	html.rpc-floating-init-pending .btn_confirm01.btn_confirm {
		visibility: hidden !important;
	}
</style>

<style>
/* ============================================================
   vpn-mall.php 다크모드 오버라이드  [data-site-theme="dark"]
   ============================================================ */

/* ── 기본 입력 필드 ── */
[data-site-theme="dark"] .new_win input[type="text"],
[data-site-theme="dark"] .new_win input[type="number"],
[data-site-theme="dark"] .new_win input[type="password"],
[data-site-theme="dark"] .new_win input[type="email"],
[data-site-theme="dark"] .new_win input[type="url"],
[data-site-theme="dark"] .new_win input[type="search"],
[data-site-theme="dark"] .new_win input[type="date"],
[data-site-theme="dark"] .new_win select,
[data-site-theme="dark"] .new_win textarea,
[data-site-theme="dark"] .new_win .frm_input {
    background-color: #1e2028 !important;
    border-color: #3a3a42 !important;
    color: #d4d4d8 !important;
}
[data-site-theme="dark"] .new_win input:disabled,
[data-site-theme="dark"] .new_win select:disabled,
[data-site-theme="dark"] .new_win textarea:disabled,
[data-site-theme="dark"] .new_win .frm_input:disabled {
    background-color: #2c2c32 !important;
    border-color: #3a3a42 !important;
    color: #71717a !important;
}
[data-site-theme="dark"] .new_win input::placeholder,
[data-site-theme="dark"] .new_win textarea::placeholder {
    color: #71717a !important;
}

/* ── 강조 입력 필드 (노란 배경) ── */
[data-site-theme="dark"] #it_price,
[data-site-theme="dark"] #it_install_price,
[data-site-theme="dark"] #ca_id,
[data-site-theme="dark"] #it_spec_os_disp_lang,
[data-site-theme="dark"] #it_spec_cpu,
[data-site-theme="dark"] #it_spec_ram,
[data-site-theme="dark"] #it_spec_ram_type,
[data-site-theme="dark"] #it_spec_gpu,
[data-site-theme="dark"] #it_spec_ssd,
[data-site-theme="dark"] #it_spec_ssd_type,
[data-site-theme="dark"] #it_spec_hdd,
[data-site-theme="dark"] #it_spec_hdd_type,
[data-site-theme="dark"] #it_10_day,
[data-site-theme="dark"] #it_10_hour,
[data-site-theme="dark"] #it_buy_min_qty,
[data-site-theme="dark"] #it_buy_max_qty,
[data-site-theme="dark"] #addProgram,
[data-site-theme="dark"] .vpn-config-item .frm_input {
    background-color: #25200e !important;
    border-color: #6b5a20 !important;
    color: #fde68a !important;
}

/* ── VPN 접속정보 아이템 ── */
[data-site-theme="dark"] .vpn-config-item {
    background: #1e2028 !important;
    border-color: #3a3a42 !important;
    box-shadow: 0 4px 6px -1px rgba(0,0,0,0.4) !important;
}
[data-site-theme="dark"] .vpn-config-item:hover {
    border-color: #4a4a52 !important;
    box-shadow: 0 10px 15px -3px rgba(0,0,0,0.35) !important;
}
[data-site-theme="dark"] .vpn-input-group label {
    color: #9ca3af !important;
}
[data-site-theme="dark"] .vpn-divider {
    background: #3a3a42 !important;
}
[data-site-theme="dark"] .vpn-flag-display {
    background: rgba(30, 32, 40, 0.92) !important;
}
[data-site-theme="dark"] .vpn-flag-display img {
    border-color: #4a4a52 !important;
}
[data-site-theme="dark"] .vpn-flag-display span {
    color: #9ca3af !important;
}

/* ── 삭제 버튼 ── */
[data-site-theme="dark"] .btn_del_vpn {
    background: #2a1a1a !important;
    border-color: #7a3030 !important;
    color: #fca5a5 !important;
}
[data-site-theme="dark"] .btn_del_vpn:hover {
    background: #5a1a1a !important;
    border-color: #9a2020 !important;
    color: #fff !important;
    box-shadow: 0 2px 4px rgba(229,62,62,0.4) !important;
}

/* ── VPN 중복 체크 결과 ── */
[data-site-theme="dark"] .vpn-dup-notice.dup-ok {
    background-color: #0d2818 !important;
    border-color: #276749 !important;
    color: #86efac !important;
}
[data-site-theme="dark"] .vpn-dup-notice.dup-error {
    background-color: #2a1a1a !important;
    border-color: #7a3030 !important;
    color: #fca5a5 !important;
}

/* ── VPN 수동 확인 경고 ── */
[data-site-theme="dark"] .vpn-manual-check-warning {
    background-color: #2a2210 !important;
    border: 1px solid #6b5a20 !important;
    color: #fde68a !important;
}

/* ── 기준요금 섹션: 장기할인 설정 박스 ── */
[data-site-theme="dark"] [style*="#d6e4f2"][style*="#fbfdff"],
[data-site-theme="dark"] [style*="d6e4f2"][style*="fbfdff"] {
    background: #1a1e2a !important;
    border-color: #2a3a5a !important;
}
[data-site-theme="dark"] #billing_policy_current {
    color: #93c5fd !important;
}
[data-site-theme="dark"] #billing_policy_state_badge {
    background: #1e3a5a !important;
    border-color: #3a5a8a !important;
    color: #93c5fd !important;
}
[data-site-theme="dark"] #billing_reality_hint {
    color: #c4c4cc !important;
    border-top-color: #2a3a5a !important;
}
[data-site-theme="dark"] #billing_reality_hint > div:first-child {
    color: #93c5fd !important;
}
[data-site-theme="dark"] #billing_discount_rates {
    color: #9ca3af !important;
}
[data-site-theme="dark"] #billing_example_100 {
    color: #71717a !important;
}
[data-site-theme="dark"] #billing_selected_preset_name {
    background: #1a2a3e !important;
    border-color: #3a5a8a !important;
    color: #93c5fd !important;
}

/* ── 사용자정의 프리셋 모달 ── */
[data-site-theme="dark"] #billing_preset_modal > div {
    background: #1e2028 !important;
    border-color: #3a3a42 !important;
}
[data-site-theme="dark"] #billing_preset_modal > div > div:first-child {
    background: #252530 !important;
    border-bottom-color: #3a3a42 !important;
}
[data-site-theme="dark"] #billing_preset_modal strong,
[data-site-theme="dark"] #billing_preset_modal span:not([class]) {
    color: #d4d4d8 !important;
}

/* ── 판매 기간별 요금 환산 계산기 ── */
[data-site-theme="dark"] #vpn_price_calculator {
    background: #1a1e2a !important;
    border-color: #3a3a42 !important;
}
[data-site-theme="dark"] #vpn_price_calculator > div:first-child {
    color: #d4d4d8 !important;
}
[data-site-theme="dark"] #vpn_price_calculator tr {
    border-bottom-color: #3a3a42 !important;
}
[data-site-theme="dark"] #vpn_price_calculator td[style*="color:#666"],
[data-site-theme="dark"] #vpn_price_calculator td[style*="color: #666"] {
    color: #9ca3af !important;
}
[data-site-theme="dark"] #vpn_price_calculator td[style*="color:#999"],
[data-site-theme="dark"] #vpn_price_calculator td[style*="color: #999"],
[data-site-theme="dark"] #vpn_price_calculator span[style*="color:#999"],
[data-site-theme="dark"] #calc_hour_desc,
[data-site-theme="dark"] #calc_year_formula,
[data-site-theme="dark"] #calc_day_formula,
[data-site-theme="dark"] #calc_month_formula {
    color: #71717a !important;
}

/* ── 최근 설정 레이어 (최근 config 불러오기) ── */
[data-site-theme="dark"] #recent-config-layer .recent-config-modal {
    background: #1e2028 !important;
    border-color: #3a3a42 !important;
}
[data-site-theme="dark"] #recent-config-layer .recent-config-title {
    background: linear-gradient(180deg, #252530 0%, #1e2028 100%) !important;
    border-color: #3a3a42 !important;
    color: #d4d4d8 !important;
}
[data-site-theme="dark"] #recent-config-question {
    background: #252530 !important;
    border-color: #3a3a42 !important;
    color: #c4c4cc !important;
}
[data-site-theme="dark"] #recent-config-layer .recent-config-preview {
    background: #1a1a20 !important;
    border-color: #3a3a42 !important;
}
[data-site-theme="dark"] #recent-config-layer table {
    color: #c4c4cc !important;
}
[data-site-theme="dark"] #recent-config-layer th,
[data-site-theme="dark"] #recent-config-layer td {
    border-bottom-color: #3a3a42 !important;
    color: #c4c4cc !important;
}
[data-site-theme="dark"] #recent-config-layer .recent-config-group-row td {
    background: #1a2a3e !important;
    border-bottom-color: #2a3a5e !important;
    color: #93c5fd !important;
}
[data-site-theme="dark"] #recent-config-layer .recent-config-group-row:hover td {
    background: #1e3050 !important;
}
[data-site-theme="dark"] #recent-config-layer .recent-config-group-toggle {
    color: #93c5fd !important;
}
[data-site-theme="dark"] #recent-config-layer .recent-config-resize-help {
    color: #71717a !important;
}
[data-site-theme="dark"] .recent-config-btns .recent-btn-outline {
    background: #1a2a3e !important;
    border-color: #3a5a8a !important;
    color: #93c5fd !important;
}
[data-site-theme="dark"] .recent-config-btns .recent-btn-ghost {
    background: #2c2c32 !important;
    border-color: #4a4a52 !important;
    color: #c4c4cc !important;
}

/* ── 플로팅 메뉴 (rpc-floating-menu) ── */
[data-site-theme="dark"] .btn_confirm01.btn_confirm.rpc-floating-menu {
    background: rgba(25, 27, 35, 0.97) !important;
    border-color: #3a3a42 !important;
    box-shadow: 0 10px 20px rgba(0,0,0,0.4) !important;
}
[data-site-theme="dark"] .btn_confirm01.btn_confirm.rpc-floating-menu .rpc-floating-drag-handle {
    background: #1a2a1a !important;
    border-color: #2a4a2a !important;
    color: #86efac !important;
}
[data-site-theme="dark"] .btn_confirm01.btn_confirm.rpc-floating-menu .rpc-floating-drag-handle::before {
    background-image: radial-gradient(circle, #86efac 1.5px, transparent 1.5px) !important;
    opacity: 0.45 !important;
}
[data-site-theme="dark"] .btn_confirm01.btn_confirm.rpc-floating-menu .rpc-floating-mode-toggle {
    background: #1a2a3e !important;
    border-color: #3a5a8a !important;
    color: #93c5fd !important;
}
[data-site-theme="dark"] .rpc-floating-menu .rpc-floating-control-row {
    border-right-color: #3a3a52 !important;
}
[data-site-theme="dark"] .rpc-floating-menu-vertical .rpc-floating-control-row {
    border-bottom-color: #3a3a52 !important;
}

/* ── Copilot 확인 다이얼로그 ── */
[data-site-theme="dark"] .copilot-confirm-box {
    background: linear-gradient(180deg, #1e2028 0%, #1a1c24 100%) !important;
    border-color: #3a3a42 !important;
}
[data-site-theme="dark"] .copilot-confirm-title {
    color: #d4d4d8 !important;
}
[data-site-theme="dark"] .copilot-confirm-title.is-danger { color: #fca5a5 !important; }
[data-site-theme="dark"] .copilot-confirm-title.is-info   { color: #93c5fd !important; }
[data-site-theme="dark"] .copilot-confirm-title.is-success{ color: #86efac !important; }
[data-site-theme="dark"] .copilot-confirm-title.is-warn   { color: #fde68a !important; }
[data-site-theme="dark"] .copilot-confirm-message {
    color: #c4c4cc !important;
}
[data-site-theme="dark"] .copilot-confirm-actions .btn-cancel {
    background: #1a2a3e !important;
    color: #93c5fd !important;
    border-color: #3a5a8a !important;
}

/* ── Admin-only 배지 ── */
[data-site-theme="dark"] .admin-only-badge {
    background: #1a2a3e !important;
    border-color: #3a5a8a !important;
    color: #93c5fd !important;
}

/* ── helper 텍스트 ── */
[data-site-theme="dark"] .helper {
    color: #9ca3af !important;
}

/* ── 인라인 텍스트 색 오버라이드 ── */
[data-site-theme="dark"] [style*="color:#667"],
[data-site-theme="dark"] [style*="color: #667"],
[data-site-theme="dark"] [style*="color:#888"],
[data-site-theme="dark"] [style*="color: #888"],
[data-site-theme="dark"] [style*="color:#333"],
[data-site-theme="dark"] [style*="color: #333"],
[data-site-theme="dark"] [style*="color:#234"],
[data-site-theme="dark"] [style*="color: #234"] {
    color: #c4c4cc !important;
}
[data-site-theme="dark"] [style*="color:#1f3b67"],
[data-site-theme="dark"] [style*="color:#1e3a8a"],
[data-site-theme="dark"] [style*="color:#334155"] {
    color: #93c5fd !important;
}
[data-site-theme="dark"] [style*="color:#475569"] {
    color: #9ca3af !important;
}
[data-site-theme="dark"] [style*="color:#64748b"] {
    color: #71717a !important;
}
[data-site-theme="dark"] [style*="border-top:1px dashed #d6e4f2"],
[data-site-theme="dark"] [style*="border-top: 1px dashed #d6e4f2"] {
    border-top-color: #2a3a5a !important;
}

/* ── 플로팅 메뉴 버튼 다크모드 ── */
[data-site-theme="dark"] .btn_confirm01.btn_confirm.rpc-floating-menu > input.rpc-btn-apply {
    background: linear-gradient(135deg, #166534 0%, #14532d 100%) !important;
    border-color: #15803d !important;
}
[data-site-theme="dark"] .btn_confirm01.btn_confirm.rpc-floating-menu > a.rpc-btn-list {
    background: linear-gradient(135deg, #1e3a6e 0%, #1a2f5a 100%) !important;
    border-color: #1e40af !important;
}
[data-site-theme="dark"] .btn_confirm01.btn_confirm.rpc-floating-menu > button.rpc-btn-recent {
    background: linear-gradient(135deg, #3b1f6e 0%, #2d1854 100%) !important;
    border-color: #4c1d95 !important;
}

/* ── 컨텍스트 배지 ── */
.rpc-floating-drag-handle .rpc-ctx-badge {
    display: inline-block;
    margin-left: 5px;
    padding: 1px 6px;
    border-radius: 999px;
    font-size: 10px;
    font-weight: 700;
    line-height: 1.5;
    vertical-align: middle;
    background: #dcfce7;
    color: #166534;
    border: 1px solid #bbf7d0;
}
.rpc-floating-drag-handle .rpc-ctx-badge.is-edit {
    background: #dbeafe;
    color: #1e40af;
    border-color: #bfdbfe;
}
[data-site-theme="dark"] .rpc-floating-drag-handle .rpc-ctx-badge {
    background: #14532d !important;
    color: #86efac !important;
    border-color: #166534 !important;
}
[data-site-theme="dark"] .rpc-floating-drag-handle .rpc-ctx-badge.is-edit {
    background: #1e3a6e !important;
    color: #93c5fd !important;
    border-color: #1e40af !important;
}

/* ── 미저장 변경 표시 ── */
.rpc-floating-menu-dirty > input.rpc-btn-apply {
    animation: rpc-dirty-pulse 2s ease-in-out infinite;
}
@keyframes rpc-dirty-pulse {
    0%, 100% { box-shadow: 0 0 0 0 rgba(31, 180, 92, 0.55); }
    50%       { box-shadow: 0 0 0 6px rgba(31, 180, 92, 0); }
}
[data-site-theme="dark"] .rpc-floating-menu-dirty > input.rpc-btn-apply {
    animation: rpc-dirty-pulse-dark 2s ease-in-out infinite;
}
@keyframes rpc-dirty-pulse-dark {
    0%, 100% { box-shadow: 0 0 0 0 rgba(74, 222, 128, 0.55); }
    50%       { box-shadow: 0 0 0 6px rgba(74, 222, 128, 0); }
}
.rpc-floating-menu-dirty .rpc-floating-drag-handle {
    border-color: #fbbf24 !important;
}
[data-site-theme="dark"] .rpc-floating-menu-dirty .rpc-floating-drag-handle {
    border-color: #d97706 !important;
}
</style>

<?php // echo $pg_anchor; ?>
<?php //echo str_replace("class=\"btn_confirm01 btn_confirm\"","class=\"btn_confirm01 btn_confirm\" style=\"margin-bottom:0px;\"", $frm_submit); ?>
<script>(function(){document.documentElement.classList.add('rpc-floating-init-pending');})();</script>
<?php echo $frm_submit_with_recent ?>
<?php // echo $pg_anchor; ?>

<script>
(function() {
	if (window.showCopilotToast) {
		return;
	}

	function normalizeType(type) {
		var t = (type || 'info').toLowerCase();
		if (t !== 'success' && t !== 'warn' && t !== 'error' && t !== 'info') {
			t = 'info';
		}
		return t;
	}

	function typeIcon(type) {
		if (type === 'success') return '✅';
		if (type === 'warn') return '⚠️';
		if (type === 'error') return '⛔';
		return 'ℹ️';
	}

	function ensureWrap() {
		var wrap = document.querySelector('.copilot-toast-wrap');
		if (!wrap) {
			wrap = document.createElement('div');
			wrap.className = 'copilot-toast-wrap';
			document.body.appendChild(wrap);
		}
		return wrap;
	}

	function ensureConfirmLayer() {
		var layer = document.getElementById('copilot-confirm-layer');
		if (layer) {
			return layer;
		}

		layer = document.createElement('div');
		layer.id = 'copilot-confirm-layer';
		layer.className = 'copilot-confirm-layer';
		layer.innerHTML = ''
			+ '<div class="copilot-confirm-box" role="dialog" aria-modal="true" aria-labelledby="copilot-confirm-title">'
			+ '  <div class="copilot-confirm-title" id="copilot-confirm-title">확인</div>'
			+ '  <div class="copilot-confirm-message" id="copilot-confirm-message"></div>'
			+ '  <div class="copilot-confirm-actions">'
			+ '    <button type="button" class="btn_frmline btn-cancel" id="copilot-confirm-cancel">취소</button>'
			+ '    <button type="button" class="btn_frmline btn-ok" id="copilot-confirm-ok">확인</button>'
			+ '  </div>'
			+ '</div>';

		document.body.appendChild(layer);
		return layer;
	}

	var toastLastShown = {};
	var toastMaxVisible = 3;

	function removeToastSmooth(toast, delayMs) {
		if (!toast) {
			return;
		}
		if (toast.dataset && toast.dataset.removing === '1') {
			return;
		}
		if (toast.dataset) {
			toast.dataset.removing = '1';
		}
		toast.classList.remove('show');
		setTimeout(function() {
			if (toast.parentNode) {
				toast.parentNode.removeChild(toast);
			}
		}, (typeof delayMs === 'number' && delayMs > 0) ? delayMs : 220);
	}

	function trimOldToasts(wrap, maxVisible) {
		while (wrap && wrap.children && wrap.children.length >= maxVisible) {
			var oldest = wrap.children[0];
			if (!oldest) {
				break;
			}
			removeToastSmooth(oldest, 180);
			break;
		}
	}

	window.showCopilotToast = function(message, type, options) {
		var opts = options || {};
		var dedupeKey = (opts.key || '');
		var dedupeMs = parseInt(opts.cooldownMs, 10);
		if (!dedupeMs || dedupeMs < 0) {
			dedupeMs = 2200;
		}

		if (dedupeKey) {
			var nowTs = Date.now();
			var lastTs = toastLastShown[dedupeKey] || 0;
			if (nowTs - lastTs < dedupeMs) {
				return;
			}
			toastLastShown[dedupeKey] = nowTs;
		}

		var wrap = ensureWrap();
		trimOldToasts(wrap, toastMaxVisible);
		var safeType = normalizeType(type);
		var toast = document.createElement('div');
		toast.className = 'copilot-toast toast-' + safeType;

		var iconEl = document.createElement('span');
		iconEl.className = 'toast-icon';
		iconEl.textContent = typeIcon(safeType);

		var textEl = document.createElement('span');
		textEl.className = 'toast-text';
		textEl.textContent = String(message || '');

		toast.appendChild(iconEl);
		toast.appendChild(textEl);
		wrap.appendChild(toast);

		requestAnimationFrame(function() {
			toast.classList.add('show');
		});

		var duration = parseInt(opts.durationMs, 10);
		if (!duration || duration < 1000) {
			duration = 3200;
		}

		setTimeout(function() {
			removeToastSmooth(toast, 220);
		}, duration);
	};

	window.alert = function(message) {
		window.showCopilotToast(message, 'error');
	};

	window.showCopilotConfirm = function(message, onConfirm, onCancel, options) {
		var opts = options || {};
		var layer = ensureConfirmLayer();
		var titleEl = document.getElementById('copilot-confirm-title');
		var msgEl = document.getElementById('copilot-confirm-message');
		var okBtn = document.getElementById('copilot-confirm-ok');
		var cancelBtn = document.getElementById('copilot-confirm-cancel');

		if (!layer || !titleEl || !msgEl || !okBtn || !cancelBtn) {
			if (typeof onCancel === 'function') {
				onCancel();
			}
			return;
		}

		var tone = '';
		if (opts.danger) {
			tone = 'danger';
		} else {
			tone = String(opts.type || '').toLowerCase();
			if (tone !== 'info' && tone !== 'success' && tone !== 'warn' && tone !== 'error') {
				tone = '';
			}
		}

		var baseTitle = String(opts.title || '확인');
		var titleIcon = (typeof opts.titleIcon === 'string')
			? opts.titleIcon
			: (tone === 'danger' ? '🗑️ '
				: (tone === 'warn' ? '⚠️ '
				: (tone === 'success' ? '✅ '
				: (tone === 'error' ? '⛔ '
				: (tone === 'info' ? 'ℹ️ ' : '')))));
		titleEl.textContent = titleIcon + baseTitle;
		titleEl.classList.remove('is-danger', 'is-info', 'is-success', 'is-warn', 'is-error');
		if (tone) {
			titleEl.classList.add('is-' + tone);
		}
		msgEl.textContent = String(message || '');
		okBtn.textContent = String(opts.okText || '확인');
		cancelBtn.textContent = String(opts.cancelText || '취소');
		if (opts.danger) {
			okBtn.classList.add('is-danger');
		} else {
			okBtn.classList.remove('is-danger');
		}
		layer.classList.add('open');
		setTimeout(function() {
			try { okBtn.focus(); } catch (e) {}
		}, 0);

		function closeLayer() {
			layer.classList.remove('open');
			okBtn.removeEventListener('click', handleOk);
			cancelBtn.removeEventListener('click', handleCancel);
			layer.removeEventListener('click', handleOverlayClick);
			document.removeEventListener('keydown', handleKeydown);
		}

		function handleOk() {
			closeLayer();
			if (typeof onConfirm === 'function') {
				onConfirm();
			}
		}

		function handleCancel() {
			closeLayer();
			if (typeof onCancel === 'function') {
				onCancel();
			}
		}

		function handleOverlayClick(e) {
			if (e.target === layer) {
				handleCancel();
			}
		}

		function handleKeydown(e) {
			if (e.key === 'Escape') {
				handleCancel();
			}
		}

		okBtn.addEventListener('click', handleOk);
		cancelBtn.addEventListener('click', handleCancel);
		layer.addEventListener('click', handleOverlayClick);
		document.addEventListener('keydown', handleKeydown);
	};
})();
</script>

<?php if ($w == '') { ?>
<div id="recent-config-layer" aria-hidden="true">
	<div class="recent-config-modal">
		<div class="recent-config-title">최근 입력 설정을 불러올까요?</div>
		<div id="recent-config-question" style="margin-bottom:10px;">
			신규 등록 화면입니다. 직전에 입력했던 설정값(상품코드/상품명 제외)을 기본값으로 적용할 수 있습니다.
		</div>

		<div id="recent-config-picker" style="display:none;">
			<div style="margin-bottom:8px;">
				<label for="recent-config-select"><strong>최근 설정 세트 선택 (최대 100개)</strong></label>
				<select id="recent-config-select" class="frm_input" style="width:100%; margin-top:6px;"></select>
			</div>
			<div id="recent-config-preview" class="recent-config-preview"></div>
			<div class="recent-config-resize-help">※ 제목 바를 드래그하여 이동 / 우측 하단을 드래그하여 크기 조절</div>
		</div>

		<div class="recent-config-btns" id="recent-config-question-btns">
			<button type="button" id="recent-config-quick" class="btn_frmline recent-btn recent-btn-primary">최근값 즉시 적용(추천)</button>
			<button type="button" id="recent-config-yes" class="btn_frmline recent-btn recent-btn-outline">예(최근 설정 선택)</button>
			<button type="button" id="recent-config-no" class="btn_frmline recent-btn recent-btn-ghost">아니오(기본값 유지)</button>
		</div>

		<div class="recent-config-btns" id="recent-config-apply-btns" style="display:none;">
			<button type="button" id="recent-config-cancel" class="btn_frmline recent-btn recent-btn-ghost">닫기</button>
			<button type="button" id="recent-config-apply" class="btn_frmline recent-btn recent-btn-success">선택값 적용</button>
		</div>
	</div>
</div>
<?php } ?>

<section id="anc_sitfrm_ini" class="anc-section">
    <h2 class="h2_frm">VPN-Mall 상품기본정보</h2>
	<div class="tbl_frm01 tbl_wrap">
        <table>
        <caption>VPN-Mall 상품기본정보 입력</caption>
        <colgroup>
            <col class="grid_3">
            <col>
        </colgroup>
        <tbody>
		<tr style="display:none;">
            <th scope="row">상품코드</th>
            <td>
                <?php
                if ($w == '') {
                    sql_query(" UPDATE g5_shop_item_it_id_counter SET it_id_last = it_id_last + 1 ");
                    $it_id_last = sql_fetch(" SELECT it_id_last FROM g5_shop_item_it_id_counter ");
                    $it_id = $it_id_last['it_id_last'];
                    echo help("상품코드는 자동으로 생성됩니다.");
                    echo $it_id;
                    echo '<input type="hidden" name="it_id" value="'.$it_id.'" id="it_id" required class="frm_input required" size="20" maxLength="32" readonly>';
                } else {
					echo '<input type="hidden" name="it_id" value="'.$it['it_id'].'" id="it_id" readonly>';

                    echo '<a href="'.G5_SHOP_URL.'/item.php?it_id='.$it_id.'" target="blank" class="btn_frmline">상품확인</a>';
                    echo '<a href="./itemuselist.php?sfl=a.it_id&amp;stx='.$it_id.'" target="blank" class="btn_frmline">관련후기</a>';
                    echo '<a href="./itemqalist.php?sfl=a.it_id&amp;stx='.$it_id.'" target="blank" class="btn_frmline">관련문의</a>';
                }
                ?>
            </td>
        </tr>

		<tr>
            <th scope="row"><label for="it_name">상품명</label></th>
            <td>
				<?php if ($it['it_name']) { ?>
					<?php //echo help("상품명은 자동으로 생성됩니다."); ?>
					<?php echo "<span style='font-size:1.45em; font-weight:800; margin-right:10px;'>".get_text(cut_str($it['it_name'], 250, ""))."</span>"; ?>
                	<input type="hidden" name="it_name" value="<?php echo get_text(cut_str($it['it_name'], 250, "")); ?>" id="it_name" class="frm_input" readonly>
					<a href="<?php echo G5_SHOP_URL; ?>/item.php?it_id=<?php echo $it_id; ?>" target="blank" class="btn_frmline">상품확인</a>
                    <a href="./itemuselist.php?sfl=a.it_id&amp;stx=<?php echo $it_id; ?>" target="blank" class="btn_frmline">관련후기</a>
                    <a href="./itemqalist.php?sfl=a.it_id&amp;stx=<?php echo $it_id; ?>" target="blank" class="btn_frmline">관련문의</a>
				<?php } else { ?>
					<?php echo help("상품명은 자동으로 생성됩니다."); ?>
					<?php echo "VPN-" . $it_id; ?>
					<input type="hidden" name="it_name" value="VPN-<?php echo $it_id; ?>" id="it_name" class="frm_input" readonly>
				<?php } ?>
            </td>
        </tr>

		<tr>
			<th scope="row"><label for="it_spec_mgr_nickname">관리컴퓨터별명</label></th>
			<td>
				<?php echo help("관리컴퓨터별명은 판매자 [{$member['mb_name']}] 님만 보실 수 있습니다. 쇼핑몰(플랫폼)에는 공개되지 않습니다."); ?>
				<input type="text" name="it_spec_mgr_nickname" value="<?php echo get_text($it['it_spec_mgr_nickname']); ?>" id="it_spec_mgr_nickname" class="frm_input" size="40">
				<div id="it_spec_mgr_nickname_dup_notice" class="helper" style="display:none; margin-top:4px;"></div>
				<script>
				(function() {
					var inputEl = document.getElementById('it_spec_mgr_nickname');
					var noticeEl = document.getElementById('it_spec_mgr_nickname_dup_notice');
					var ownerId = <?php echo json_encode(($it['pt_id']=='') ? $member['mb_id'] : $it['pt_id']); ?>;
					if (!inputEl || !noticeEl) {
						return;
					}

					var timer = null;
					var lastQueried = '';
					var requestSeq = 0;

					function setNotice(message, isDuplicate) {
						if (!message) {
							noticeEl.style.display = 'none';
							noticeEl.textContent = '';
							noticeEl.style.color = '';
							inputEl.style.borderColor = '';
							return;
						}

						noticeEl.style.display = 'block';
						noticeEl.textContent = message;
						noticeEl.style.color = isDuplicate ? '#c0392b' : '#5b747e';
						inputEl.style.borderColor = isDuplicate ? '#d9534f' : '';
					}

					function checkDuplicateNow() {
						var nickname = (inputEl.value || '').trim();
						if (!nickname) {
							setNotice('', false);
							lastQueried = '';
							return;
						}

						if (nickname === lastQueried) {
							return;
						}

						lastQueried = nickname;
						var requestedNickname = nickname;
						var seq = ++requestSeq;

						$.ajax({
							url: './ajax.it_spec_mgr_nickname.php',
							type: 'POST',
							dataType: 'json',
							cache: false,
							data: {
								it_spec_mgr_nickname: nickname,
								it_id: (document.getElementById('it_id') ? document.getElementById('it_id').value : ''),
								owner_id: ownerId || ''
							},
							success: function(res) {
								if (seq !== requestSeq) {
									return;
								}
								if (((inputEl.value || '').trim()) !== requestedNickname) {
									return;
								}
								if (!res || res.error) {
									setNotice('', false);
									return;
								}

								if (res.duplicate) {
									var msg = res.message || '중복된 관리컴퓨터별명입니다.';
									setNotice('⚠ ' + msg + ' (저장은 가능합니다)', true);
								} else {
									setNotice('사용 가능한 관리컴퓨터별명입니다.', false);
								}
							},
							error: function() {
								if (seq !== requestSeq) {
									return;
								}
								setNotice('', false);
							}
						});
					}

					inputEl.addEventListener('input', function() {
						if (timer) {
							clearTimeout(timer);
						}
						timer = setTimeout(checkDuplicateNow, 300);
					});

					inputEl.addEventListener('blur', function() {
						checkDuplicateNow();
					});

					if ((inputEl.value || '').trim()) {
						checkDuplicateNow();
					}
				})();
				</script>
			</td>
		</tr>

		<tr>
            <th scope="row"><label for="it_spec_vpn_type">상품종류</label></th>
            <td>
                <?php
                $vpn_type_options = array('' => '-- 미지정 --', 'IKEv2' => 'IKEv2', 'PPTP' => 'PPTP', 'OpenVPN' => 'OpenVPN', 'WireGuard' => 'WireGuard', 'L2TP' => 'L2TP');
                $cur_vpn_type = isset($it['it_spec_vpn_type']) ? trim((string)$it['it_spec_vpn_type']) : '';
                if ($cur_vpn_type === '' && !empty($it['it_spec_os'])) {
                    $_os_proto_map = ['IKEV2'=>'IKEv2','PPTP'=>'PPTP','OPENVPN'=>'OpenVPN','WIREGUARD'=>'WireGuard','L2TP'=>'L2TP'];
                    $_os_key = strtoupper(trim(explode('-', (string)$it['it_spec_os'])[0]));
                    if (isset($_os_proto_map[$_os_key])) $cur_vpn_type = $_os_proto_map[$_os_key];
                }
                ?>
                <select name="it_spec_vpn_type" id="it_spec_vpn_type" class="frm_input" style="width:160px;">
                    <?php foreach($vpn_type_options as $vv => $vl) { ?>
                    <option value="<?php echo $vv; ?>"<?php echo ($cur_vpn_type === $vv) ? ' selected' : ''; ?>><?php echo $vl; ?></option>
                    <?php } ?>
                </select>
                <span class="help-text" style="margin-left:8px;font-size:12px;color:#888;">VPN 프로토콜 종류 (쇼핑몰 목록·상세페이지에 표시됩니다)</span>
            </td>
        </tr>

		<tr>
            <th scope="row"><label for="it_spec_grade">상품등급</label></th>
            <td>
                <?php
                $grade_options = array('' => '-- 미지정 --', 'BASIC' => 'BASIC', 'PLUS' => 'PLUS', 'PRO' => 'PRO', 'ULTRA' => 'ULTRA', 'MAX' => 'MAX');
                $cur_grade = isset($it['it_spec_grade']) ? strtoupper(trim((string)$it['it_spec_grade'])) : '';
                ?>
                <select name="it_spec_grade" id="it_spec_grade" class="frm_input" style="width:160px;">
                    <?php foreach($grade_options as $gv => $gl) { ?>
                    <option value="<?php echo $gv; ?>"<?php echo ($cur_grade === $gv) ? ' selected' : ''; ?>><?php echo $gl; ?></option>
                    <?php } ?>
                </select>
                <span class="help-text" style="margin-left:8px;font-size:12px;color:#888;">VPN 상품 등급 (쇼핑몰 목록·상세페이지에 표시됩니다)</span>
            </td>
        </tr>

		<tr>
            <th scope="row"><label for="it_use">상품판매</label></th>
            <td>
                <?php echo help("잠시 판매를 중단하거나 재고가 없을 경우에 체크를 해제해 놓으면 쇼핑몰(플랫폼)에 노출되지 않습니다."); ?>
				<?php if ($w == '') { ?>
                	<label><input type="checkbox" name="it_use" value="1" id="it_use" checked> 예</label>
				<?php } else { ?>
					<label><input type="checkbox" name="it_use" value="1" id="it_use" <?php echo ($it['it_use']) ? "checked" : ""; ?>> 예</label>
				<?php } ?>
            </td>
        </tr>

		<tr>
			<th scope="row"><label for="it_soldout">상품품절</label></th>
			<td>
				<?php echo help("잠시 판매를 중단하거나 재고가 없을 경우에 체크해 놓으면 품절상품으로 표시됩니다."); ?>
				<label><input type="checkbox" name="it_soldout" value="1" id="it_soldout" <?php echo ($it['it_soldout']) ? "checked" : ""; ?>> 예</label>
			</td>
		</tr>


		<!-- 로딩바 표시 /shop/partner/itemform.php 에 있음 JSLEE { -->
		<style>
			.loading-bar-enter {
				animation: loading-bar-enter-progress 1s linear infinite;
			}

			@keyframes loading-bar-enter-progress {
				0% {
					width: 0%;
				}
				50% {
					width: 50%;
				}
				100% {
					width: 100%;
				}
			}
		</style>
		<div id="loading-overlay_enter" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); z-index: 9999;">
			<div style="position: absolute; top: 50%; left: calc(50% + 112.5px); transform: translate(-50%, -50%);">
				<div class="loading-bar-enter" style="width: 0%; height: 5px; background-color: #ccc; border-radius: 2.5px;"></div>
				<p style="font-size: 20px; color: white;">Loading...</p>
			</div>
		</div>
		<!-- 로딩바 표시 /shop/partner/itemform.php 에 있음 JSLEE } -->

		<!-- 저장 중 로딩바 표시 (새로 추가됨) { -->
		<div id="loading-overlay" style="display:none;"></div>
		<!-- 저장 중 로딩바 표시 (새로 추가됨) } -->

		<script>
			$(document).ready(function() {
				function hideEnterLoadingOverlay() {
					var overlay = document.getElementById('loading-overlay_enter');
					if (overlay) {
						overlay.style.display = 'none';
					}
				}

				if (window.requestAnimationFrame) {
					window.requestAnimationFrame(hideEnterLoadingOverlay);
				} else {
					setTimeout(hideEnterLoadingOverlay, 0);
				}

				window.addEventListener('load', hideEnterLoadingOverlay);
			});
		</script>



		<!-- 관리자 전용 필드 (유지) -->
		<?php if($is_auth) { // 관리자일 때만 출력 ?>
			<tr>
				<th scope="row" class="admin-only-title"><label for="it_cust_price">시중가격</label><?php echo $admin_only_badge; ?></th>
				<td>
					<?php echo help("입력하지 않으면 상품상세페이지에 출력되지 않습니다."); ?>
					<input type="text" name="it_cust_price" value="<?php echo $it['it_cust_price']; ?>" id="it_cust_price" class="frm_input" size="8"> Point
				</td>
			</tr>
		<?php } // 관리자 끝 ?>

        <!-- 포인트 관련 필드 삭제 (기본값 설정 로직만 남김 필요시) -->
        <input type="hidden" name="it_point_type" value="0">
        <input type="hidden" name="it_point" value="0">
        <input type="hidden" name="it_supply_point" value="0">

		<?php if($is_auth) { // 관리자일 때만 출력 ?>
			<tr>
				<th scope="row" class="admin-only-title"><label for="it_stock_sms">재입고SMS 알림</label><?php echo $admin_only_badge; ?></th>
				<td>
					<?php echo help("상품이 품절인 경우에 체크해 놓으면 상품상세보기에서 고객이 재입고SMS 알림을 신청할 수 있게 됩니다."); ?>
					<input type="checkbox" name="it_stock_sms" value="1" id="it_stock_sms" <?php echo ($it['it_stock_sms']) ? "checked" : ""; ?>> 예
				</td>
			</tr>
		<?php } // 관리자 끝 ?>

        <!-- 재고 관련 삭제 (VPN은 보통 무제한/기간제이므로 재고 99999 고정) -->
		<input type="hidden" name="it_stock_qty" value="99999" id="it_stock_qty">
		<input type="hidden" name="it_noti_qty" value="0">

        <!-- 판매유형/셀러ID 숨김 처리 유지/삭제 -->
        <input type="hidden" name="it_spec_sales_type" value="vpn-mall" id="it_spec_sales_type">
        <input type="hidden" name="it_spec_partner_id" value="<?php echo ($it['pt_id']=='')?$member['mb_id']:$it['pt_id']; ?>" id="it_spec_partner_id">
        <!-- 상품종류(pt_it)는 VPN은 온라인상품으로 고정 -->
        <input type="hidden" name="pt_it" value="2" id="pt_it">

		<?php if($is_auth) { // 관리자일 때만 출력 ?>
			<tr>
				<th scope="row" class="admin-only-title"><label for="it_basic">기본설명</label><?php echo $admin_only_badge; ?></th>
				<td>
					<?php echo help("상품명 하단에 상품에 대한 추가적인 설명이 필요한 경우에 입력합니다. HTML 입력도 가능합니다."); ?>
					<input type="text" name="it_basic" value="<?php echo get_text(html_purifier($it['it_basic'])); ?>" id="it_basic" class="frm_input sl">
				</td>
			</tr>
			<tr>
				<th scope="row" class="admin-only-title"><label for="pt_tag">상품태그</label><?php echo $admin_only_badge; ?></th>
				<td>
					<?php echo help("등록할 상품태그를 콤마(,)로 구분해서 입력합니다."); ?>
					<input type="text" name="pt_tag" value="<?php echo get_text($it['pt_tag']); ?>" id="pt_tag" class="frm_input sl">
				</td>
			</tr>
			<tr>
				<th scope="row" class="admin-only-title"><label for="pt_show">판매자센터순서</label><?php echo $admin_only_badge; ?></th>
				<td>
					<?php echo help("숫자가 작을 수록 판매자센터 상위에 출력되며, -2147483648 부터 2147483647 까지 입력가능합니다. 미입력시 자동으로 출력됩니다."); ?>
					<input type="text" name="pt_show" value="<?php echo $it['pt_show']; ?>" id="pt_show" class="frm_input" size="12">
				</td>
			</tr>
		<?php } // 관리자 끝 ?>

		<?php if($is_auth) { // 관리자일 때만 출력 ?>
			<tr>
				<th scope="row" class="admin-only-title"><label for="it_order">출력순서</label><?php echo $admin_only_badge; ?></th>
				<td>
					<?php echo help("숫자가 작을 수록 상위에 출력되며, -2147483648 부터 2147483647 까지 입력가능합니다. 미입력시 자동으로 출력됩니다."); ?>
					<input type="text" name="it_order" value="<?php echo $it['it_order']; ?>" id="it_order" class="frm_input" size="12">
				</td>
			</tr>
			<tr>
				<th scope="row" class="admin-only-title">상품유형<?php echo $admin_only_badge; ?></th>
				<td>
					<?php echo help("메인화면에 유형별로 출력할때 사용합니다. 목록에서 유형별로 정렬할때 체크된 것이 가장 먼저 출력됩니다."); ?>
					<input type="checkbox" name="it_type1" value="1" <?php echo ($it['it_type1'] ? "checked" : ""); ?> id="it_type1">
					<label for="it_type1">히트 <img src="<?php echo G5_SHOP_URL; ?>/img/icon_hit.gif" alt=""></label>
					&nbsp;
					<input type="checkbox" name="it_type2" value="1" <?php echo ($it['it_type2'] ? "checked" : ""); ?> id="it_type2">
					<label for="it_type2">추천 <img src="<?php echo G5_SHOP_URL; ?>/img/icon_rec.gif" alt=""></label>
					&nbsp;
					<input type="checkbox" name="it_type3" value="1" <?php echo ($it['it_type3'] ? "checked" : ""); ?> id="it_type3">
					<label for="it_type3">새글 <img src="<?php echo G5_SHOP_URL; ?>/img/icon_new.gif" alt=""></label>
					&nbsp;
					<input type="checkbox" name="it_type4" value="1" <?php echo ($it['it_type4'] ? "checked" : ""); ?> id="it_type4">
					<label for="it_type4">인기 <img src="<?php echo G5_SHOP_URL; ?>/img/icon_best.gif" alt=""></label>
					&nbsp;
					<input type="checkbox" name="it_type5" value="1" <?php echo ($it['it_type5'] ? "checked" : ""); ?> id="it_type5">
					<label for="it_type5">할인 <img src="<?php echo G5_SHOP_URL; ?>/img/icon_discount.gif" alt=""></label>
					&nbsp;
					<input type="checkbox" name="pt_main" value="1" <?php echo ($it['pt_main'] ? "checked" : ""); ?> id="pt_main">
					<label for="pt_main">메인</label>
				</td>
			</tr>
		<?php } // 관리자 끝 ?>

		<!-- PC 하드웨어 스펙 (삭제됨) -->

         <!-- 카테고리(분류) UI 삭제 (값 유지를 위해 hidden 처리) -->
        <input type="hidden" name="ca_id" value="<?php echo ($it['ca_id']) ? $it['ca_id'] : '301010'; ?>" id="ca_id">
        <!-- 카테고리 Select Box 코드 삭제됨 -->

		<!-- VPN 설정 정보 입력 -->
		<?php
			// VPN 설정 정보 (기존 it_spec_remote_sw 재활용)
			// VPN Type A: Server IP/URL, ID, PW
			// VPN Type B: Protocol Only (Managed by Platform)
			// But the prompt says Users might input Server Address, ID, PW for Type A.
			// Reusing it_spec_remote_sw JSON structure for VPN Config.
			// Structure:
			// Program -> Protocol (e.g., IKEv2, OpenVPN)
			// RemoteIP -> Server Address
			// ID -> VPN ID
			// PWD -> VPN Password
			$jsonData_vpn_config = json_decode($it['it_spec_remote_sw'], true);

			// VPN 프로토콜 목록 (DB에서 동적 로드) - JSLEE
            // ca_id 3020으로 시작하는 카테고리(클라이언트군)에서 프로토콜명 추출
            $vpnProtocols = array();
            $sql_vpn_proto = " select ca_name from {$g5['g5_shop_category_table']} where ca_use = '1' and pt_use = '1' and (ca_id like '30%' or ca_id like '40%') order by ca_order, ca_id ";
            $res_vpn_proto = sql_query($sql_vpn_proto);
            while ($row_vpn_proto = sql_fetch_array($res_vpn_proto)) {
                // ca_name 예: "IKEv2-Client" 그대로 사용
                if($row_vpn_proto['ca_name']) {
                     $vpnProtocols[] = $row_vpn_proto['ca_name'];
                }
            }
            $vpnProtocols = array_unique($vpnProtocols); // 중복 제거
		?>
		<tr>
			<th scope="row"><label for="it_spec_remote_sw">VPN 접속정보</label></th>
			<td>
				<style>
                    /* VPN Configuration Section - Sophisticated UI */
                    .vpn-config-list {
                        display: flex;
                        flex-direction: column;
                        gap: 15px;
                    }
					.vpn-config-item {
						background: #ffffff;
						border: 1px solid #e2e8f0;
                        border-radius: 8px;
						padding: 20px;
						max-width: 980px;
                        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03); /* Soft shadow */
                        transition: all 0.2s ease;
					}
                    .vpn-config-item:hover {
                        box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.05), 0 4px 6px -2px rgba(0, 0, 0, 0.025);
                        border-color: #cbd5e0;
                    }
                    .vpn-config-row {
                        display: flex;
                        flex-wrap: wrap;
						justify-content: flex-start;
                        gap: 20px;
                        align-items: flex-end;
                        margin-bottom: 5px;
                    }
                    .vpn-input-group {
                        display: flex;
                        flex-direction: column;
						flex: 0 1 auto;
						min-width: 0;
					}
					.vpn-input-group.protocol-group {
						width: 200px;
						max-width: 100%;
					}
					.vpn-input-group.server-group {
						width: 500px;
						max-width: 100%;
					}
					.vpn-input-group.credential-group {
						width: 260px;
						max-width: 100%;
                    }
                    .vpn-input-group label {
                        font-weight: 600;
                        font-size: 13px;
                        margin-bottom: 6px;
                        color: #4a5568; /* Slate 700 */
                        text-transform: uppercase;
                        letter-spacing: 0.03em;
                    }
                    .vpn-input-group .frm_input {
                        width: 100%;
                    }
					@media (max-width: 1200px) {
						.vpn-input-group.server-group {
							width: 100%;
						}
						.vpn-input-group.credential-group {
							width: calc(50% - 10px);
						}
					}
					@media (max-width: 760px) {
						.vpn-input-group.protocol-group,
						.vpn-input-group.server-group,
						.vpn-input-group.credential-group {
							width: 100%;
						}
					}
                    .btn_del_vpn {
                        height: 40px; /* MATCH INPUT HEIGHT EXACTLY */
                        line-height: normal; /* Use flex centering or line-height matching */
                        padding: 0 18px;
                        background: #fff;
                        border: 1px solid #fc8181; /* Red-300 */
                        color: #e53e3e; /* Red-600 */
                        cursor: pointer;
                        font-size: 14px;
                        border-radius: 4px;
                        font-weight: 500;
                        white-space: nowrap;
                        transition: all 0.2s;
                        display: inline-flex;
                        align-items: center;
                        justify-content: center;
                    }
                    .btn_del_vpn:hover {
                        background: #e53e3e;
                        color: #fff;
                        border-color: #c53030;
                        box-shadow: 0 2px 4px rgba(229, 62, 62, 0.2);
                    }
                    .vpn-divider {
                        height: 1px;
                        background: #edf2f7; /* Very light gray */
                        margin: 15px 0;
                        width: 100%;
                    }
                    .vpn-flag-display {
                        position: absolute;
                        right: 10px;
                        top: 50%;
                        transform: translateY(-50%);
                        display: flex;
                        align-items: center;
                        pointer-events: none; /* Make sure clicks go through to input if needed, though it is on the right */
                        background: rgba(255,255,255,0.8); /* Slight background to ensure readablity */
                        padding: 2px 5px;
                        border-radius: 4px;
                    }
                    .vpn-flag-display img {
                        width: 24px;
                        height: auto;
                        margin-right: 5px;
                        border: 1px solid #ddd;
                        box-shadow: 0 1px 2px rgba(0,0,0,0.1);
                    }
                    .vpn-flag-display span {
                        font-size: 11px;
                        color: #555;
                        font-weight: 600;
                    }
					.vpn-dup-notice {
						display: none;
						margin-top: 10px;
						padding: 10px;
						border-radius: 4px;
						font-size: 12px;
						line-height: 1.5;
					}
					.vpn-dup-notice.dup-ok {
						display: block;
						background-color: #f0fff4;
						border: 1px solid #9ae6b4;
						color: #276749;
					}
					.vpn-dup-notice.dup-error {
						display: block;
						background-color: #fff5f5;
						border: 1px solid #feb2b2;
						color: #c53030;
					}
					.vpn-dup-highlight {
						border-color: #e53e3e !important;
						box-shadow: 0 0 0 1px rgba(229, 62, 62, 0.2);
					}
				</style>
				<div id="vpnConfigList" class="vpn-config-list">
					<?php
					if (is_array($jsonData_vpn_config) && !empty($jsonData_vpn_config)) {
						foreach ($jsonData_vpn_config as $index => $data) {
							// Map old keys to new VPN meaning
							$protocol = $data["Program__{$index}"] ?? '';
							$server = $data["RemoteIP__{$index}"] ?? '';
							$vpnId = $data["{$protocol}_ID__{$index}"] ?? '';
							$vpnPwd = $data["{$protocol}_PWD__{$index}"] ?? '';

							$countryName = $data["RemoteIP_CountryName__{$index}"] ?? '';
							$countryCode = $data["RemoteIP_CountryCode__{$index}"] ?? '';
							$cityName = $data["RemoteIP_City__{$index}"] ?? '';

							$flagDisplay = '';
                            $paddingRight = '';
							if($countryCode) {
								$flagUrl = G5_DATA_URL . '/item/img_nation_flag/svg/' . strtolower($countryCode) . '.svg';
								$flagDisplay = "
								<div class='vpn-flag-display visible'>
									<img src='{$flagUrl}' alt='{$countryName}'>
									<span>{$countryName}</span>
								</div>";
                                $paddingRight = 'padding-right: 140px;';
							}

                            if(!$flagDisplay) {
                                $flagDisplay = "
								<div class='vpn-flag-display' style='display:none;' data-status='pending'>
									<img src='' alt=''>
									<span></span>
								</div>";
                            }

							echo "
							<div class='vpn-config-item'>
                                <div class='vpn-config-row'>
                                    <div class='vpn-input-group protocol-group'>
                                        <label>VPN상품구분(프로토콜)</label>
								        <select name='remoteProgram[]' class='vpnProtocol frm_input' required>
									        <option value=''>- 선택 -</option>";
									        foreach ($vpnProtocols as $p) {
										        $selected = ($p == $protocol) ? 'selected' : '';
										        echo "<option value='{$p}' {$selected}>{$p}</option>";
									        }
							echo "      </select>
                                    </div>
									<div class='vpn-input-group server-group'>
                                        <label>서버주소 (IP/Domain) <span class='vpn-auth-status' style='font-size:11px; font-weight:bold; margin-left:5px;'></span></label>
                                        <div style='position:relative;'>
								            <input type='text' name='remoteIp[]' class='vpnServer frm_input' value='{$server}' placeholder='예: 123.45.67.89 또는 vpn.example.com' style='{$paddingRight}' required>
                                            {$flagDisplay}
                                        </div>
                                    </div>
                                </div>
                                <div class='vpn-divider'></div>
                                <div class='vpn-config-row'>
									<div class='vpn-input-group credential-group'>
                                        <label>ID (계정)</label>
								        <input type='text' name='remoteId[]' class='vpnId frm_input' value='{$vpnId}' required>
                                    </div>
									<div class='vpn-input-group credential-group'>
                                        <label>Password (암호)</label>
								        <input type='text' name='remotePassword[]' class='vpnPassword frm_input' value='{$vpnPwd}' required>
                                    </div>
                                    <button type='button' class='btn_del_vpn'>삭제</button>
                                </div>
                                <div class='vpn-manual-check-warning' style='display:none; background-color: #fff3cd; border: 1px solid #ffeeba; color: #856404; padding: 10px; border-radius: 4px; font-size: 12px; margin-top: 10px;'>
                                    ※ <strong>주의:</strong> 해당 프로토콜은 ID/비밀번호 자동 검증이 지원되지 않습니다.<br>
                                    서버에 해당 ID와 비밀번호가 정상적으로 세팅되어 실제 접속이 가능한지 <strong>반드시 별도로 확인</strong>해 주시기 바랍니다.<br>
                                    (검증되지 않은 계정 정보 등록 시, 구매 고객이 접속 장애를 겪을 수 있습니다.)
                                </div>
								<div class='vpn-dup-notice'></div>
                                <input type='hidden' name='remoteCountryCode[]' value='{$countryCode}' class='vpnCountryCode'>
								<input type='hidden' name='remoteCountryName[]' value='{$countryName}' class='vpnCountryName'>
								<input type='hidden' name='remoteCity[]' value='{$cityName}' class='vpnCity'>
							</div>";
						}
					}
					?>
				</div>
                <div style="margin-top:10px;">
				    <button type="button" id="addVpnConfig" class="btn_frmline">VPN 접속정보 추가 +</button>
                </div>
				<script>
					$(document).ready(function() {
						var vpnDupOwnerId = <?php echo json_encode(($it['pt_id']=='') ? $member['mb_id'] : $it['pt_id']); ?>;

						function normalizeVpnField(value) {
							return $.trim((value || '').toString()).toLowerCase();
						}

						function buildVpnDupKey(protocol, server, vpnId) {
							var p = normalizeVpnField(protocol);
							var s = normalizeVpnField(server);
							var i = normalizeVpnField(vpnId);
							if (!p || !s || !i) {
								return '';
							}
							return p + '|' + s + '|' + i;
						}

						function clearVpnDupUi($container) {
							$container.data('dup-status', '');
							$container.data('dup-message', '');
							$container.find('.vpnProtocol, .vpnServer, .vpnId').removeClass('vpn-dup-highlight');
							$container.find('.vpn-dup-notice').removeClass('dup-ok dup-error').hide().text('');
						}

						function setVpnDupUi($container, message, isDuplicate) {
							var $notice = $container.find('.vpn-dup-notice');
							$container.find('.vpnProtocol, .vpnServer, .vpnId').toggleClass('vpn-dup-highlight', !!isDuplicate);
							$notice.removeClass('dup-ok dup-error');

							if (!message) {
								$notice.hide().text('');
								return;
							}

							$notice.addClass(isDuplicate ? 'dup-error' : 'dup-ok').text(message).show();
						}

						function checkLocalVpnDupAndMark() {
							var map = {};
							var hasDuplicate = false;

							$('.vpn-config-item').each(function() {
								var $item = $(this);
								clearVpnDupUi($item);

								var protocol = $item.find('.vpnProtocol').val();
								var server = $item.find('.vpnServer').val();
								var vpnId = $item.find('.vpnId').val();
								var key = buildVpnDupKey(protocol, server, vpnId);
								if (!key) {
									return true;
								}

								if (!map[key]) {
									map[key] = [];
								}
								map[key].push($item);
							});

							$.each(map, function(key, items) {
								if (!items || items.length < 2) {
									return true;
								}

								hasDuplicate = true;
								for (var i = 0; i < items.length; i++) {
									var $dupItem = items[i];
									$dupItem.data('dup-status', 'duplicate');
									$dupItem.data('dup-message', '동일한 VPN 접속정보(프로토콜/서버주소/ID)가 이 상품 내에서 중복되었습니다.');
									setVpnDupUi($dupItem, '⚠ 동일한 VPN 접속정보(프로토콜/서버주소/ID)가 이 상품 내에서 중복되었습니다.', true);
								}
								showVpnDupToast('동일한 VPN 접속정보(프로토콜/서버주소/ID)가 이 상품 내에서 중복되었습니다.', 'warn', key);
							});

							return hasDuplicate;
						}

						function checkRemoteVpnDupForRow($container, options) {
							var opts = options || {};
							var protocol = $container.find('.vpnProtocol').val();
							var server = $container.find('.vpnServer').val();
							var vpnId = $container.find('.vpnId').val();
							var key = buildVpnDupKey(protocol, server, vpnId);

							if (!key) {
								clearVpnDupUi($container);
								return { duplicate: false, message: '' };
							}

							if (checkLocalVpnDupAndMark()) {
								return { duplicate: true, message: '동일한 VPN 접속정보(프로토콜/서버주소/ID)가 이 상품 내에서 중복되었습니다.' };
							}

							var resultObj = { duplicate: false, message: '' };
							$container.data('dup-status', 'checking');

							$.ajax({
								url: './ajax.vpn_conn_dup.php',
								type: 'POST',
								dataType: 'json',
								cache: false,
								async: (opts.sync === true ? false : true),
								data: {
									protocol: protocol,
									server: server,
									vpn_id: vpnId,
									it_id: (document.getElementById('it_id') ? document.getElementById('it_id').value : ''),
									owner_id: vpnDupOwnerId || ''
								},
								success: function(res) {
									if (!res || res.error) {
										$container.data('dup-status', '');
										return;
									}

									if (res.duplicate) {
										var msg = res.message || '동일한 VPN 접속정보(프로토콜/서버주소/ID)가 이미 존재합니다.';
										$container.data('dup-status', 'duplicate');
										$container.data('dup-message', msg);
										setVpnDupUi($container, '⚠ ' + msg, true);
										showVpnDupToast(msg, 'warn', key);
										resultObj.duplicate = true;
										resultObj.message = msg;
									} else {
										$container.data('dup-status', 'ok');
										$container.data('dup-message', '사용가능한 VPN 접속정보입니다.');
										if (!opts.silentSuccess) {
											setVpnDupUi($container, '사용가능한 VPN 접속정보입니다.', false);
										}
									}
								},
								error: function() {
									$container.data('dup-status', '');
								}
							});

							return resultObj;
						}

						function scheduleVpnDupCheck($container, immediate) {
							if (!$container || !$container.length) {
								return;
							}

							var timer = $container.data('dup-timer');
							if (timer) {
								clearTimeout(timer);
							}

							var delay = immediate ? 0 : 300;
							timer = setTimeout(function() {
								checkRemoteVpnDupForRow($container, { sync: false, silentSuccess: false });
							}, delay);

							$container.data('dup-timer', timer);
						}

						function showVpnDupToast(message, type, keyPart) {
							if (!window.showCopilotToast) {
								return;
							}
							window.showCopilotToast(message, type || 'warn', {
								key: 'vpn-dup-' + (keyPart || 'general'),
								cooldownMs: 2600,
								durationMs: 7000
							});
						}

						function hideSubmitLoadingOverlay() {
							var overlay = document.getElementById('loading-overlay_enter');
							if (overlay) {
								overlay.style.display = 'none';
							}
						}

						function focusDuplicateRow($target) {
							if (!$target || !$target.length) {
								return;
							}

							var targetEl = $target.find('.vpnId, .vpnServer, .vpnProtocol').filter(':visible').first();
							if (!targetEl.length) {
								targetEl = $target.find('.vpnId, .vpnServer, .vpnProtocol').first();
							}

							if ($target[0] && typeof $target[0].scrollIntoView === 'function') {
								try {
									$target[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
								} catch (e) {
									$target[0].scrollIntoView();
								}
							}

							$target.addClass('vpn-dup-highlight');
							setTimeout(function() {
								$target.removeClass('vpn-dup-highlight');
							}, 2200);

							if (targetEl.length && typeof targetEl.focus === 'function') {
								targetEl.focus();
							}
						}

						function showVpnDupLayer(message, $target, keyPart) {
							hideSubmitLoadingOverlay();

							var finalMessage = message || '동일한 VPN 접속정보(프로토콜/서버주소/ID)가 이미 등록되어 있어 저장할 수 없습니다. 중복 항목을 수정한 후 다시 적용해 주세요.';
							if (typeof window.showCopilotConfirm === 'function') {
								window.showCopilotConfirm(finalMessage, function() {
									focusDuplicateRow($target);
								}, null, {
									title: '저장 실패 안내',
									type: 'error',
									okText: '중복 항목으로 이동',
									cancelText: '닫기'
								});
								return;
							}

							showVpnDupToast(finalMessage, 'warn', keyPart || 'dup-layer');
							focusDuplicateRow($target);
						}

                        // GeoIP Lookup
                        $(document).on('change blur', '.vpnServer', function() {
                            var $input = $(this);
                            var ip = $input.val().trim();
                            var $container = $input.closest('.vpn-config-item');
                            var $flagDisplay = $input.siblings('.vpn-flag-display');

                            var $countryCodeInput = $container.find('.vpnCountryCode');
                            var $countryNameInput = $container.find('.vpnCountryName');

                            if(ip === '') {
                                $flagDisplay.hide();
                                $input.css('padding-right', '');
                                return;
                            }

                            if($input.data('last-checked-ip') === ip) return;
                            $input.data('last-checked-ip', ip);

                            // Show loading state
                            $flagDisplay.find('img').hide(); // Hide flag image during check
                            $flagDisplay.find('span').text('확인중...'); // Checking...
                            $flagDisplay.css('display', 'flex');
                            $flagDisplay.show();
                            $input.css('padding-right', '140px');

                            $.ajax({
                                url: '<?php echo G5_SHOP_URL; ?>/partner/ajax.get_geoip_country.php',
                                type: 'POST',
                                dataType: 'json',
                                data: { ip: ip },
                                success: function(data) {
                                    if(data.status === 'success') {
                                        var flagUrl = "<?php echo G5_DATA_URL; ?>/item/img_nation_flag/svg/" + data.country_code.toLowerCase() + ".svg";
                                        $flagDisplay.find('img').attr('src', flagUrl).attr('alt', data.country_name).show(); // Show image again
                                        $flagDisplay.find('span').text(data.country_name);
                                        $flagDisplay.css('display', 'flex').data('status', 'valid'); // Set valid

                                        $input.css('padding-right', '140px');

                                        $countryCodeInput.val(data.country_code);
                                        $countryNameInput.val(data.country_name);
                                    } else {
                                        // Show error message
                                        $flagDisplay.find('img').hide();
                                        $flagDisplay.find('span').text('국가 확인 불가 (사용불가)').css('color', '#e53e3e');
                                        $flagDisplay.css('display', 'flex').data('status', 'invalid'); // Set invalid
                                        $input.css('padding-right', '170px');

                                        $countryCodeInput.val('');
                                        $countryNameInput.val('');
                                    }
                                },
                                error: function() {
                                    $flagDisplay.find('img').hide();
                                    $flagDisplay.find('span').text('확인 오류').css('color', '#e53e3e');
                                    $flagDisplay.css('display', 'flex').data('status', 'invalid'); // Set invalid
                                    $input.css('padding-right', '100px');
                                }
                            });
                        });

						$(document).on('input', '.vpnServer, .vpnId', function() {
							var $container = $(this).closest('.vpn-config-item');
							scheduleVpnDupCheck($container, false);
						});

						$(document).on('change', '.vpnProtocol', function() {
							var $container = $(this).closest('.vpn-config-item');
							scheduleVpnDupCheck($container, true);
						});

						$(document).on('blur', '.vpnProtocol, .vpnServer, .vpnId', function() {
							var $container = $(this).closest('.vpn-config-item');
							scheduleVpnDupCheck($container, true);
						});

                        // Auth Check Logic
                        $(document).on('blur', '.vpnId, .vpnPassword', function() {
                            var $container = $(this).closest('.vpn-config-item');

                            var protocol = $container.find('.vpnProtocol').val();
                            var ip = $container.find('.vpnServer').val();
                            var id = $container.find('.vpnId').val();
                            var pw = $container.find('.vpnPassword').val();
                            var $status = $container.find('.vpn-auth-status');

                            if(!protocol || !ip || !id || !pw) {
                                // If any field is empty, clear status
                                $status.hide();
                                return;
                            }

                            // Prevent re-checking same data?
                            var currentData = protocol + '|' + ip + '|' + id + '|' + pw;
                            if($status.data('last-checked-auth') === currentData) return;
                            $status.data('last-checked-auth', currentData);

                            $status.text(' - 검증중...').css('color', '#666').show();

                             $.ajax({
                                url: '<?php echo G5_SHOP_URL; ?>/partner/ajax.check_vpn_auth.php',
                                type: 'POST',
                                dataType: 'json',
                                data: {
                                    protocol: protocol,
                                    ip: ip,
                                    id: id,
                                    pw: pw
                                },
                                success: function(data) {
                                    // Reset warning
                                    $container.find('.vpn-manual-check-warning').hide();

                                    if(data.status === 'success') {
                                        // Show message from server (e.g. "IKEv2 Service Active (ID/PW Unknown)")
                                        $status.text(' - ' + data.msg).css('color', '#28a745').data('status', 'valid'); // Green

                                        // If verification is partial (Service Active only), show warning box
                                        if(data.msg.indexOf('검증불가') !== -1) {
                                            $container.find('.vpn-manual-check-warning').show();
                                        }
                                    } else if(data.status === 'warning') {
                                        $status.text(' - ' + data.msg).css('color', '#d69e2e').data('status', 'valid'); // Orange/Yellow - Treat warning as valid (just alert user)
                                    } else {
                                        $status.text(' - ' + data.msg).css('color', '#e53e3e').data('status', 'invalid'); // Red - Fail
                                    }
                                },
                                error: function() {
                                    $status.text(' - 검증 오류').css('color', '#e53e3e').data('status', 'invalid');
                                }
                            });
                        });

                        // If Protocol or IP changes, re-trigger check if ID/PW exist
                        $(document).on('change', '.vpnProtocol, .vpnServer', function() {
                             var $container = $(this).closest('.vpn-config-item');
                             var id = $container.find('.vpnId').val();
                             var pw = $container.find('.vpnPassword').val();
                             if(id && pw) {
                                 // Trigger blur on PW to run check
                                 $container.find('.vpnPassword').trigger('blur');
                             }
                        });


                        // Prevent form submission if any VPN config is invalid
                        $("form[name='fitemform']").submit(function(e) {
                            var invalidAuth = false;
                            var invalidCountry = false;
							var duplicateVpn = false;
							var duplicateMsg = '';
							var duplicateTarget = null;

							if (checkLocalVpnDupAndMark()) {
								duplicateTarget = $('.vpn-config-item').filter(function() {
									return $(this).data('dup-status') === 'duplicate';
								}).first();
								showVpnDupLayer('동일한 VPN 접속정보(프로토콜/서버주소/ID)가 같은 상품 내에 중복되었습니다.\n\n중복 항목만 수정하신 후 다시 적용해 주세요.', duplicateTarget, 'submit-local');
								e.preventDefault();
								return false;
							}

							var checkedDupKeys = {};

							$('.vpn-config-item').each(function() {
								var $this = $(this);
								var protocol = $this.find('.vpnProtocol').val();
								var ip = $this.find('.vpnServer').val().trim();
								var vpnId = $this.find('.vpnId').val();
								var key = buildVpnDupKey(protocol, ip, vpnId);
								if (!key || checkedDupKeys[key]) {
									return true;
								}

								checkedDupKeys[key] = true;
								var checkRes = checkRemoteVpnDupForRow($this, { sync: true, silentSuccess: true });
								if (checkRes && checkRes.duplicate) {
									duplicateVpn = true;
									duplicateMsg = checkRes.message || '동일한 VPN 접속정보(프로토콜/서버주소/ID)가 이미 다른 상품에 등록되어 있습니다.';
									duplicateTarget = $this;
									$this.find('.vpnId').focus();
									return false;
								}
							});

							if (duplicateVpn) {
								showVpnDupLayer(duplicateMsg + '\n\n중복 항목만 수정하신 후 다시 적용해 주세요.', duplicateTarget, 'submit-remote');
								e.preventDefault();
								return false;
							}

                            $('.vpn-config-item').each(function() {
                                var $this = $(this);
                                var $status = $this.find('.vpn-auth-status');
                                var $flag = $this.find('.vpn-flag-display');

                                // Skip if input is empty (required check will handle it, or it's not relevant)
                                var ip = $this.find('.vpnServer').val().trim();
                                if(!ip) return true; // continue

                                if ($status.data('status') === 'invalid') {
                                    invalidAuth = true;
                                    // Highlight the input?
                                    $this.find('.vpnServer').focus();
                                    return false; // break loop
                                }

                                // Also check GeoIP status
                                if ($flag.data('status') === 'invalid') {
                                    invalidCountry = true;
                                    $this.find('.vpnServer').focus();
                                    return false;
                                }
                            });

                            if (invalidAuth) {
								hideSubmitLoadingOverlay();
                                alert("접속할 수 없는 VPN 서버가 포함되어 있습니다.\n서버 주소 및 상태를 확인해 주세요.");
                                e.preventDefault();
                                return false;
                            }

                            if (invalidCountry) {
								hideSubmitLoadingOverlay();
                                alert("국가를 확인할 수 없는 IP가 포함되어 있습니다.\n서버 주소를 확인해 주세요.");
                                e.preventDefault();
                                return false;
                            }
                        });


                        // Function to add a new VPN configuration row
                        function addVpnRow() {
                            // Get last selected protocol from localStorage
                            var lastProtocol = localStorage.getItem('lastVpnProtocol') || '';

                            var protocolOptions = '<option value="">- 선택 -</option>';
                            <?php
                                foreach ($vpnProtocols as $p) {
                                    echo "protocolOptions += '<option value=\"{$p}\">{$p}</option>';";
                                }
                            ?>

							var newHtml = `
							<div class='vpn-config-item'>
                                <div class='vpn-config-row'>
									<div class='vpn-input-group protocol-group'>
                                        <label>VPN상품구분(프로토콜)</label>
								        <select name='remoteProgram[]' class='vpnProtocol frm_input required' required>
									        ` + protocolOptions + `
								        </select>
                                    </div>
									<div class='vpn-input-group server-group'>
                                        <label>서버주소 (IP/Domain) <span class='vpn-auth-status' style='font-size:11px; font-weight:bold; margin-left:5px;'></span></label>
                                        <div style='position:relative;'>
								            <input type='text' name='remoteIp[]' class='vpnServer frm_input required' value='' placeholder='예: 123.45.67.89 또는 vpn.example.com' required>
                                            <div class='vpn-flag-display' style='display:none;'>
                                                <img src='' alt=''>
                                                <span></span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class='vpn-divider'></div>
                                <div class='vpn-config-row'>
									<div class='vpn-input-group credential-group'>
                                        <label>ID (계정)</label>
								        <input type='text' name='remoteId[]' class='vpnId frm_input required' value='' required>
                                    </div>
									<div class='vpn-input-group credential-group'>
                                        <label>Password (암호)</label>
								        <input type='text' name='remotePassword[]' class='vpnPassword frm_input required' value='' required>
                                    </div>
                                    <button type='button' class='btn_del_vpn'>삭제</button>
                                </div>
                                <div class='vpn-manual-check-warning' style='display:none; background-color: #fff3cd; border: 1px solid #ffeeba; color: #856404; padding: 10px; border-radius: 4px; font-size: 12px; margin-top: 10px;'>
                                    ※ <strong>주의:</strong> 해당 프로토콜은 ID/비밀번호 자동 검증이 지원되지 않습니다.<br>
                                    서버에 해당 ID와 비밀번호가 정상적으로 세팅되어 실제 접속이 가능한지 <strong>반드시 별도로 확인</strong>해 주시기 바랍니다.<br>
                                    (검증되지 않은 계정 정보 등록 시, 구매 고객이 접속 장애를 겪을 수 있습니다.)
                                </div>
								<div class='vpn-dup-notice'></div>
							</div>`;

                            var $newRow = $(newHtml);

                            // Set the selected protocol if available
                            if(lastProtocol) {
                                $newRow.find('.vpnProtocol').val(lastProtocol);
                            }

							$('#vpnConfigList').append($newRow);
								checkLocalVpnDupAndMark();
                        }

						$('#addVpnConfig').click(function() {
							addVpnRow();
						});

						$(document).on('click', '.btn_del_vpn', function() {
                            var rowCount = $('#vpnConfigList .vpn-config-item').length;
                            // Ensure at least one row remains if strictly required (User said "basically require 1 input"),
                            // but if user intentionally deletes, maybe allow it?
                            // User request: "required property applied so prevent moving to next step if missing".
                            // If user deletes the last row, the form will have no inputs, so required check won't trigger (no inputs to check).
                            // But user said "Prevent moving to next step if input value is missing".
                            // And "Basically store 1 input even without clicking button first".
                            // If they delete all, they might submit empty form?
                            // Let's prevent deleting the last row or re-add one if all deleted?
                            // Usually "delete" just removes. If all removed, maybe show add button.
                            // Use case: User deletes a row.
                            // If it's the only row, warn or clear values?

                            if(rowCount <= 1) {
								var $targetRow = $(this).closest('.vpn-config-item');
								showCopilotConfirm('마지막 항목입니다. 내용을 삭제하고 초기화하시겠습니까?', function() {
									$targetRow.find('input').val('');
									$targetRow.find('select').val('');
								}, null, { title: '초기화 확인', okText: '초기화', type: 'warn' });
                                return;
                            }

							var $rowToDelete = $(this).closest('.vpn-config-item');
							showCopilotConfirm('정말 삭제하시겠습니까?', function() {
							    $rowToDelete.remove();
								checkLocalVpnDupAndMark();
							}, null, { title: '삭제 확인', okText: '삭제', type: 'warn', danger: true });
						});

                        // Save protocol selection to localStorage when changed
                        $(document).on('change', '.vpnProtocol', function() {
                            var val = $(this).val();
                            if(val) {
                                localStorage.setItem('lastVpnProtocol', val);
                            }
                        });


                        // Check if list is empty on load, if so add one row
                        if ($('#vpnConfigList').children().length === 0) {
                            addVpnRow();
						} else {
							checkLocalVpnDupAndMark();
							$('.vpn-config-item').each(function() {
								scheduleVpnDupCheck($(this), true);
							});
                        }
					});
				</script>
			</td>
		</tr>

		<!-- 제조사/원산지/브랜드/모델 hidden 유지 -->
        <input type="hidden" name="it_maker" value="">
        <input type="hidden" name="it_origin" value="">
        <input type="hidden" name="it_brand" value="">
        <input type="hidden" name="it_model" value="">

		<?php
			$vpn_it_10_hours = (int)$it['it_10'];
			if ($vpn_it_10_hours < 0) {
				$vpn_it_10_hours = 0;
			}

			$vpn_it_buy_min_hours = (int)$it['it_buy_min_qty'];
			if ($vpn_it_buy_min_hours <= 0) {
				$vpn_it_buy_min_hours = 1;
			}

			$vpn_it_buy_max_hours = (int)$it['it_buy_max_qty'];
			if ($vpn_it_buy_max_hours > 0 && $vpn_it_buy_max_hours <= 365) {
				$vpn_it_buy_max_hours *= 24;
			}
			if ($vpn_it_buy_max_hours <= 0) {
				$vpn_it_buy_max_hours = 8760;
			}
			if ($vpn_it_buy_max_hours > 8760) {
				$vpn_it_buy_max_hours = 8760;
			}

			$vpn_it_10_day = (int)floor($vpn_it_10_hours / 24);
			$vpn_it_10_hour = $vpn_it_10_hours % 24;

			$vpn_it_buy_min_day = (int)floor($vpn_it_buy_min_hours / 24);
			$vpn_it_buy_max_day = (int)floor($vpn_it_buy_max_hours / 24);

			$vpn_contract_day_option_max = max(365, $vpn_it_10_day, $vpn_it_buy_min_day, $vpn_it_buy_max_day);
			if ($vpn_contract_day_option_max > 3650) {
				$vpn_contract_day_option_max = 3650;
			}
		?>
		<tr>
			<th scope="row"><label for="it_install_price">개통비/설치비</label></th>
			<td>
				<?php echo help("VPN 설치 작업비로서 신규 주문시 한번만 청구하는 비용입니다.<br>이 비용은 계약기간을 연장하는 경우에는 청구되지 않습니다.<br>기준시간 이상 구매 시 면제할지 여부만 설정할 수 있습니다."); ?>
				<?php if ($w == '') { ?>
					<input type="text" name="it_install_price" value="0" id="it_install_price" class="frm_input" size="8"> Point
				<?php } else { ?>
					<input type="text" name="it_install_price" value="<?php echo $it['it_install_price']; ?>" id="it_install_price" class="frm_input" size="8"> Point
				<?php } ?>

				<div style="margin-top:8px;">
					<?php echo help("고객님이 아래 기간 이상으로 주문하게 되면 개통비/설치비 전액이 감면되도록 설정합니다."); ?>
					<select name="it_10_day" id="it_10_day" class="frm_input">
						<?php for ($d = 0; $d <= $vpn_contract_day_option_max; $d++) { ?>
							<option value="<?php echo $d; ?>" <?php echo ($d === $vpn_it_10_day) ? 'selected' : ''; ?>><?php echo $d; ?>일</option>
						<?php } ?>
					</select>
					<select name="it_10_hour" id="it_10_hour" class="frm_input">
						<?php for ($h = 0; $h <= 23; $h++) { ?>
							<option value="<?php echo $h; ?>" <?php echo ($h === $vpn_it_10_hour) ? 'selected' : ''; ?>><?php echo $h; ?>시간</option>
						<?php } ?>
					</select>
					<input type="hidden" name="it_10" value="<?php echo $vpn_it_10_hours; ?>" id="it_10" class="frm_input"> <span class="helper">(0일 0시간 = 미사용)</span>
				</div>
			</td>
		</tr>
		<script>
		$(function() {
			function syncVpnInstallThresholdHours() {
				var day = parseInt($('#it_10_day').val(), 10);
				var hour = parseInt($('#it_10_hour').val(), 10);
				if (isNaN(day) || day < 0) day = 0;
				if (isNaN(hour) || hour < 0) hour = 0;
				if (hour > 23) hour = 23;
				$('#it_10').val(String((day * 24) + hour));
			}

			$('#it_10_day, #it_10_hour').on('change', syncVpnInstallThresholdHours);
			syncVpnInstallThresholdHours();
		});
		</script>


		<input type="hidden" name="it_billing_plan" id="it_billing_plan" value="<?php echo get_text($it['it_billing_plan']); ?>">
		<tr id="billing_usage_fields" style="display:none; background-color:#fcfcfc;">
			<th scope="row">종량제 단가 설정</th>
			<td>
				<div style="margin-bottom:8px;">
					<span style="display:inline-block; width:150px;">트래픽 비용 (Point/GB)</span>
					<input type="text" name="it_billing_traffic_cost" value="<?php echo $it['it_billing_traffic_cost']; ?>" id="it_billing_traffic_cost" class="frm_input" size="10" style="text-align:right;"> Point
				</div>
				<div>
					<span style="display:inline-block; width:150px;">시간 비용 (Point/시간)</span>
					<input type="text" name="it_billing_time_cost" value="<?php echo $it['it_billing_time_cost']; ?>" id="it_billing_time_cost" class="frm_input" size="10" style="text-align:right;"> Point
				</div>
			</td>
		</tr>
		<script>
		function toggleBillingUsageFields() {
			if ($('#chk_sell_usage').is(':checked')) {
				$('#billing_usage_fields').show();
			} else {
				$('#billing_usage_fields').hide();
			}
		}
		</script>

		<tr id="sales_period_settings">
			<th scope="row">판매허용 요금제</th>
			<td>
				<div style="margin:5px 0;">
					<div style="margin-bottom:5px;">
						<label style="font-weight:bold; font-size:1.1em;">
							<input type="checkbox" id="chk_sell_usage" <?php echo ((isset($it['it_7']) && (string)$it['it_7'] === '1') || $it['it_billing_plan'] === 'usage') ? "checked" : ""; ?>> 종량제 이용권 판매 허용
						</label>
					</div>
					<div style="margin-bottom:5px;">
						<label style="font-weight:bold; font-size:1.1em;">
							<input type="checkbox" id="chk_sell_hour" <?php echo ($it['it_is_hour_sale']) ? "checked" : ""; ?>> 1시간 이용권 판매 허용
						</label>
					</div>
					<div style="margin-bottom:5px;">
						<label style="font-weight:bold; font-size:1.1em;">
							<input type="checkbox" id="chk_sell_day" <?php echo ($it['it_1'] == '1' || $w == '') ? "checked" : ""; ?>> 1일 이용권 판매 허용
						</label>
					</div>
					<div>
						<label style="font-weight:bold; font-size:1.1em;">
							<input type="checkbox" id="chk_sell_month" <?php echo ($it['it_2'] == '1' || $w == '') ? "checked" : ""; ?>> 1개월(30일) 이용권 판매 허용
						</label>
					</div>
					<div style="margin-top:5px;">
						<label style="font-weight:bold; font-size:1.1em;">
							<input type="checkbox" id="chk_sell_year" <?php echo ($it['it_3'] == '1') ? "checked" : ""; ?>> 1년(365일) 이용권 판매 허용
						</label>
					</div>

					<div style="font-size:0.9em; color:#666; margin-top:10px; padding-left:10px; border-left:3px solid #ddd;">
						※ 체크된 요금제 단위로 이용권을 판매합니다.<br>
						※ 주문시간 기반 이용권은 시간/일/월/년 중 최소 1개 이상 선택하세요.
					</div>
				</div>

				<!-- Hidden Fields & Logic -->
				<!-- Use hidden inputs to store values. For it_1/it_2, we will sync with any existing inputs by ID if present, or add them if not. -->
				<!-- Note: Parent form might output it_1/it_2 at bottom. We use JS to ensure values are synced. -->

				<input type="hidden" name="it_is_hour_sale" value="<?php echo $it['it_is_hour_sale']; ?>" id="it_is_hour_sale">
				<input type="hidden" name="it_7" value="<?php echo isset($it['it_7']) ? $it['it_7'] : '0'; ?>" id="it_7">
				<!-- We create local hidden inputs for it_1/it_2 just in case they don't exist, but give them IDs to sync.
				     If parent has inputs with same ID, this might be issue. We will use specific IDs for local use and sync to 'name' based inputs if needed.
				     Actually, we will assume standard behavior: we control these values. -->

				<?php
					$it_buy_min_hours = isset($it['it_buy_min_qty']) ? (int)$it['it_buy_min_qty'] : 1;
					if ($it_buy_min_hours < 1) {
						$it_buy_min_hours = 1;
					}

					$it_buy_max_hours = isset($it['it_buy_max_qty']) ? (int)$it['it_buy_max_qty'] : 0;
					if ($it_buy_max_hours > 0 && $it_buy_max_hours <= 365) {
						// 과거 일 단위 저장값(최대 365일) 호환: 시간 단위로 보정
						$it_buy_max_hours *= 24;
					}
					if ($it_buy_max_hours <= 0) {
						$it_buy_max_hours = 8760;
					}
					if ($it_buy_max_hours > 8760) {
						$it_buy_max_hours = 8760;
					}
				?>
				<input type="hidden" name="it_buy_min_qty" id="it_buy_min_qty" value="<?php echo $it_buy_min_hours; ?>">
				<input type="hidden" name="it_buy_max_qty" id="it_buy_max_qty" value="<?php echo $it_buy_max_hours; ?>">

				<script>
					$(function(){
						function updateSalesConfig() {
							var hasUsage = $('#chk_sell_usage').is(':checked');
							$('#it_7').val(hasUsage ? '1' : '0');
							$('input[name="it_7"]').val(hasUsage ? '1' : '0');
							toggleBillingUsageFields();

							// Hour
							if($('#chk_sell_hour').is(':checked')) {
								$('#it_is_hour_sale').val('1'); // For checkbox type hidden trick or value
                                $('input[name="it_is_hour_sale"]').val('1');
                                $('#calc_hour_desc').text('(판매 중)');
								$('#calc_hour_price').parent().css('opacity', '1');
							} else {
								$('#it_is_hour_sale').val('0');
                                $('input[name="it_is_hour_sale"]').val('0');
								$('#calc_hour_desc').text('(미판매)');
								$('#calc_hour_price').parent().css('opacity', '0.5');
							}

							// Day - Store in it_1
							if($('#chk_sell_day').is(':checked')) {
								if($('#it_1').length) $('#it_1').val('1'); /* If exists by ID */
                                else { /* Create if missing? No, assume exists or add hidden */ }
                                $('input[name="it_1"]').val('1'); // Target by name too
								$('#calc_day_desc').text('(판매 중)');
								$('#calc_day_price').parent().css('opacity', '1');
							} else {
								if($('#it_1').length) $('#it_1').val('0');
                                $('input[name="it_1"]').val('0');
								$('#calc_day_desc').text('(미판매)');
								$('#calc_day_price').parent().css('opacity', '0.5');
							}

							// Month - Store in it_2
							if($('#chk_sell_month').is(':checked')) {
								if($('#it_2').length) $('#it_2').val('1');
                                $('input[name="it_2"]').val('1');
								$('#calc_month_desc').text('(판매 중)');
								$('#calc_month_price').parent().css('opacity', '1');
							} else {
								if($('#it_2').length) $('#it_2').val('0');
                                $('input[name="it_2"]').val('0');
								$('#calc_month_desc').text('(미판매)');
								$('#calc_month_price').parent().css('opacity', '0.5');
							}

							// Year - Store in it_3
							if($('#chk_sell_year').is(':checked')) {
								if($('#it_3').length) $('#it_3').val('1');
								$('input[name="it_3"]').val('1');
								$('#calc_year_desc').text('(판매 중)');
								$('#calc_year_price').parent().css('opacity', '1');
							} else {
								if($('#it_3').length) $('#it_3').val('0');
								$('input[name="it_3"]').val('0');
								$('#calc_year_desc').text('(미판매)');
								$('#calc_year_price').parent().css('opacity', '0.5');
							}

							// Update Min Qty (판매 허용 단위 중 최소 시간 기준)
							var minQtyCandidates = [];
							if($('#chk_sell_hour').is(':checked')) minQtyCandidates.push(1);
							if($('#chk_sell_day').is(':checked')) minQtyCandidates.push(24);
							if($('#chk_sell_month').is(':checked')) minQtyCandidates.push(720);
							if($('#chk_sell_year').is(':checked')) minQtyCandidates.push(8760);

							if (minQtyCandidates.length > 0) {
								$('#it_buy_min_qty').val(String(Math.min.apply(null, minQtyCandidates)));
							} else {
								$('#it_buy_min_qty').val('1');
							}

							// 최대계약은 내부 저장 기준으로 항상 시간 단위(최대 1년=8760시간)로 고정
							$('#it_buy_max_qty').val('8760');
						}

						$('#chk_sell_usage, #chk_sell_hour, #chk_sell_day, #chk_sell_month, #chk_sell_year').change(function(){
							updateSalesConfig();
						});

                        // Set initial state for hidden inputs based on checkboxes
                        // (PHP sets checkboxes correctly, we need to push that to hidden inputs)
						updateSalesConfig();
					});
				</script>
			</td>
		</tr>

		<!-- Billing Plan Logic moved up -->

		<tr id="billing_fixed_fields">
			<th scope="row"><label for="it_price">기준요금 (1시간 기준)</label></th>
			<td>
				<?php
					$hourly_input_price = (int)$it['it_is_hour_sale_price'];
					if($hourly_input_price <= 0) {
						$hourly_input_price = (int)$it['it_price'];
					}

					$billing_day_hours = isset($it['it_4']) ? (float)$it['it_4'] : 0;
					if ($billing_day_hours <= 0) {
						$billing_day_hours = 20;
					}

					$billing_month_hours = isset($it['it_5']) ? (float)$it['it_5'] : 0;
					if ($billing_month_hours <= 0) {
						$billing_month_hours = 420;
					}

					$billing_year_hours = isset($it['it_6']) ? (float)$it['it_6'] : 0;
					if ($billing_year_hours <= 0) {
						$billing_year_hours = 3360;
					}
				?>
				<div style="display:flex; align-items:center; margin-bottom:10px;">
					<input type="text" name="it_price" value="<?php echo $hourly_input_price; ?>" id="it_price" class="frm_input required" required size="10" oninput="calculatePrices()" style="font-weight:bold; font-size:1.2em; text-align:right;">
					<span style="font-size:1.2em; margin-left:5px;">Point</span>
					<span style="margin-left:10px; color:#888;">(입력값은 1시간 기준)</span>
				</div>

				<div style="padding:12px; border:1px dashed #d6e4f2; background:#fbfdff; border-radius:4px; margin-bottom:12px; max-width:700px;">
					<div style="display:flex; justify-content:space-between; align-items:center; gap:10px; flex-wrap:wrap; margin-bottom:8px;">
						<div style="font-weight:bold; color:#234;">장기 주문 요금할인 설정 (직접 조정 가능)</div>
						<div style="display:flex; flex-wrap:wrap; gap:6px;">
							<button type="button" class="btn_frmline billing-preset-btn" data-preset-key="standard" id="billing_preset_btn_standard">표준설정</button>
							<button type="button" class="btn_frmline billing-preset-btn" data-preset-key="basic" id="billing_preset_btn_basic">추천설정</button>
							<button type="button" class="btn_frmline" id="billing_preset_add_btn">사용자정의 추가+</button>
							<span id="billing_custom_buttons" style="display:flex; flex-wrap:wrap; gap:6px;"></span>
						</div>
					</div>
					<div id="billing_weights_inline_row" style="display:flex; flex-wrap:nowrap; gap:14px; align-items:center; overflow-x:auto; padding-bottom:2px;">
						<div id="billing_selected_preset_info" style="display:none; flex:0 0 auto;">
							<span id="billing_selected_preset_name" style="display:inline-block; font-size:12px; font-weight:700; color:#1d4ed8; background:#dbeafe; border:1px solid #bfdbfe; border-radius:999px; padding:3px 10px;"></span>
							<button type="button" class="btn_frmline" id="billing_selected_preset_edit_btn" style="margin-left:6px;">수정</button>
						</div>
						<label style="display:flex; align-items:center; gap:6px;">
							<span>1일 =</span>
							<input type="number" step="1" min="1" name="billing_day_hours" id="billing_day_hours" value="<?php echo $billing_day_hours; ?>" class="frm_input" style="width:90px; text-align:right;" oninput="calculatePrices()">
							<span>시간</span>
						</label>
						<label style="display:flex; align-items:center; gap:6px;">
							<span>1개월 =</span>
							<input type="number" step="1" min="1" name="billing_month_hours" id="billing_month_hours" value="<?php echo $billing_month_hours; ?>" class="frm_input" style="width:90px; text-align:right;" oninput="calculatePrices()">
							<span>시간</span>
						</label>
						<label style="display:flex; align-items:center; gap:6px;">
							<span>1년 =</span>
							<input type="number" step="1" min="1" name="billing_year_hours" id="billing_year_hours" value="<?php echo $billing_year_hours; ?>" class="frm_input" style="width:90px; text-align:right;" oninput="calculatePrices()">
							<span>시간</span>
						</label>
					</div>
					<div style="font-size:12px; color:#667; margin-top:6px;">
						추천 정책(장기할인형): 1일=20시간 요금, 1개월(30일)=420시간 요금, 1년(365일)=3360시간 요금<br>
						표준 정책: 1일=24시간 요금, 1개월(30일)=720시간 요금, 1년(365일)=8760시간 요금
					</div>
					<div id="billing_policy_current" style="font-size:12px; color:#1f3b67; margin-top:4px; font-weight:600; display:flex; align-items:center; gap:8px; flex-wrap:wrap;">
						<span id="billing_policy_current_text">현재 적용값: 1일=20시간, 1개월=420시간, 1년=3360시간</span>
						<span id="billing_policy_state_badge" style="display:inline-flex; align-items:center; justify-content:center; padding:2px 8px; border:1px solid #bfdbfe; background:#e0ecff; color:#1e40af; font-size:11px; font-weight:700; line-height:1.2;">추천</span>
					</div>
					<div id="billing_reality_hint" style="margin-top:8px; font-size:12px; color:#334155; line-height:1.55; border-top:1px dashed #d6e4f2; padding-top:8px;">
						<div style="font-weight:600; color:#1e3a8a; margin-bottom:2px;">장기요금 체감 지표</div>
						<div id="billing_effective_rates">일권 체감시급: - / 월권 체감시급: - / 연권 체감시급: -</div>
						<div id="billing_discount_rates" style="color:#475569;">표준정가 대비 할인율: 일권 - / 월권 - / 연권 -</div>
						<div id="billing_example_100" style="color:#64748b;">예시(1시간=100 Point): 1일 - / 1개월 - / 1년 -</div>
					</div>


					<div id="billing_preset_modal" style="display:none; position:fixed; z-index:10020; inset:0; background:rgba(15, 23, 42, 0.45);">
						<div style="position:absolute; left:50%; top:50%; transform:translate(-50%, -50%); width:min(760px, calc(100% - 24px)); background:#fff; border-radius:10px; box-shadow:0 20px 40px rgba(2,6,23,0.26); border:1px solid #dbe4ee; overflow:hidden;">
							<div style="display:flex; justify-content:space-between; align-items:center; padding:12px 14px; border-bottom:1px solid #edf2f7; background:#f8fafc;">
								<strong style="font-size:14px; color:#1f2937;">사용자정의 프리셋 입력</strong>
								<button type="button" class="btn_frmline" id="billing_preset_modal_close_top">닫기</button>
							</div>
							<div style="padding:14px;">
								<input type="hidden" id="billing_preset_edit_id" value="">
								<div style="display:flex; flex-wrap:wrap; gap:8px; align-items:center; margin-bottom:10px;">
									<label style="display:flex; align-items:center; gap:6px;">
										<span>이름</span>
										<input type="text" id="billing_preset_edit_name" class="frm_input" style="width:180px;" placeholder="예: 주말특가">
									</label>
									<label style="display:flex; align-items:center; gap:6px;">
										<span>1일</span>
										<input type="number" id="billing_preset_edit_day" class="frm_input" style="width:90px; text-align:right;" min="1" step="1">
									</label>
									<label style="display:flex; align-items:center; gap:6px;">
										<span>1개월</span>
										<input type="number" id="billing_preset_edit_month" class="frm_input" style="width:90px; text-align:right;" min="1" step="1">
									</label>
									<label style="display:flex; align-items:center; gap:6px;">
										<span>1년</span>
										<input type="number" id="billing_preset_edit_year" class="frm_input" style="width:90px; text-align:right;" min="1" step="1">
									</label>
								</div>
								<div style="display:flex; flex-wrap:wrap; gap:6px; align-items:center;">
									<button type="button" class="btn_frmline" id="billing_preset_register_btn">등록</button>
									<button type="button" class="btn_frmline" id="billing_preset_update_btn">수정</button>
									<button type="button" class="btn_frmline" id="billing_preset_delete_btn">삭제</button>
									<button type="button" class="btn_frmline" id="billing_preset_cancel_btn">취소</button>
									<span style="font-size:11px; color:#94a3b8;">※ 저장/수정 시 상단 값에 즉시 적용됩니다.</span>
								</div>
							</div>
						</div>
					</div>
				</div>

				<div id="vpn_price_calculator" style="padding:15px; border:1px solid #e9e9e9; background:#f7fbff; border-radius:4px; max-width:700px;">
					<div style="font-weight:bold; margin-bottom:10px; color:#333;">판매 기간별 요금 환산 (자동 계산)</div>
					<table style="width:100%; border-collapse:collapse;">
						<tr style="border-bottom:1px solid #eee;">
							<td style="padding:8px; color:#666;">1시간 이용권</td>
							<td style="padding:8px; font-weight:bold; color:#d9534f; text-align:right;" id="calc_hour_price">0 Point</td>
							<td style="padding:8px; font-size:0.9em; color:#999;" id="calc_hour_desc">(판매 중)</td>
						</tr>
						<tr>
							<td style="padding:8px; color:#666;">1년 이용권</td>
							<td style="padding:8px; font-weight:bold; color:#5b2caa; text-align:right;" id="calc_year_price">0 Point</td>
							<td style="padding:8px; font-size:0.9em; color:#999;">
								<span id="calc_year_desc" style="margin-right:6px;">(판매 중)</span>
								<span id="calc_year_formula">(1시간 요금 × 3360)</span>
							</td>
						</tr>
						<tr style="border-bottom:1px solid #eee;">
							<td style="padding:8px; color:#666;">1일 이용권</td>
							<td style="padding:8px; font-weight:bold; color:#0275d8; text-align:right;" id="calc_day_price">0 Point</td>
							<td style="padding:8px; font-size:0.9em; color:#999;">
								<span id="calc_day_desc" style="margin-right:6px;">(판매 중)</span>
								<span id="calc_day_formula">(1시간 요금 × 20)</span>
							</td>
						</tr>
						<tr>
							<td style="padding:8px; color:#666;">1개월 이용권</td>
							<td style="padding:8px; font-weight:bold; color:#28a745; text-align:right;" id="calc_month_price">0 Point</td>
							<td style="padding:8px; font-size:0.9em; color:#999;">
								<span id="calc_month_desc" style="margin-right:6px;">(판매 중)</span>
								<span id="calc_month_formula">(1시간 요금 × 420)</span>
							</td>
						</tr>
					</table>
				</div>

				<script>
					function calculatePrices() {
						var hourPrice = parseInt($('#it_price').val().replace(/[^0-9]/g, '')) || 0;
						var dayHours = parseFloat($('#billing_day_hours').val());
						var monthHours = parseFloat($('#billing_month_hours').val());
						var yearHours = parseFloat($('#billing_year_hours').val());

						if (!dayHours || dayHours <= 0) dayHours = 20;
						if (!monthHours || monthHours <= 0) monthHours = 420;
						if (!yearHours || yearHours <= 0) yearHours = 3360;

						$('#billing_policy_current_text').text('현재 적용값: 1일=' + dayHours + '시간, 1개월=' + monthHours + '시간, 1년=' + yearHours + '시간');

						var $policyBadge = $('#billing_policy_state_badge');
						if ($policyBadge.length) {
							var isRecommended = (Math.abs(dayHours - 20) < 0.0001) && (Math.abs(monthHours - 420) < 0.0001) && (Math.abs(yearHours - 3360) < 0.0001);
							var isStandard = (Math.abs(dayHours - 24) < 0.0001) && (Math.abs(monthHours - 720) < 0.0001) && (Math.abs(yearHours - 8760) < 0.0001);

							if (isRecommended) {
								$policyBadge.text('추천').css({
									'border-color': '#bfdbfe',
									'background': '#e0ecff',
									'color': '#1e40af'
								});
							} else if (isStandard) {
								$policyBadge.text('표준').css({
									'border-color': '#c7d2fe',
									'background': '#eef2ff',
									'color': '#3730a3'
								});
							} else {
								$policyBadge.text('사용자정의').css({
									'border-color': '#bbf7d0',
									'background': '#ecfdf3',
									'color': '#166534'
								});
							}
						}

						var dayPrice = Math.round(hourPrice * dayHours);
						var monthPrice = Math.round(hourPrice * monthHours);
						var yearPrice = Math.round(hourPrice * yearHours);

						$('#calc_hour_price').text(number_format_custom(hourPrice) + ' Point');
						$('#calc_day_price').text(number_format_custom(dayPrice) + ' Point');
						$('#calc_month_price').text(number_format_custom(monthPrice) + ' Point');
						$('#calc_year_price').text(number_format_custom(yearPrice) + ' Point');
						$('#calc_day_formula').text('(1시간 요금 × ' + dayHours + ')');
						$('#calc_month_formula').text('(1시간 요금 × ' + monthHours + ')');
						$('#calc_year_formula').text('(1시간 요금 × ' + yearHours + ')');

						var effDayHourly = (dayPrice / 24);
						var effMonthHourly = (monthPrice / 720);
						var effYearHourly = (yearPrice / 8760);
						var dayDiscountPct = (1 - (dayHours / 24)) * 100;
						var monthDiscountPct = (1 - (monthHours / 720)) * 100;
						var yearDiscountPct = (1 - (yearHours / 8760)) * 100;

						function formatPct(pct) {
							if (pct < 0) {
								return Math.abs(pct).toFixed(1) + '% 할증';
							}

							var grade = '라이트 할인';
							if (pct >= 45) {
								grade = '강한 할인';
							} else if (pct >= 20) {
								grade = '중간 할인';
							}

							return pct.toFixed(1) + '% 할인(' + grade + ')';
						}

						$('#billing_effective_rates').text(
							'일권 체감시급: ' + number_format_custom(Math.round(effDayHourly)) + ' Point/h'
							+ ' / 월권 체감시급: ' + number_format_custom(Math.round(effMonthHourly)) + ' Point/h'
							+ ' / 연권 체감시급: ' + number_format_custom(Math.round(effYearHourly)) + ' Point/h'
						);

						$('#billing_discount_rates').text(
							'표준정가 대비 할인율: 일권 ' + formatPct(dayDiscountPct)
							+ ' / 월권 ' + formatPct(monthDiscountPct)
							+ ' / 연권 ' + formatPct(yearDiscountPct)
						);

						var exampleHour = 100;
						$('#billing_example_100').text(
							'예시(1시간=100 Point): 1일 ' + number_format_custom(Math.round(exampleHour * dayHours)) + ' Point'
							+ ' / 1개월 ' + number_format_custom(Math.round(exampleHour * monthHours)) + ' Point'
							+ ' / 1년 ' + number_format_custom(Math.round(exampleHour * yearHours)) + ' Point'
						);

                        // Visual update is handled by updateSalesConfig as well, but this function runs on Price Input change.
                        // We should ensure visual state is consistent.
                        // Or just let updateSalesConfig handle the opacity/text.
                        // But calculatePrices might be called by oninput which doesn't trigger checkbox change.
                        // So we should re-apply opacity here or call updateSalesConfig?
                        // Better to replicate opacity logic or just check checkboxes here too.

                        if($('#chk_sell_hour').is(':checked')) {
							$('#calc_hour_price').parent().css('opacity', '1');
							$('#calc_hour_desc').text('(판매 중)');
						} else {
							$('#calc_hour_price').parent().css('opacity', '0.5');
							$('#calc_hour_desc').text('(미판매)');
						}

                        if($('#chk_sell_day').is(':checked')) {
							$('#calc_day_price').parent().css('opacity', '1');
							$('#calc_day_desc').text('(판매 중)');
						} else {
							$('#calc_day_price').parent().css('opacity', '0.5');
							$('#calc_day_desc').text('(미판매)');
						}

                        if($('#chk_sell_month').is(':checked')) {
							$('#calc_month_price').parent().css('opacity', '1');
							$('#calc_month_desc').text('(판매 중)');
						} else {
							$('#calc_month_price').parent().css('opacity', '0.5');
							$('#calc_month_desc').text('(미판매)');
						}

						if($('#chk_sell_year').is(':checked')) {
							$('#calc_year_price').parent().css('opacity', '1');
							$('#calc_year_desc').text('(판매 중)');
						} else {
							$('#calc_year_price').parent().css('opacity', '0.5');
							$('#calc_year_desc').text('(미판매)');
						}
					}

					function number_format_custom(num) {
						return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
					}

					$(function(){
						calculatePrices();

						var $itemForm = $("form[name='fitemform']");
						$itemForm.on('keydown', 'input, select', function(e) {
							if (e.key !== 'Enter') return;

							var $target = $(e.target);
							if ($target.is('textarea')) return;
							if ($target.is('[type="submit"], [type="button"], [type="file"], [type="checkbox"], [type="radio"]')) return;

							e.preventDefault();
							return false;
						});

						var billingPresetDefaults = { day: 20, month: 420, year: 3360 };
						var billingPresetStandard = { day: 24, month: 720, year: 8760 };
						var billingPresetStorageKey = 'vpnBillingPresets::' + <?php echo json_encode((string)$member['mb_id']); ?>;
						var billingPresetIsAdmin = true;
						var billingSelectedPresetId = '';

						function getBillingPresetPayload() {
							var payload = { nextId: 1, presets: [] };

							try {
								var raw = localStorage.getItem(billingPresetStorageKey);
								if (!raw) return payload;
								var parsed = JSON.parse(raw);
								if (parsed && typeof parsed === 'object') {
									if (Array.isArray(parsed.presets)) {
										payload.presets = parsed.presets;
										payload.nextId = parseInt(parsed.nextId, 10);
										if (!payload.nextId || payload.nextId < 1) payload.nextId = 1;
									}

									// 구버전(names/values) 마이그레이션
									if (!payload.presets.length && parsed.values && typeof parsed.values === 'object') {
										var migrated = [];
										var migrateId = 1;
										for (var mk in parsed.values) {
											if (!Object.prototype.hasOwnProperty.call(parsed.values, mk)) continue;
											var mv = parsed.values[mk] || {};
											var day = parseFloat(mv.day);
											var month = parseFloat(mv.month);
											var year = parseFloat(mv.year);
											if (!day || day <= 0 || !month || month <= 0 || !year || year <= 0) continue;
											var label = (parsed.names && parsed.names[mk]) ? String(parsed.names[mk]) : ('사용자정의' + migrateId);
											migrated.push({ id: migrateId, name: label, day: day, month: month, year: year });
											migrateId++;
										}
										payload.presets = migrated;
										payload.nextId = migrateId;
									}
								}
							} catch (e) {}

							return payload;
						}

						function saveBillingPresetPayload(payload) {
							try {
								localStorage.setItem(billingPresetStorageKey, JSON.stringify(payload));
							} catch (e) {}
						}

						function renderBillingCustomButtons(payload) {
							var $wrap = $('#billing_custom_buttons');
							$wrap.empty();

							if (!payload.presets || !payload.presets.length) {
								return;
							}

							for (var i = 0; i < payload.presets.length; i++) {
								var p = payload.presets[i];
								var btn = $('<button type="button" class="btn_frmline billing-preset-btn billing-preset-custom"></button>');
								btn.attr('data-preset-id', String(p.id));
								btn.text(String(p.name || ('사용자정의' + p.id)));
								$wrap.append(btn);
							}
						}

						function applyBillingPreset(day, month, year) {
							if (!day || day <= 0) day = billingPresetDefaults.day;
							if (!month || month <= 0) month = billingPresetDefaults.month;
							if (!year || year <= 0) year = billingPresetDefaults.year;

							$('#billing_day_hours').val(day);
							$('#billing_month_hours').val(month);
							$('#billing_year_hours').val(year);
							$('#billing_policy_current_text').text('현재 적용값: 1일=' + day + '시간, 1개월=' + month + '시간, 1년=' + year + '시간');
							calculatePrices();
						}

						function findPresetById(payload, presetId) {
							if (!payload || !Array.isArray(payload.presets)) return null;
							for (var i = 0; i < payload.presets.length; i++) {
								if (String(payload.presets[i].id) === String(presetId)) return payload.presets[i];
							}
							return null;
						}

						function setSelectedPreset(preset) {
							if (!preset || !preset.id) {
								billingSelectedPresetId = '';
								$('#billing_selected_preset_name').text('');
								$('#billing_selected_preset_info').hide();
								return;
							}

							billingSelectedPresetId = String(preset.id);
							$('#billing_selected_preset_name').text('사용자정의: ' + String(preset.name || ('사용자정의' + preset.id)));
							$('#billing_selected_preset_info').show();
						}

						function openPresetEditor(preset) {
							$('#billing_preset_modal').show();
							if (!preset) {
								$('#billing_preset_edit_id').val('');
								$('#billing_preset_edit_name').val('');
								$('#billing_preset_edit_day').val($('#billing_day_hours').val());
								$('#billing_preset_edit_month').val($('#billing_month_hours').val());
								$('#billing_preset_edit_year').val($('#billing_year_hours').val());
								return;
							}

							$('#billing_preset_edit_id').val(String(preset.id));
							$('#billing_preset_edit_name').val(String(preset.name || ''));
							$('#billing_preset_edit_day').val(String(preset.day || billingPresetDefaults.day));
							$('#billing_preset_edit_month').val(String(preset.month || billingPresetDefaults.month));
							$('#billing_preset_edit_year').val(String(preset.year || billingPresetDefaults.year));
						}

						function readEditorValues() {
							return {
								id: String($('#billing_preset_edit_id').val() || ''),
								name: String($('#billing_preset_edit_name').val() || '').trim(),
								day: parseFloat($('#billing_preset_edit_day').val()),
								month: parseFloat($('#billing_preset_edit_month').val()),
								year: parseFloat($('#billing_preset_edit_year').val())
							};
						}

						function validateEditorValues(v) {
							if (!v.name) {
								if (typeof showCopilotToast === 'function') showCopilotToast('사용자정의 이름을 입력해 주세요.', 'warn');
								return false;
							}
							if (!v.day || v.day <= 0 || !v.month || v.month <= 0 || !v.year || v.year <= 0) {
								if (typeof showCopilotToast === 'function') showCopilotToast('1일/1개월/1년 값은 모두 0보다 커야 합니다.', 'warn');
								return false;
							}
							return true;
						}

						var billingPresetPayload = getBillingPresetPayload();
						renderBillingCustomButtons(billingPresetPayload);

						$(document).on('click', '.billing-preset-btn', function() {
							var key = String($(this).data('preset-key') || '');
							if (key === 'standard') {
								applyBillingPreset(billingPresetStandard.day, billingPresetStandard.month, billingPresetStandard.year);
								setSelectedPreset(null);
								if (typeof showCopilotToast === 'function') {
									showCopilotToast('표준설정 프리셋(1일=24, 1개월=720, 1년=8760)을 적용했습니다.', 'success');
								}
								return;
							}

							if (key === 'basic') {
								applyBillingPreset(billingPresetDefaults.day, billingPresetDefaults.month, billingPresetDefaults.year);
								setSelectedPreset(null);
								if (typeof showCopilotToast === 'function') {
									showCopilotToast('추천설정 프리셋을 적용했습니다.', 'success');
								}
								return;
							}

							var presetId = String($(this).data('preset-id') || '');
							var preset = findPresetById(billingPresetPayload, presetId);
							if (!preset) {
								if (typeof showCopilotToast === 'function') {
									showCopilotToast('프리셋 정보를 찾을 수 없습니다.', 'warn');
								}
								return;
							}

							applyBillingPreset(parseFloat(preset.day), parseFloat(preset.month), parseFloat(preset.year));
							setSelectedPreset(preset);
							if (typeof showCopilotToast === 'function') {
								showCopilotToast('프리셋을 적용했습니다.', 'success');
							}
						});

						$('#billing_selected_preset_edit_btn').on('click', function() {
							if (!billingSelectedPresetId) {
								if (typeof showCopilotToast === 'function') showCopilotToast('먼저 사용자정의 프리셋을 선택해 주세요.', 'warn');
								return;
							}
							var selectedPreset = findPresetById(billingPresetPayload, billingSelectedPresetId);
							if (!selectedPreset) {
								setSelectedPreset(null);
								if (typeof showCopilotToast === 'function') showCopilotToast('선택된 프리셋을 찾을 수 없습니다.', 'warn');
								return;
							}
							openPresetEditor(selectedPreset);
						});

						$('#billing_preset_add_btn').on('click', function() {
							openPresetEditor(null);
						});

						$('#billing_preset_register_btn').on('click', function() {
							var v = readEditorValues();
							if (!validateEditorValues(v)) return;

							var newId = parseInt(billingPresetPayload.nextId, 10);
							if (!newId || newId < 1) newId = 1;

							billingPresetPayload.presets.push({
								id: newId,
								name: v.name,
								day: v.day,
								month: v.month,
								year: v.year
							});
							billingPresetPayload.nextId = newId + 1;
							saveBillingPresetPayload(billingPresetPayload);
							renderBillingCustomButtons(billingPresetPayload);
							var createdPreset = findPresetById(billingPresetPayload, newId);
							if (createdPreset) {
								setSelectedPreset(createdPreset);
								applyBillingPreset(parseFloat(createdPreset.day), parseFloat(createdPreset.month), parseFloat(createdPreset.year));
								openPresetEditor(createdPreset);
							}
							if (typeof showCopilotToast === 'function') showCopilotToast('사용자정의 프리셋을 등록했습니다.', 'success');
						});

						$('#billing_preset_update_btn').on('click', function() {
							var v = readEditorValues();
							if (!v.id) {
								if (typeof showCopilotToast === 'function') showCopilotToast('수정할 프리셋을 먼저 선택해 주세요.', 'warn');
								return;
							}
							if (!validateEditorValues(v)) return;

							var p = findPresetById(billingPresetPayload, v.id);
							if (!p) {
								if (typeof showCopilotToast === 'function') showCopilotToast('수정 대상 프리셋을 찾지 못했습니다.', 'warn');
								return;
							}

							p.name = v.name;
							p.day = v.day;
							p.month = v.month;
							p.year = v.year;
							saveBillingPresetPayload(billingPresetPayload);
							renderBillingCustomButtons(billingPresetPayload);
							setSelectedPreset(p);
							applyBillingPreset(parseFloat(p.day), parseFloat(p.month), parseFloat(p.year));
							if (typeof showCopilotToast === 'function') showCopilotToast('프리셋을 수정했습니다.', 'success');
						});

						$('#billing_preset_delete_btn').on('click', function() {
							var v = readEditorValues();
							if (!v.id) {
								if (typeof showCopilotToast === 'function') showCopilotToast('삭제할 프리셋을 먼저 선택해 주세요.', 'warn');
								return;
							}

							billingPresetPayload.presets = (billingPresetPayload.presets || []).filter(function(each) {
								return String(each.id) !== String(v.id);
							});
							saveBillingPresetPayload(billingPresetPayload);
							renderBillingCustomButtons(billingPresetPayload);
							if (String(billingSelectedPresetId) === String(v.id)) {
								setSelectedPreset(null);
							}
							$('#billing_preset_cancel_btn').trigger('click');
							if (typeof showCopilotToast === 'function') showCopilotToast('프리셋을 삭제했습니다.', 'success');
						});

						$('#billing_preset_cancel_btn').on('click', function() {
							$('#billing_preset_modal').hide();
							$('#billing_preset_edit_id').val('');
							$('#billing_preset_edit_name').val('');
							$('#billing_preset_edit_day').val('');
							$('#billing_preset_edit_month').val('');
							$('#billing_preset_edit_year').val('');
						});

						$('#billing_preset_modal_close_top').on('click', function() {
							$('#billing_preset_cancel_btn').trigger('click');
						});

						$('#billing_preset_modal').on('click', function(e) {
							if (e.target === this) {
								$('#billing_preset_cancel_btn').trigger('click');
							}
						});

						$(document).on('keydown', function(e) {
							if (e.key === 'Escape' && $('#billing_preset_modal').is(':visible')) {
								$('#billing_preset_cancel_btn').trigger('click');
							}
						});
					});
				</script>
			</td>
		</tr>

		<tr>
			<th scope="row"><label for="it_shop_memo">상점메모</label></th>
			<td>
				<?php echo help("상점메모는 [{$member['mb_name']}] 판매자 님만 보실 수 있습니다. 쇼핑몰(플랫폼)에는 공개되지 않습니다."); ?>
				<textarea name="it_shop_memo" id="it_shop_memo"><?php echo html_purifier($it['it_shop_memo']); ?></textarea>
			</td>
		</tr>

		<?php if($is_auth) { // 관리자일 때만 출력 ?>
			<tr>
				<th scope="row" class="admin-only-title"><label for="it_tel_inq">전화문의</label><?php echo $admin_only_badge; ?></th>
				<td>
					<?php echo help("상품 금액 대신 전화문의로 표시됩니다."); ?>
					<input type="checkbox" name="it_tel_inq" value="1" id="it_tel_inq" <?php echo ($it['it_tel_inq']) ? "checked" : ""; ?>> 예
				</td>
			</tr>
			<tr>
				<th scope="row" class="admin-only-title"><label for="it_nocoupon">쿠폰적용안함</label><?php echo $admin_only_badge; ?></th>
				<td>
					<?php echo help("설정에 체크하시면 쿠폰 생성 때 상품 검색 결과에 노출되지 않습니다."); ?>
					<input type="checkbox" name="it_nocoupon" value="1" id="it_nocoupon" <?php echo ($it['it_nocoupon']) ? "checked" : ""; ?>> 예
				</td>
			</tr>
			<tr>
				<th scope="row" class="admin-only-title"><label for="it_use">포인트결제안함</label><?php echo $admin_only_badge; ?></th>
				<td>
					<?php echo help("설정에 체크하시면 주문시 본 상품이 포함된 경우 포인트 결제 또는 포인트 사용을 할 수 없습니다."); ?>
					<label><input type="checkbox" name="pt_point" value="1" id="pt_point" <?php echo ($it['pt_point']) ? "checked" : ""; ?>> 예</label>
				</td>
			</tr>
			<tr>
				<th scope="row" class="admin-only-title"><label for="ec_mall_pid">네이버쇼핑 상품ID</label><?php echo $admin_only_badge; ?></th>
				<td colspan="2">
					<?php echo help("네이버쇼핑에 입점한 경우 네이버쇼핑 상품ID를 입력하시면 네이버페이와 연동됩니다."); ?>
					<input type="text" name="ec_mall_pid" value="<?php echo get_text($it['ec_mall_pid']); ?>" id="ec_mall_pid" class="frm_input" size="20">
				</td>
			</tr>
		<?php } // 관리자 끝 ?>

		</tbody>
        </table>
	</div>
</section>

<?php // echo $frm_submit; ?>

<?php // echo $pg_anchor; ?>

<section id="anc_sitfrm_compact" style="display:none;">
	<h2 class="h2_frm">상품요약정보</h2>
	<div class="local_desc02 local_desc">
		<p><strong>전자상거래 등에서의 상품 등의 정보제공에 관한 고시</strong>에 따라 총 35개 상품군에 대해 상품 특성 등을 양식에 따라 입력할 수 있습니다.</p>
	</div>

	<div id="sit_compact">
		<?php echo help("상품군을 선택하면 자동으로 항목이 변환됩니다."); ?>
		<select id="it_info_gubun" name="it_info_gubun">
			<option value="">상품군을 선택하세요.</option>
			<?php echo apms_it_gubun($it['it_info_gubun'], 'digital_contents'); // 우측은 초기값 ?>
		</select>
	</div>
	<div id="sit_compact_fields">
		<?php include_once('./iteminfo.php'); ?>
	</div>

	<script>
	$(function(){
	    $(document).on("change", "#it_info_gubun", function() {
			var gubun = $(this).val();
			$.post(
				"./iteminfo.php",
				{ it_id: "<?php echo $it['it_id']; ?>", gubun: gubun },
				function(data) {
					$("#sit_compact_fields").empty().html(data);
				}
			);
		});
	});
	</script>
</section>

<?php echo $frm_submit_with_recent; ?>

<?php // echo $pg_anchor; ?>

<section id="anc_sitfrm_cost">
	<h2 class="h2_frm">상품설명 (필요시 입력하세요)</h2>
	<div class="tbl_frm01 tbl_wrap">
		<table>
		<caption>상품설명</caption>
		<colgroup>
			<col class="grid_3">
			<col>
		</colgroup>
		<tbody>

		<tr>
            <th scope="row">상품설명</th>
            <td>
				<a href="<?php echo G5_BBS_URL;?>/helper.php" target="_blank" class="btn_frmline win_scrap">기능안내</a>
			</td>
		</tr>
		<tr>
            <td colspan="2">
				<?php echo editor_html('it_explan', get_text(html_purifier($it['it_explan']), 0)); ?>
			</td>
		</tr>
		<tr style="display:none;">
            <th scope="row">모바일 상품설명</th>
            <td>
				<a href="<?php echo G5_BBS_URL;?>/helper.php" target="_blank" class="btn_frmline win_scrap">기능안내</a>
			</td>
        </tr>
		<tr style="display:none;">
            <td colspan="2" class="iframe">
				<?php echo editor_html('it_mobile_explan', get_text(html_purifier($it['it_mobile_explan']), 0)); ?>
			</td>
        </tr>
		<tr>
			<th scope="row">판매자센터 아이디 (디버깅 표시)</th>
			<td>
				<?php echo help("디버깅을 위해 임시로 표시 중입니다. 정상 확인 후 hide 처리 예정입니다."); ?>
				<input type="text" name="pt_id" value="<?php echo ($it['pt_id'] !== '') ? $it['pt_id'] : $member['mb_id']; ?>" id="pt_id" class="frm_input sm" readonly>
			</td>
		</tr>
		<tr style="display:none;">
			<th scope="row"><label for="it_sell_email">판매자 e-mail</label></th>
			<td>
				<?php echo help("운영자와 실제 판매자가 다른 경우 실제 판매자의 e-mail을 입력하면, 상품 주문 시점을 기준으로 실제 판매자에게도 주문서를 발송합니다."); ?>
				<input type="text" name="it_sell_email" value="<?php echo get_sanitize_input($it['it_sell_email']); ?>" id="it_sell_email" class="frm_input sm">
			</td>
		</tr>

		<?php if($is_auth) { // 관리자일 때만 출력 ?>
			<tr>
				<th scope="row" class="admin-only-title">추천인 적립율<?php echo $admin_only_badge; ?></th>
				<td>
					<?php echo help("부가세를 제한 순판매액에 대해 추천인(마케터)에게 적립됩니다."); ?>
					<input type="text" name="pt_marketer" value="<?php echo $it['pt_marketer']; ?>" id="pt_marketer" class="frm_input sm"> % 적립
				</td>
			</tr>
		<?php } // 관리자 끝 ?>

		<tr style="display:none;">
			<th scope="row"><label for="it_notax">상품과세 유형</label></th>
			<td>
				<?php echo help("상품의 과세유형(과세, 비과세)을 설정합니다."); ?>
				<select name="it_notax" id="it_notax">
					<option value="0"<?php echo get_selected('0', $it['it_notax']); ?>>과세</option>
					<option value="1"<?php echo get_selected('1', $it['it_notax']); ?>>비과세</option>
				</select>
			</td>
		</tr>
		<?php
			$opt_subject = explode(',', $it['it_option_subject']);
		?>
		<tr style="display:none;">
			<th scope="row">상품선택옵션</th>
			<td>
				<div class="sit_option tbl_frm01">
					<?php echo help('옵션항목은 콤마(,) 로 구분하여 여러개를 입력할 수 있습니다. 예시) 라지,미디움,스몰<br><strong>옵션명과 옵션항목에 따옴표(\', ")는 입력할 수 없습니다.</strong>'); ?>
					<table>
					<caption>상품선택옵션 입력</caption>
					<colgroup>
						<col class="grid_4">
						<col>
					</colgroup>
					<tbody>
					<tr>
						<th scope="row">
							<label for="opt1_subject">옵션1</label>
							<input type="text" name="opt1_subject" value="<?php echo $opt_subject[0]; ?>" id="opt1_subject" class="frm_input" size="15">
						</th>
						<td>
							<label for="opt1"><b>옵션1 항목</b></label>
							<input type="text" name="opt1" value="" id="opt1" class="frm_input" size="50">
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="opt2_subject">옵션2</label>
							<input type="text" name="opt2_subject" value="<?php echo $opt_subject[1]; ?>" id="opt2_subject" class="frm_input" size="15">
						</th>
						<td>
							<label for="opt2"><b>옵션2 항목</b></label>
							<input type="text" name="opt2" value="" id="opt2" class="frm_input" size="50">
						</td>
					</tr>
					 <tr>
						<th scope="row">
							<label for="opt3_subject">옵션3</label>
							<input type="text" name="opt3_subject" value="<?php echo $opt_subject[2]; ?>" id="opt3_subject" class="frm_input" size="15">
						</th>
						<td>
							<label for="opt3"><b>옵션3 항목</b></label>
							<input type="text" name="opt3" value="" id="opt3" class="frm_input" size="50">
						</td>
					</tr>
					</tbody>
					</table>
					<div class="btn_confirm02 btn_confirm">
						<button type="button" id="option_table_create" class="btn_frmline">옵션목록생성</button>
					</div>
				</div>
				<div id="sit_option_frm"><?php include_once(G5_ADMIN_PATH.'/shop_admin/itemoption.php'); ?></div>

				<script>
				$(function() {
					<?php if($it['it_id'] && $po_run) { ?>
					//옵션항목설정
					var arr_opt1 = new Array();
					var arr_opt2 = new Array();
					var arr_opt3 = new Array();
					var opt1 = opt2 = opt3 = '';
					var opt_val;

					$(".opt-cell").each(function() {
						opt_val = $(this).text().split(" > ");
						opt1 = opt_val[0];
						opt2 = opt_val[1];
						opt3 = opt_val[2];

						if(opt1 && $.inArray(opt1, arr_opt1) == -1)
							arr_opt1.push(opt1);

						if(opt2 && $.inArray(opt2, arr_opt2) == -1)
							arr_opt2.push(opt2);

						if(opt3 && $.inArray(opt3, arr_opt3) == -1)
							arr_opt3.push(opt3);
					});


					$("input[name=opt1]").val(arr_opt1.join());
					$("input[name=opt2]").val(arr_opt2.join());
					$("input[name=opt3]").val(arr_opt3.join());
					<?php } ?>
					// 옵션목록생성
					$("#option_table_create").click(function() {
						var it_id = $.trim($("input[name=it_id]").val());
						var opt1_subject = $.trim($("#opt1_subject").val());
						var opt2_subject = $.trim($("#opt2_subject").val());
						var opt3_subject = $.trim($("#opt3_subject").val());
						var opt1 = $.trim($("#opt1").val());
						var opt2 = $.trim($("#opt2").val());
						var opt3 = $.trim($("#opt3").val());
						var $option_table = $("#sit_option_frm");

						if(!opt1_subject || !opt1) {
							alert("옵션명과 옵션항목을 입력해 주십시오.");
							return false;
						}

						$.post(
							"./itemoption.php",
							{ it_id: it_id, w: "<?php echo $w; ?>", opt1_subject: opt1_subject, opt2_subject: opt2_subject, opt3_subject: opt3_subject, opt1: opt1, opt2: opt2, opt3: opt3 },
							function(data) {
								$option_table.empty().html(data);
							}
						);
					});

					// 모두선택
                    $(document).on("click", "input[name=opt_chk_all]", function() {
						if($(this).is(":checked")) {
							$("input[name='opt_chk[]']").attr("checked", true);
						} else {
							$("input[name='opt_chk[]']").attr("checked", false);
						}
					});

					// 선택삭제
                    $(document).on("click", "#sel_option_delete", function() {
						var $el = $("input[name='opt_chk[]']:checked");
						if($el.size() < 1) {
							alert("삭제하려는 옵션을 하나 이상 선택해 주십시오.");
							return false;
						}

						$el.closest("tr").remove();
					});

					// 일괄적용
                    $(document).on("click", "#opt_value_apply", function() {
						if($(".opt_com_chk:checked").size() < 1) {
							alert("일괄 수정할 항목을 하나이상 체크해 주십시오.");
							return false;
						}

						var opt_price = $.trim($("#opt_com_price").val());
						var opt_stock = $.trim($("#opt_com_stock").val());
						var opt_noti = $.trim($("#opt_com_noti").val());
						var opt_use = $("#opt_com_use").val();
						var $el = $("input[name='opt_chk[]']:checked");

						// 체크된 옵션이 있으면 체크된 것만 적용
						if($el.size() > 0) {
							var $tr;
							$el.each(function() {
								$tr = $(this).closest("tr");

								if($("#opt_com_price_chk").is(":checked"))
									$tr.find("input[name='opt_price[]']").val(opt_price);

								if($("#opt_com_stock_chk").is(":checked"))
									$tr.find("input[name='opt_stock_qty[]']").val(opt_stock);

								if($("#opt_com_noti_chk").is(":checked"))
									$tr.find("input[name='opt_noti_qty[]']").val(opt_noti);

								if($("#opt_com_use_chk").is(":checked"))
									$tr.find("select[name='opt_use[]']").val(opt_use);
							});
						} else {
							if($("#opt_com_price_chk").is(":checked"))
								$("input[name='opt_price[]']").val(opt_price);

							if($("#opt_com_stock_chk").is(":checked"))
								$("input[name='opt_stock_qty[]']").val(opt_stock);

							if($("#opt_com_noti_chk").is(":checked"))
								$("input[name='opt_noti_qty[]']").val(opt_noti);

							if($("#opt_com_use_chk").is(":checked"))
								$("select[name='opt_use[]']").val(opt_use);
						}
					});
				});
				</script>
			</td>
		</tr>
		<?php
			$spl_subject = explode(',', $it['it_supply_subject']);
			$spl_count = count($spl_subject);
		?>
		<tr style="display:none;">
			<th scope="row">상품추가옵션</th>
			<td>
				<div id="sit_supply_frm" class="sit_option tbl_frm01">
					<?php echo help('옵션항목은 콤마(,) 로 구분하여 여러개를 입력할 수 있습니다. 예시) 라지,미디움,스몰<br><strong>옵션명과 옵션항목에 따옴표(\', ")는 입력할 수 없습니다.</strong>'); ?>
					<table>
					<caption>상품추가옵션 입력</caption>
					<colgroup>
						<col class="grid_4">
						<col>
					</colgroup>
					<tbody>
					<?php
					$i = 0;
					do {
						$seq = $i + 1;
					?>
					<tr>
						<th scope="row">
							<label for="spl_subject_<?php echo $seq; ?>">추가<?php echo $seq; ?></label>
							<input type="text" name="spl_subject[]" id="spl_subject_<?php echo $seq; ?>" value="<?php echo $spl_subject[$i]; ?>" class="frm_input" size="15">
						</th>
						<td>
							<label for="spl_item_<?php echo $seq; ?>"><b>추가<?php echo $seq; ?> 항목</b></label>
							<input type="text" name="spl[]" id="spl_item_<?php echo $seq; ?>" value="" class="frm_input" size="40">
							<?php
							if($i > 0)
								echo '<button type="button" id="del_supply_row" class="btn_frmline">삭제</button>';
							?>
						</td>
					</tr>
					<?php
						$i++;
					} while($i < $spl_count);
					?>
					</tbody>
					</table>
					<div id="sit_option_addfrm_btn"><button type="button" id="add_supply_row" class="btn_frmline">옵션추가</button></div>
					<div class="btn_confirm02 btn_confirm">
						<button type="button" id="supply_table_create">옵션목록생성</button>
					</div>
				</div>
				<div id="sit_option_addfrm"><?php include_once(G5_ADMIN_PATH.'/shop_admin/itemsupply.php'); ?></div>

				<script>
				$(function() {
					<?php if($it['it_id'] && $ps_run) { ?>
					// 추가옵션의 항목 설정
					var arr_subj = new Array();
					var subj, spl;

					$("input[name='spl_subject[]']").each(function() {
						subj = $.trim($(this).val());
						if(subj && $.inArray(subj, arr_subj) == -1)
							arr_subj.push(subj);
					});

					for(i=0; i<arr_subj.length; i++) {
						var arr_spl = new Array();
						$(".spl-subject-cell").each(function(index) {
							subj = $(this).text();
							if(subj == arr_subj[i]) {
								spl = $(".spl-cell:eq("+index+")").text();
								arr_spl.push(spl);
							}
						});

						$("input[name='spl[]']:eq("+i+")").val(arr_spl.join());
					}
					<?php } ?>
					// 입력필드추가
					$("#add_supply_row").click(function() {
						var $el = $("#sit_supply_frm tr:last");
						var fld = "<tr>\n";
						fld += "<th scope=\"row\">\n";
						fld += "<label for=\"\">추가</label>\n";
						fld += "<input type=\"text\" name=\"spl_subject[]\" value=\"\" class=\"frm_input\" size=\"15\">\n";
						fld += "</th>\n";
						fld += "<td>\n";
						fld += "<label for=\"\"><b>추가 항목</b></label>\n";
						fld += "<input type=\"text\" name=\"spl[]\" value=\"\" class=\"frm_input\" size=\"40\">\n";
						fld += "<button type=\"button\" id=\"del_supply_row\" class=\"btn_frmline\">삭제</button>\n";
						fld += "</td>\n";
						fld += "</tr>";

						$el.after(fld);

						supply_sequence();
					});

					// 입력필드삭제
                    $(document).on("click", "#del_supply_row", function() {
						$(this).closest("tr").remove();

						supply_sequence();
					});

					// 옵션목록생성
					$("#supply_table_create").click(function() {
						var it_id = $.trim($("input[name=it_id]").val());
						var subject = new Array();
						var supply = new Array();
						var subj, spl;
						var count = 0;
						var $el_subj = $("input[name='spl_subject[]']");
						var $el_spl = $("input[name='spl[]']");
						var $supply_table = $("#sit_option_addfrm");

						$el_subj.each(function(index) {
							subj = $.trim($(this).val());
							spl = $.trim($el_spl.eq(index).val());

							if(subj && spl) {
								subject.push(subj);
								supply.push(spl);
								count++;
							}
						});

						if(!count) {
							alert("추가옵션명과 추가옵션항목을 입력해 주십시오.");
							return false;
						}

						$.post(
							"./itemsupply.php",
							{ it_id: it_id, w: "<?php echo $w; ?>", 'subject[]': subject, 'supply[]': supply },
							function(data) {
								$supply_table.empty().html(data);
							}
						);
					});

					// 모두선택
                    $(document).on("click", "input[name=spl_chk_all]", function() {
						if($(this).is(":checked")) {
							$("input[name='spl_chk[]']").attr("checked", true);
						} else {
							$("input[name='spl_chk[]']").attr("checked", false);
						}
					});

					// 선택삭제
                    $(document).on("click", "#sel_supply_delete", function() {
						var $el = $("input[name='spl_chk[]']:checked");
						if($el.size() < 1) {
							alert("삭제하려는 옵션을 하나 이상 선택해 주십시오.");
							return false;
						}

						$el.closest("tr").remove();
					});

					// 일괄적용
                    $(document).on("click", "#spl_value_apply", function() {
						if($(".spl_com_chk:checked").size() < 1) {
							alert("일괄 수정할 항목을 하나이상 체크해 주십시오.");
							return false;
						}

						var spl_price = $.trim($("#spl_com_price").val());
						var spl_stock = $.trim($("#spl_com_stock").val());
						var spl_noti = $.trim($("#spl_com_noti").val());
						var spl_use = $("#spl_com_use").val();
						var $el = $("input[name='spl_chk[]']:checked");

						// 체크된 옵션이 있으면 체크된 것만 적용
						if($el.size() > 0) {
							var $tr;
							$el.each(function() {
								$tr = $(this).closest("tr");

								if($("#spl_com_price_chk").is(":checked"))
									$tr.find("input[name='spl_price[]']").val(spl_price);

								if($("#spl_com_stock_chk").is(":checked"))
									$tr.find("input[name='spl_stock_qty[]']").val(spl_stock);

								if($("#spl_com_noti_chk").is(":checked"))
									$tr.find("input[name='spl_noti_qty[]']").val(spl_noti);

								if($("#spl_com_use_chk").is(":checked"))
									$tr.find("select[name='spl_use[]']").val(spl_use);
							});
						} else {
							if($("#spl_com_price_chk").is(":checked"))
								$("input[name='spl_price[]']").val(spl_price);

							if($("#spl_com_stock_chk").is(":checked"))
								$("input[name='spl_stock_qty[]']").val(spl_stock);

							if($("#spl_com_noti_chk").is(":checked"))
								$("input[name='spl_noti_qty[]']").val(spl_noti);

							if($("#spl_com_use_chk").is(":checked"))
								$("select[name='spl_use[]']").val(spl_use);
						}
					});
				});

				function supply_sequence()
				{
					var $tr = $("#sit_supply_frm tr");
					var seq;
					var th_label, td_label;

					$tr.each(function(index) {
						seq = index + 1;
						$(this).find("th label").attr("for", "spl_subject_"+seq).text("추가"+seq);
						$(this).find("th input").attr("id", "spl_subject_"+seq);
						$(this).find("td label").attr("for", "spl_item_"+seq);
						$(this).find("td label b").text("추가"+seq+" 항목");
						$(this).find("td input").attr("id", "spl_item_"+seq);
					});
				}
				</script>
			</td>
		</tr>
		<tr style="display:none;">
			<th scope="row"><label>상품메모옵션</label></th>
			<td>
				<?php echo help("텍스트 입력 옵션으로 미입력시 출력되지 않습니다. 옵션 항목명을 입력해 주세요."); ?>
				<input type="text" name="pt_msg1" value="<?php echo $it['pt_msg1']; ?>" id="pt_msg1" class="frm_input" size="18">
				<input type="text" name="pt_msg2" value="<?php echo $it['pt_msg2']; ?>" id="pt_msg2" class="frm_input" size="18">
				<input type="text" name="pt_msg3" value="<?php echo $it['pt_msg3']; ?>" id="pt_msg3" class="frm_input" size="18">
			</td>
		</tr>
		</tbody>
		</table>
	</div>
</section>

<section id="anc_sitfrm_sendcost" style="display:none;">
	<h2 class="h2_frm">배송비</h2>
	<div class="local_desc02 local_desc">
		<p>쇼핑몰설정 &gt; 배송비유형 설정보다 <strong>개별상품 배송비설정이 우선</strong> 적용됩니다.</p>
	</div>

	<div class="tbl_frm01 tbl_wrap">
		<table>
		<caption>배송비 입력</caption>
		<colgroup>
			<col class="grid_3">
			<col>
		</colgroup>
		<tbody>
			<tr>
				<th scope="row"><label for="it_sc_type">배송비 유형</label></th>
				<td>
					<?php echo help("배송비 유형을 선택하면 자동으로 항목이 변환됩니다."); ?>
					<input type="hidden" name="it_sc_type" id="it_sc_type" value="1"> <!-- VPN-Mall 온라인상품 특성상 무조건 무료배송이므로 1로 설정 -->
				</td>
			</tr>
		<tr id="sc_con_method">
			<th scope="row"><label for="it_sc_method">배송비 결제</label></th>
			<td>
					<select name="it_sc_method" id="it_sc_method">
						<option value="0"<?php echo get_selected('0', $it['it_sc_method']); ?>>선불</option>
						<option value="1"<?php echo get_selected('1', $it['it_sc_method']); ?>>착불</option>
						<option value="2"<?php echo get_selected('2', $it['it_sc_method']); ?>>사용자선택</option>
					</select>
				</td>
			</tr>
			<tr id="sc_con_basic">
				<th scope="row"><label for="it_sc_price">기본배송비</label></th>
				<td>
					<?php echo help("무료배송 이외의 설정에 적용되는 배송비 금액입니다."); ?>
					<input type="text" name="it_sc_price" value="<?php echo $it['it_sc_price']; ?>" id="it_sc_price" class="frm_input" size="8"> Point
				</td>
			</tr>
			<tr id="sc_con_minimum">
				<th scope="row"><label for="it_sc_minimum">배송비 상세조건</label></th>
				<td>
					주문금액 <input type="text" name="it_sc_minimum" value="<?php echo $it['it_sc_minimum']; ?>" id="it_sc_minimum" class="frm_input" size="8"> 이상 무료 배송
				</td>
			</tr>
			<tr id="sc_con_qty">
				<th scope="row"><label for="it_sc_qty">배송비 상세조건</label></th>
				<td>
					<?php echo help("상품의 주문 수량에 따라 배송비가 부과됩니다. 예를 들어 기본배송비가 3,000원 수량을 3으로 설정했을 경우 상품의 주문수량이 5개이면 6,000원 배송비가 부과됩니다."); ?>
					주문수량 <input type="text" name="it_sc_qty" value="<?php echo $it['it_sc_qty']; ?>" id="it_sc_qty" class="frm_input" size="8"> 마다 배송비 부과
				</td>
			</tr>
		</tbody>
		</table>
	</div>

	<script>
	$(function() {
		<?php
		switch($it['it_sc_type']) {
			case 1:
				echo '$("#sc_con_method").hide();'.PHP_EOL;
				echo '$("#sc_con_basic").hide();'.PHP_EOL;
				echo '$("#sc_con_minimum").hide();'.PHP_EOL;
				echo '$("#sc_con_qty").hide();'.PHP_EOL;
				echo '$("#sc_grp").attr("rowspan","1");'.PHP_EOL;
				break;
			case 2:
				echo '$("#sc_con_method").show();'.PHP_EOL;
				echo '$("#sc_con_basic").show();'.PHP_EOL;
				echo '$("#sc_con_minimum").show();'.PHP_EOL;
				echo '$("#sc_con_qty").hide();'.PHP_EOL;
				echo '$("#sc_grp").attr("rowspan","4");'.PHP_EOL;
				break;
			case 3:
				echo '$("#sc_con_method").show();'.PHP_EOL;
				echo '$("#sc_con_basic").show();'.PHP_EOL;
				echo '$("#sc_con_minimum").hide();'.PHP_EOL;
				echo '$("#sc_con_qty").hide();'.PHP_EOL;
				echo '$("#sc_grp").attr("rowspan","3");'.PHP_EOL;
				break;
			case 4:
				echo '$("#sc_con_method").show();'.PHP_EOL;
				echo '$("#sc_con_basic").show();'.PHP_EOL;
				echo '$("#sc_con_minimum").hide();'.PHP_EOL;
				echo '$("#sc_con_qty").show();'.PHP_EOL;
				echo '$("#sc_grp").attr("rowspan","4");'.PHP_EOL;
				break;
			default:
				echo '$("#sc_con_method").hide();'.PHP_EOL;
				echo '$("#sc_con_basic").hide();'.PHP_EOL;
				echo '$("#sc_con_minimum").hide();'.PHP_EOL;
				echo '$("#sc_con_qty").hide();'.PHP_EOL;
				echo '$("#sc_grp").attr("rowspan","2");'.PHP_EOL;
				break;
		}
		?>
		$("#it_sc_type").change(function() {
			var type = $(this).val();

			switch(type) {
				case "1":
					$("#sc_con_method").hide();
					$("#sc_con_basic").hide();
					$("#sc_con_minimum").hide();
					$("#sc_con_qty").hide();
					$("#sc_grp").attr("rowspan","1");
					break;
				case "2":
					$("#sc_con_method").show();
					$("#sc_con_basic").show();
					$("#sc_con_minimum").show();
					$("#sc_con_qty").hide();
					$("#sc_grp").attr("rowspan","4");
					break;
				case "3":
					$("#sc_con_method").show();
					$("#sc_con_basic").show();
					$("#sc_con_minimum").hide();
					$("#sc_con_qty").hide();
					$("#sc_grp").attr("rowspan","3");
					break;
				case "4":
					$("#sc_con_method").show();
					$("#sc_con_basic").show();
					$("#sc_con_minimum").hide();
					$("#sc_con_qty").show();
					$("#sc_grp").attr("rowspan","4");
					break;
				default:
					$("#sc_con_method").hide();
					$("#sc_con_basic").hide();
					$("#sc_con_minimum").hide();
					$("#sc_con_qty").hide();
					$("#sc_grp").attr("rowspan","1");
					break;
			}
		});
	});
	</script>
</section>

<?php if($is_admin == 'super') { //최고관리자만 가능 ?>
	<section id="anc_sitfrm_commission">
		<h2 class="h2_frm">판매수수료/인센티브</h2>

		<div class="local_desc02 local_desc">
			<p>판매자센터 기본설정 또는 판매자센터별 설정보다 <strong>상품의 개별설정이 우선</strong> 적용됩니다.</p>
		</div>

		<div class="tbl_frm01 tbl_wrap">
			<table>
			<caption>판매수수료/인센티브 입력</caption>
			<colgroup>
				<col class="grid_3">
				<col>
			</colgroup>
			<tbody>
				<tr id="sc_con_basic">
					<th scope="row" class="admin-only-title"><label for="it_sc_price">판매수수료</label><?php echo $admin_only_badge; ?></th>
					<td>
						<?php echo help("판매금액에서 차감되는 수수료율입니다. 0 입력시 기본 또는 판매자센터별 수수료가 자동적용됩니다."); ?>
						<input type="text" name="pt_commission" value="<?php echo $it['pt_commission']; ?>" id="pt_commission" class="frm_input" size="4"> %
					</td>
				</tr>
				<tr id="sc_con_basic">
					<th scope="row" class="admin-only-title"><label for="it_sc_price">인센티브</label><?php echo $admin_only_badge; ?></th>
					<td>
						<?php echo help("정산금액에 추가되는 인센티브율입니다. 0 입력시 기본 또는 판매자센터별 인센티브가 자동적용됩니다."); ?>
						<input type="text" name="pt_incentive" value="<?php echo $it['pt_incentive']; ?>" id="pt_incentive" class="frm_input" size="4"> %
					</td>
				</tr>
			</tbody>
			</table>
		</div>
	</section>
<?php } ?>

<?php // echo $frm_submit; ?>

<?php // echo $pg_anchor; ?>

<section id="anc_sitfrm_img" class="anc-section" style="display:none;">
    <h2 class="h2_frm">이미지</h2>
	<div class="local_desc02 local_desc">
		{이미지:1}, {이미지:2} 와 같이 이미지 번호를 입력하면 해당 첨부이미지를 내용에 출력할 수 있습니다.
	</div>

	<div class="tbl_frm01 tbl_wrap">
        <table>
        <caption>이미지 업로드</caption>
        <colgroup>
            <col class="grid_3">
            <col>
        </colgroup>
        <tbody>
        <?php for($i=1; $i<=10; $i++) { ?>
        <tr>
            <th scope="row"><label for="it_img1">이미지 <?php echo $i; ?></label></th>
            <td>
                <input type="file" name="it_img<?php echo $i; ?>" id="it_img<?php echo $i; ?>">
                <?php
                $it_img = G5_DATA_PATH.'/item/'.$it['it_img'.$i];
                if(is_file($it_img) && $it['it_img'.$i]) {
                    $size = @getimagesize($it_img);
                    $thumb = get_it_thumbnail($it['it_img'.$i], 25, 25);
                ?>
                <label for="it_img<?php echo $i; ?>_del"><span class="sound_only">이미지 <?php echo $i; ?> </span>파일삭제</label>
                <input type="checkbox" name="it_img<?php echo $i; ?>_del" id="it_img<?php echo $i; ?>_del" value="1">
                <span class="sit_wimg_limg<?php echo $i; ?>"><?php echo $thumb; ?></span>
                <div id="limg<?php echo $i; ?>" class="banner_or_img">
                    <img src="<?php echo G5_DATA_URL; ?>/item/<?php echo $it['it_img'.$i]; ?>" alt="" width="<?php echo $size[0]; ?>" height="<?php echo $size[1]; ?>">
                    <button type="button" class="sit_wimg_close">닫기</button>
                </div>
                <script>
                $('<button type="button" id="it_limg<?php echo $i; ?>_view" class="btn_frmline sit_wimg_view">이미지<?php echo $i; ?> 확인</button>').appendTo('.sit_wimg_limg<?php echo $i; ?>');
                </script>
                <?php } ?>
            </td>
        </tr>
        <?php } ?>
        </tbody>
        </table>
    </div>
</section>

<?php // echo $frm_submit; ?>

<?php // echo $pg_anchor; ?>

<section id="anc_sitfrm_relation" class="srel anc-section" style="display:none;">
    <h2 class="h2_frm">관련상품</h2>
    <div class="local_desc02 local_desc">
        <p>
            등록된 전체상품 목록에서 분류를 선택하면 해당 상품 리스트가 연이어 나타납니다.<br>
            상품 리스트에서 관련상품으로 추가하시면 선택된 관련상품 목록에 <strong>함께</strong> 추가됩니다.<br>
            예를 들어, A 상품에 B 상품을 관련상품으로 등록하면 B 상품에도 A 상품이 관련상품으로 자동 추가되며, <strong>확인 버튼을 누르셔야 정상 반영됩니다.</strong>
        </p>
    </div>

    <div class="compare_wrap">
        <section class="compare_left">
            <h3>등록된 전체상품 목록</h3>
            <label for="sch_relation" class="sound_only">분류</label>
            <span class="srel_pad">
                <select id="sch_relation">
                    <option value=''>분류별 상품</option>
					<?php echo apms_it_category($is_auth, $is_partner);?>
                </select>
                <label for="sch_name" class="sound_only">상품명</label>
                <input type="text" name="sch_name" id="sch_name" class="frm_input" size="15">
                <button type="button" id="btn_search_item" class="btn_frmline">검색</button>
            </span>
            <div id="relation" class="srel_list">
                <p>분류를 선택하거나 상품명 입력 후 검색해 주세요.</p>
            </div>
            <script>
            $(function() {
                $("#btn_search_item").click(function() {
                    var ca_id = $("#sch_relation").val();
                    var it_name = $.trim($("#sch_name").val());
                    var $relation = $("#relation");

                    if(ca_id == "" && it_name == "") {
                        $relation.html("<p>분류를 선택하거나 상품명 입력 후 검색해 주세요.</p>");
                        return false;
                    }

                    $("#relation").load(
                        "./itemformrelation.php",
                        { it_id: "<?php echo $it_id; ?>", ca_id: ca_id, it_name: it_name }
                    );
                });

                $(document).on("click", "#relation .add_item", function() {
					// 이미 등록된 상품인지 체크
                    var $li = $(this).closest("li");
                    var it_id = $li.find("input:hidden").val();
                    var it_id2;
                    var dup = false;
                    $("#reg_relation input[name='re_it_id[]']").each(function() {
                        it_id2 = $(this).val();
                        if(it_id == it_id2) {
                            dup = true;
                            return false;
                        }
                    });

                    if(dup) {
                        alert("이미 선택된 상품입니다.");
                        return false;
                    }

                    var cont = "<li>"+$li.html().replace("add_item", "del_item").replace("추가", "삭제")+"</li>";
                    var count = $("#reg_relation li").size();

                    if(count > 0) {
                        $("#reg_relation li:last").after(cont);
                    } else {
                        $("#reg_relation").html("<ul>"+cont+"</ul>");
                    }

                    $li.remove();
                });

                $(document).on("click", "#reg_relation .del_item", function() {
					var $row = $(this).closest("li");
					showCopilotConfirm("관련상품을 삭제하시겠습니까?", function() {
						$row.remove();

						var count = $("#reg_relation li").size();
						if(count < 1)
							$("#reg_relation").html("<p>선택된 상품이 없습니다.</p>");
					}, null, { title: '관련상품 삭제', okText: '삭제', type: 'warn', danger: true });
					return false;
                });
            });
            </script>
        </section>

        <section class="compare_right">
            <h3>선택된 관련상품 목록</h3>
            <span class="srel_pad"></span>
            <div id="reg_relation" class="srel_sel">
                <?php
                $str = array();
                $sql = " select b.ca_id, b.it_id, b.it_name, b.it_price
                           from {$g5['g5_shop_item_relation_table']} a
                           left join {$g5['g5_shop_item_table']} b on (a.it_id2=b.it_id)
                          where a.it_id = '$it_id'
                          order by ir_no asc ";
                $result = sql_query($sql);
                for($g=0; $row=sql_fetch_array($result); $g++)
                {
                    $it_name = get_it_image($row['it_id'], 50, 50).' '.$row['it_name'];

                    if($g==0)
                        echo '<ul>';
                ?>
                    <li>
                        <input type="hidden" name="re_it_id[]" value="<?php echo $row['it_id']; ?>">
                        <div class="list_item"><?php echo $it_name; ?></div>
                        <div class="list_item_btn"><button type="button" class="del_item btn_frmline">삭제</button></div>
                    </li>
                <?php
                    $str[] = $row['it_id'];
                }
                $str = implode(",", $str);

                if($g > 0)
                    echo '</ul>';
                else
                    echo '<p>선택된 상품이 없습니다.</p>';
                ?>
            </div>
            <input type="hidden" name="it_list" value="<?php echo $str; ?>">
        </section>

    </div>

</section>

<?php // echo $frm_submit; ?>

<?php if($is_auth) { ?>
	<?php // echo $pg_anchor; ?>
	<section id="anc_sitfrm_event" class="srel anc-section">
		<h2 class="h2_frm">관련이벤트</h2>
		<div class="compare_wrap">
			<section class="compare_left">
				<h3>등록된 전체이벤트 목록</h3>
				<div id="event_list" class="srel_list srel_noneimg">
					<?php
					$sql = " select ev_id, ev_subject from {$g5['g5_shop_event_table']} order by ev_id desc ";
					$result = sql_query($sql);
					for ($g=0; $row=sql_fetch_array($result); $g++) {
						if($g == 0)
							echo '<ul>';
					?>
						<li>
							<input type="hidden" name="ev_id[]" value="<?php echo $row['ev_id']; ?>">
							<div class="list_item"><?php echo get_text($row['ev_subject']); ?></div>
							<div class="list_item_btn"><button type="button" class="add_event btn_frmline">추가</button></div>
						</li>
					<?php
					}

					if($g > 0)
						echo '</ul>';
					else
						echo '<p>등록된 이벤트가 없습니다.</p>';
					?>
				</div>
				<script>
				$(function() {
	                $(document).on("click", "#event_list .add_event", function() {
						// 이미 등록된 이벤트인지 체크
						var $li = $(this).closest("li");
						var ev_id = $li.find("input:hidden").val();
						var ev_id2;
						var dup = false;
						$("#reg_event_list input[name='ev_id[]']").each(function() {
							ev_id2 = $(this).val();
							if(ev_id == ev_id2) {
								dup = true;
								return false;
							}
						});

						if(dup) {
							alert("이미 선택된 이벤트입니다.");
							return false;
						}

						var cont = "<li>"+$li.html().replace("add_event", "del_event").replace("추가", "삭제")+"</li>";
						var count = $("#reg_event_list li").size();

						if(count > 0) {
							$("#reg_event_list li:last").after(cont);
						} else {
							$("#reg_event_list").html("<ul>"+cont+"</ul>");
						}
					});

	                $(document).on("click", "#reg_event_list .del_event", function() {
						var $row = $(this).closest("li");
						showCopilotConfirm("이벤트를 삭제하시겠습니까?", function() {
							$row.remove();

							var count = $("#reg_event_list li").size();
							if(count < 1)
								$("#reg_event_list").html("<p>선택된 이벤트가 없습니다.</p>");
						}, null, { title: '이벤트 삭제', okText: '삭제', type: 'warn', danger: true });
						return false;
					});
				});
				</script>
			</section>

			<section class="compare_right">
				<h3>선택된 관련이벤트 목록</h3>
				<div id="reg_event_list" class="srel_sel srel_noneimg">
					<?php
					$str = "";
					$comma = "";
					$sql = " select b.ev_id, b.ev_subject
							   from {$g5['g5_shop_event_item_table']} a
							   left join {$g5['g5_shop_event_table']} b on (a.ev_id=b.ev_id)
							  where a.it_id = '$it_id'
							  order by b.ev_id desc ";
					$result = sql_query($sql);
					for ($g=0; $row=sql_fetch_array($result); $g++) {
						$str .= $comma . $row['ev_id'];
						$comma = ",";

						if($g == 0)
							echo '<ul>';
					?>
						<li>
							<input type="hidden" name="ev_id[]" value="<?php echo $row['ev_id']; ?>">
							<div class="list_item"><?php echo get_text($row['ev_subject']); ?></div>
							<div class="list_item_btn"><button type="button" class="del_event btn_frmline">삭제</button></div>
						</li>
					<?php
					}

					if($g > 0)
						echo '</ul>';
					else
						echo '<p>선택된 이벤트가 없습니다.</p>';
					?>
				</div>
				<input type="hidden" name="ev_list" value="<?php echo $str; ?>">
			</section>
		</div>

	</section>

	<?php echo $frm_submit_with_recent; ?>

<?php } ?>

<?php // echo $pg_anchor; ?>

<section id="anc_sitfrm_opt" class="anc-section" style="display:none;">
    <h2 class="h2_frm">옵션사항</h2>
	<div class="tbl_frm01 tbl_wrap">
        <table>
        <caption>옵션사항</caption>
        <colgroup>
            <col class="grid_3">
            <col>
        </colgroup>
        <tbody>
		<tr>
            <th scope="row">추가 상품설명</th>
            <td class="helper">
				구매한 회원에게만 출력되는 추가 상품설명입니다.
			</td>
        </tr>
		<tr>
            <td colspan="2" class="iframe">
				<?php echo editor_html('pt_explan', get_text(html_purifier($it['pt_explan']),0)); ?>
			</td>
        </tr>
		<tr>
            <th scope="row">모바일 추가 상품설명</th>
            <td class="helper">
				구매한 회원에게만 출력되는 모바일 추가 상품설명입니다.
			</td>
		</tr>
		<tr>
            <td colspan="2" class="iframe">
				<?php echo editor_html('pt_mobile_explan', get_text(html_purifier($it['pt_mobile_explan']),0)); ?>
			</td>
        </tr>
		<tr>
			<th scope="row"><label for="pt_ccl">CCL</label></th>
			<td>
				<select id="pt_ccl" name="pt_ccl">
					<option value="0"<?php echo get_selected('0', $it['pt_ccl']); ?>>표시안함</option>
					<option value="1"<?php echo get_selected('1', $it['pt_ccl']); ?>>저작자표시</option>
					<option value="2"<?php echo get_selected('2', $it['pt_ccl']); ?>>저작자표시-비영리</option>
					<option value="3"<?php echo get_selected('3', $it['pt_ccl']); ?>>저작자표시-변경금지</option>
					<option value="4"<?php echo get_selected('4', $it['pt_ccl']); ?>>저작자표시-동일조건변경허락</option>
					<option value="5"<?php echo get_selected('5', $it['pt_ccl']); ?>>저작자표시-비영리-동일조건변경허락</option>
					<option value="6"<?php echo get_selected('6', $it['pt_ccl']); ?>>저작자표시-비영리-변경금지</option>
				</select>
			</td>
		</tr>

        <tr>
            <th scope="row"><label for="pt_link1">관련링크1</label></th>
            <td>
                <?php echo help("각 요소는 바(|)로 구분하며, \"주소|이름|FA아이콘명\" 순으로 입력하시면 됩니다."); ?>
                <input type="text" name="pt_link1" value="<?php echo get_text($it['pt_link1']); ?>" id="pt_link1" class="frm_input sl">
            </td>
        </tr>
        <tr>
            <th scope="row"><label for="pt_link2">관련링크2</label></th>
            <td>
                <?php echo help("ex) http://www.youtube.com|유튜브|youtube"); ?>
                <input type="text" name="pt_link2" value="<?php echo get_text($it['pt_link2']); ?>" id="pt_link2" class="frm_input sl">
            </td>
        </tr>
		<?php if($is_auth || $default['pt_review_use']) { ?>
			<tr>
				<th scope="row"><label for="pt_review_use">후기등록</label></th>
				<td>
	                <?php echo help("체크하시면 쇼핑몰 설정과 관계없이 후기등록이 가능합니다."); ?>
					<label><input type="checkbox" name="pt_review_use" value="1" id="pt_review_use" <?php echo ($it['pt_review_use']) ? "checked" : ""; ?>> 구매와 상관없이 후기작성이 가능하도록 합니다.</label>
				</td>
			</tr>
		<?php } ?>
		<?php if($is_auth || $default['pt_comment_use']) { ?>
			<tr>
				<th scope="row"><label for="pt_comment_use">댓글등록</label></th>
				<td>
					<select name="pt_comment_use" id="pt_comment_use">
						<option value="1"<?php echo get_selected('1', $it['pt_comment_use']); ?>>모두 등록가능</option>
						<option value="2"<?php echo get_selected('2', $it['pt_comment_use']); ?>>나만 등록가능</option>
						<?php if($is_auth || $default['pt_comment_use'] != "2") { ?>
							<option value="0"<?php echo get_selected('0', $it['pt_comment_use']); ?>>댓글 사용안함</option>
						<?php } ?>
					</select>
				</td>
			</tr>
		<?php } ?>

		<?php if($is_auth || !$is_reserve_none) { ?>
			<?php if($is_auth || $is_reserve) { // 관리자 일 때 ?>
				<tr>
					<th scope="row"><label for="pt_reserve">판매예약</label></th>
					<td>
						<?php if(!$is_auth && $is_reserve_none) { ?>
							<?php if($it['pt_no']) { ?>
								<?php echo date("Y년 m월 d일 H시 i분", $it['pt_no']);?>에 판매되었습니다.
							<?php } else if($it['pt_reserve']) { ?>
								현재 <?php echo date("Y년 m월 d일 H시 i분", $it['pt_reserve']);?>으로 판매예약되어 있습니다.
							<?php } else { ?>
								상품등록 후 <?php echo $default['pt_reserve_none'];?>시간이 지나 예약설정 또는 변경이 불가능합니다.
							<?php } ?>
							<input type="hidden" name="pt_reserve_use" value="<?php echo $it['pt_reserve_use']; ?>">
							<input type="hidden" name="pt_reserve" value="<?php echo $it['pt_reserve']; ?>">
						<?php } else { ?>
							<?php
								if($is_auth) {
									if($is_reserve) {
										echo help("현재 ".$default['pt_reserve_day']."일 이내 등록상품을 대상으로 ".$default['pt_reserve_cache']."분 간격으로 예약상품을 체크하고 있습니다.");
									} else {
										echo help("판매예약은 판매자센터관리 > 기본설정에서 예약가능일, 예약체크, 예약대상을 모두 설정해 주셔야 작동합니다.");
									}
								} else {
									echo help("등록 후 {$default['pt_reserve_none']}시간이 지나면 예약 설정을 할 수 없습니다.");
								}
							?>
							<input type="text" id="pt_reserve_date"  name="pt_reserve_date" value="<?php echo $pt_rdate; ?>" class="frm_input" size="10" maxlength="10" readonly>
							<script>
								$(function(){
									$("#pt_reserve_date").datepicker({ changeMonth: true, changeYear: true, dateFormat: "yy-mm-dd", showButtonPanel: true, yearRange: "c-0:c+99", maxDate: "<?php echo $default['pt_reserve_end']?>" });
								});
							</script>
							&nbsp;
							<select name="pt_reserve_hour" id="pt_reserve_hour">
								<?php for($i=0; $i < 24; $i++) { $im = sprintf("%02d", $i); ?>
									<option value="<?php echo $im;?>"<?php echo get_selected($im, $pt_rhour); ?>><?php echo $im;?>시</option>
								<?php } ?>
							</select>
							&nbsp;
							<select name="pt_reserve_minute" id="pt_reserve_minute">
								<option value="00"<?php echo get_selected('00', $pt_rminute); ?>>00분</option>
								<option value="05"<?php echo get_selected('05', $pt_rminute); ?>>05분</option>
								<?php for($i=2; $i < 12; $i++) { $im = $i * 5; ?>
									<option value="<?php echo $im;?>"<?php echo get_selected($im, $pt_rminute); ?>><?php echo $im;?>분</option>
								<?php } ?>
							</select>
							&nbsp;
							<label><input type="checkbox" name="pt_reserve_use" value="1" id="pt_reserve_use" <?php echo ($it['pt_reserve_use']) ? "checked" : ""; ?>> 예약하기</label>
						<?php } ?>
					</td>
				</tr>
			<?php } ?>
			<tr>
				<th scope="row"><label for="pt_end">판매종료</label></th>
				<td>
					<?php if($is_reserve_none) echo help("판매종료는 판매자센터관리 > 기본설정에서 예약체크가 설정되어 있어야 작동합니다."); ?>
					<input type="text" id="pt_end_date"  name="pt_end_date" value="<?php echo $pt_edate; ?>" class="frm_input" size="10" maxlength="10" readonly>
					<script>
						$(function(){
							$("#pt_end_date").datepicker({ changeMonth: true, changeYear: true, dateFormat: "yy-mm-dd", showButtonPanel: true, yearRange: "c-0:c+2" });
						});
					</script>
					&nbsp;
					<select name="pt_end_hour" id="pt_end_hour">
						<?php for($i=0; $i < 24; $i++) { $im = sprintf("%02d", $i); ?>
							<option value="<?php echo $im;?>"<?php echo get_selected($im, $pt_ehour); ?>><?php echo $im;?>시</option>
						<?php } ?>
					</select>
					&nbsp;
					<select name="pt_end_minute" id="pt_end_minute">
						<option value="00"<?php echo get_selected('00', $pt_eminute); ?>>00분</option>
						<option value="05"<?php echo get_selected('05', $pt_eminute); ?>>05분</option>
						<?php for($i=2; $i < 12; $i++) { $im = $i * 5; ?>
							<option value="<?php echo $im;?>"<?php echo get_selected($im, $pt_eminute); ?>><?php echo $im;?>분</option>
						<?php } ?>
					</select>
					&nbsp;
					<button type="button" onclick="this.form.pt_end_date.value='';" class="btn_frmline">종료설정해제</button>
				</td>
			</tr>
		<?php } // 예약 끝 ?>
		<?php if($is_auth) { // 관리자일 때만 출력 ?>
			<?php if ($w == "u") { ?>
			<tr>
				<th scope="row" class="admin-only-title">입력일시<?php echo $admin_only_badge; ?></th>
				<td colspan="2">
					<?php echo help("상품을 처음 입력(등록)한 시간입니다."); ?>
					<?php echo $it['it_time']; ?>
				</td>
			</tr>
			<tr>
				<th scope="row" class="admin-only-title">수정일시<?php echo $admin_only_badge; ?></th>
				<td colspan="2">
					<?php echo help("상품을 최종 수정한 시간입니다."); ?>
					<?php echo $it['it_update_time']; ?>
				</td>
			</tr>
			<?php } ?>
		<?php } // 관리자 끝 ?>
		</tbody>
        </table>
	</div>
</section>

<?php // echo $frm_submit; ?>

<?php // echo $pg_anchor; ?>

<section id="anc_sitfrm_attach" class="anc-section" style="display:none;">
    <h2 class="h2_frm">파일첨부</h2>
    <div class="tbl_frm01 tbl_wrap">
        <table>
        <caption>첨부파일 업로드</caption>
        <colgroup>
			<col class="grid_3">
            <col>
            <col class="grid_3">
			<col class="grid_3">
            <col class="grid_3">
            <col class="grid_3">
            <col class="grid_3">
        </colgroup>
        <tbody>
		<tr>
			<th>옵션설정안내</th>
	        <td colspan="6">
				"<strong>구매</strong>" 체크시 구매한 회원에게만 노출되며, "<strong>다운</strong>" 체크시 다운로드 가능하고, 오디오나 동영상은 "<strong>보기</strong>" 체크시 JWPlayer로 실행할 수 있습니다.
			</td>
	    </tr>
		<?php $attach = apms_get_file('item', $it['it_id']); ?>
		<?php for ($i=0; $i < 10; $i++) { ?>
			<tr>
			<td>
				<?php if($attach[$i]['file']) { ?>
					<a href="<?php echo $attach[$i]['href'];?>"><?php echo $attach[$i]['source'];?> (<?php echo $attach[$i]['size'];?>)</a>
				<?php } ?>
			</td>
			<td>
				<input type="file" name="pf_file[]" title="파일첨부 <?php echo $i+1 ?> : 용량 <?php echo $upload_max_filesize ?> 이하만 업로드 가능">
			</td>
			<td align="center">
				<?php if($attach[$i]['file']) { ?>
					<label><input type="checkbox" id="pf_file_del<?php echo $i ?>" name="pf_file_del[<?php echo $i;  ?>]" value="1"> 삭제</label>
				<?php } ?>
			</td>
			<td align="center">
				<label><input type="checkbox" id="pf_purchase<?php echo $i ?>" name="pf_purchase[<?php echo $i;  ?>]" value="1"<?php echo ($attach[$i]['purchase_use']) ? ' checked' : '';?>> 구매</label>
			</td>
			<td align="center">
				<label><input type="checkbox" id="pf_download<?php echo $i ?>" name="pf_download[<?php echo $i;  ?>]" value="1"<?php echo ($attach[$i]['download_use']) ? ' checked' : '';?>> 다운</label>
			</td>
			<td align="center">
				<label><input type="checkbox" id="pf_view<?php echo $i ?>" name="pf_view[<?php echo $i;  ?>]" value="1"<?php echo ($attach[$i]['view_use']) ? ' checked' : '';?>> 보기</label>
			</td>
			<td align="center">
				<label><input type="checkbox" id="pf_guest<?php echo $i ?>" name="pf_guest[<?php echo $i;  ?>]" value="1"<?php echo ($attach[$i]['guest_use']) ? ' checked' : '';?>> 비회원</label>
			</td>
			</tr>
		<?php } ?>
        </tbody>
        </table>
    </div>
</section>

<?php // echo $frm_submit; ?>

<?php if($is_auth) { // 관리자일 때만 출력 ?>

	<?php // echo $pg_anchor; ?>

	<section id="anc_sitfrm_optional" class="anc-section">
		<h2 class="h2_frm">상하단내용</h2>
		<div class="tbl_frm01 tbl_wrap">
			<table>
			<caption>상하단내용설정</caption>
			<colgroup>
				<col class="grid_3">
				<col>
			</colgroup>
			<tbody>
			<tr>
				<th scope="row" class="admin-only-title">상단내용<?php echo $admin_only_badge; ?></th>
				<td class="helper">상세설명 페이지 상단에 출력하는 HTML 내용입니다.</td>
			</tr>
			<tr>
				<td colspan="2" class="iframe"><?php echo editor_html('it_head_html', get_text(html_purifier($it['it_head_html']), 0)); ?></td>
			</tr>
			<tr>
				<th scope="row" class="admin-only-title">하단내용<?php echo $admin_only_badge; ?></th>
				<td class="helper">상세설명 페이지 하단에 출력하는 HTML 내용입니다.</td>
			</tr>
			<tr>
				<td colspan="2" class="iframe"><?php echo editor_html('it_tail_html', get_text(html_purifier($it['it_tail_html']), 0)); ?></td>
			</tr>
			<tr>
				<th scope="row" class="admin-only-title">모바일 상단내용<?php echo $admin_only_badge; ?></th>
				<td class="helper">모바일 상세설명 페이지 상단에 출력하는 HTML 내용입니다.</td>
			</tr>
			<tr>
				<td colspan="2" class="iframe"><?php echo editor_html('it_mobile_head_html', get_text(html_purifier($it['it_mobile_head_html']), 0)); ?></td>
			</tr>
			<tr>
				<th scope="row" class="admin-only-title">모바일 하단내용<?php echo $admin_only_badge; ?></th>
				<td class="helper">모바일 상세설명 페이지 하단에 출력하는 HTML 내용입니다.</td>
			</tr>
			<tr>
				<td colspan="2" class="iframe"><?php echo editor_html('it_mobile_tail_html', get_text(html_purifier($it['it_mobile_tail_html']), 0)); ?></td>
			</tr>
			</tbody>
			</table>
		</div>
	</section>

	<?php echo $frm_submit_with_recent; ?>

	<?php // echo $pg_anchor; ?>

	<section id="anc_sitfrm_extra" class="anc-section">
		<h2 class="h2_frm">여분필드 설정</h2>
		<div class="tbl_frm01 tbl_wrap">
			<table>
			<colgroup>
				<col class="grid_3">
				<col>
			</colgroup>
			<tbody>
			<?php for ($i=1; $i<=10; $i++) { ?>
			<tr>
				<th scope="row" class="admin-only-title">여분필드<?php echo $i ?><?php echo $admin_only_badge; ?></th>
				<td class="td_extra">
					<label for="it_<?php echo $i ?>_subj">여분필드 <?php echo $i ?> 제목</label>
					<input type="text" name="it_<?php echo $i ?>_subj" id="it_<?php echo $i ?>_subj" value="<?php echo get_text($it['it_'.$i.'_subj']) ?>" class="frm_input">
					<label for="it_<?php echo $i ?>">여분필드 <?php echo $i ?> 값</label>
					<input type="text" name="it_<?php echo $i ?>" value="<?php echo get_text($it['it_'.$i]) ?>" id="it_<?php echo $i ?>" class="frm_input">
				</td>
			</tr>
			<?php } ?>
			</tbody>
			</table>
		</div>
	</section>

<?php } else { // 판매자센터 ?>
	<?php for ($i=1; $i<=10; $i++) { ?>
		<input type="hidden" name="it_<?php echo $i ?>_subj" id="it_<?php echo $i ?>_subj" value="<?php echo get_text($it['it_'.$i.'_subj']) ?>">
		<input type="hidden" name="it_<?php echo $i ?>" value="<?php echo get_text($it['it_'.$i]) ?>" id="it_<?php echo $i ?>">
	<?php } ?>
<?php } ?>

<?php echo $frm_submit_with_recent; ?>

<?php include_once(__DIR__ . '/_leave_confirm_helper.php'); ?>

<script>
	var rpcItemFormMode = <?php echo json_encode($w == '' ? 'new' : 'edit'); ?>;
</script>

<script>
	(function() {
		function clearFloatingInitMask() {
			document.documentElement.classList.remove('rpc-floating-init-pending');
		}

		function initFloatingSubmitMenu() {
			var allMenus = document.querySelectorAll('.btn_confirm01.btn_confirm');
			if (!allMenus || !allMenus.length) {
				clearFloatingInitMask();
				return;
			}

			var submitMenus = [];
			for (var i = 0; i < allMenus.length; i++) {
				var menu = allMenus[i];
				if (menu.querySelector('input[type="submit"], button[type="submit"], .btn_submit')) {
					submitMenus.push(menu);
				}
			}

			if (!submitMenus.length) {
				clearFloatingInitMask();
				return;
			}

			var primaryMenu = submitMenus[0];
			for (var j = 1; j < submitMenus.length; j++) {
				submitMenus[j].classList.add('rpc-floating-menu-clone-hidden');
				submitMenus[j].setAttribute('aria-hidden', 'true');
			}

			primaryMenu.classList.add('rpc-floating-menu');
			primaryMenu.setAttribute('data-rpc-floating-menu', '1');
			primaryMenu.style.visibility = 'hidden';

			// 컨트롤 행: 드래그핸들 + 모드토글 아이콘을 묶어 액션 버튼과 시각적 분리
			var controlRow = primaryMenu.querySelector('.rpc-floating-control-row');
			if (!controlRow) {
				controlRow = document.createElement('div');
				controlRow.className = 'rpc-floating-control-row';
				primaryMenu.insertBefore(controlRow, primaryMenu.firstChild);
			}

			var handle = primaryMenu.querySelector('.rpc-floating-drag-handle');
			if (!handle) {
				handle = document.createElement('span');
				handle.className = 'rpc-floating-drag-handle';
				var _ctxIsEdit = (typeof rpcItemFormMode !== 'undefined' && rpcItemFormMode === 'edit');
				var _ctxBadgeClass = _ctxIsEdit ? 'rpc-ctx-badge is-edit' : 'rpc-ctx-badge';
				var _ctxBadgeText = _ctxIsEdit ? '✏️ 수정중' : '🆕 신규등록';
				var _ctxTitle = _ctxIsEdit ? '상품 수정 폼 — 드래그로 이동 가능' : '상품 신규등록 폼 — 드래그로 이동 가능';
				handle.innerHTML = '☰ 메뉴<span class="' + _ctxBadgeClass + '">' + _ctxBadgeText + '</span>';
				handle.setAttribute('title', _ctxTitle);
				controlRow.appendChild(handle);
			}

			var modeToggleBtn = primaryMenu.querySelector('.rpc-floating-mode-toggle');
			if (!modeToggleBtn) {
				modeToggleBtn = document.createElement('button');
				modeToggleBtn.type = 'button';
				modeToggleBtn.className = 'rpc-floating-mode-toggle';
				controlRow.appendChild(modeToggleBtn);
			}

			var storageKey = 'vpn-mall-floating-menu-pos';
			var modeStorageKey = 'vpn-mall-floating-menu-mode';
			var dragState = null;
			var currentMode = 'horizontal';

			function readMode() {
				try {
					var saved = String(window.localStorage.getItem(modeStorageKey) || '').toLowerCase();
					if (saved === 'horizontal' || saved === 'vertical') {
						return saved;
					}
				} catch (e) {}
				return 'vertical';
			}

			function saveMode(mode) {
				try { window.localStorage.setItem(modeStorageKey, mode); } catch (e) {}
			}

			function updateModeToggleText() {
				var _isVert = (currentMode === 'vertical');
				var _icon = _isVert ? '↔' : '↕';
				var _label = _isVert ? '가로형으로 전환' : '세로형으로 전환';
				modeToggleBtn.innerHTML = '<span style="display:block;line-height:1;pointer-events:none;" aria-hidden="true">' + _icon + '</span>';
				modeToggleBtn.setAttribute('title', _label);
				modeToggleBtn.setAttribute('aria-label', _label);
			}

			function setMenuMode(mode) {
				currentMode = (mode === 'vertical') ? 'vertical' : 'horizontal';
				primaryMenu.classList.toggle('rpc-floating-menu-horizontal', currentMode === 'horizontal');
				primaryMenu.classList.toggle('rpc-floating-menu-vertical', currentMode === 'vertical');
				primaryMenu.setAttribute('data-menu-mode', currentMode);
				updateModeToggleText();
			}

			function normalizeSpace(text) {
				return String(text || '').replace(/\s+/g, ' ').trim();
			}

			function setCompactAnchorText(anchorEl, icon, shortLabel, fullLabel) {
				if (!anchorEl) {
					return;
				}
				anchorEl.innerHTML = '<span class="rpc-btn-icon" aria-hidden="true">' + icon + '</span><span class="rpc-btn-label">' + shortLabel + '</span>';
				anchorEl.setAttribute('title', fullLabel || shortLabel);
			}

			function setCompactButtonText(buttonEl, icon, shortLabel, fullLabel) {
				if (!buttonEl) {
					return;
				}
				buttonEl.innerHTML = '<span class="rpc-btn-icon" aria-hidden="true">' + icon + '</span><span class="rpc-btn-label">' + shortLabel + '</span>';
				buttonEl.setAttribute('title', fullLabel || shortLabel);
			}

			function appendQueryParam(url, key, value) {
				var input = String(url || '');
				if (!input) {
					return input;
				}

				var hashIndex = input.indexOf('#');
				var hashPart = '';
				var basePart = input;
				if (hashIndex >= 0) {
					hashPart = input.substring(hashIndex);
					basePart = input.substring(0, hashIndex);
				}

				var encodedKey = encodeURIComponent(String(key || ''));
				var encodedValue = encodeURIComponent(String(value || ''));
				if (!encodedKey) {
					return input;
				}

				var regex = new RegExp('([?&])' + encodedKey + '=[^&#]*', 'i');
				if (regex.test(basePart)) {
					basePart = basePart.replace(regex, '$1' + encodedKey + '=' + encodedValue);
				} else {
					basePart += (basePart.indexOf('?') >= 0 ? '&' : '?') + encodedKey + '=' + encodedValue;
				}

				return basePart + hashPart;
			}

			function ensureDetailPreviewLayer() {
				var layer = document.getElementById('item-detail-preview-layer');
				if (layer) {
					return layer;
				}

				var _isDark    = document.documentElement.getAttribute('data-site-theme') === 'dark';
				var _modalBg   = _isDark ? '#1a1b1e' : '#fff';
				var _toolbarBg = _isDark ? '#252528' : '#f8fafc';
				var _borderCol = _isDark ? '#3a3a42' : '#e5e7eb';
				var _titleCol  = _isDark ? '#e4e4e7' : '#111827';
				var _iframeBg  = _isDark ? '#1a1b1e' : '#f9fafb';
				var _hintCol   = _isDark ? '#71717a' : '#9ca3af';
				var _shadow    = _isDark ? '0 24px 46px rgba(0,0,0,0.55)' : '0 24px 46px rgba(0,0,0,0.28)';

				/* 스피너/진행바 CSS 1회 주입 */
				if (!document.getElementById('pvl-style')) {
					var _pvlStyle = document.createElement('style');
					_pvlStyle.id = 'pvl-style';
					_pvlStyle.textContent = '@keyframes pvl-spin{to{transform:rotate(360deg)}}'
						+ '@keyframes pvl-progress{from{width:0%}to{width:82%}}'
						+ '#item-detail-preview-spinner{animation:pvl-spin .78s linear infinite}'
						+ '#item-detail-preview-bar.pvl-running{animation:pvl-progress 7s cubic-bezier(.05,.65,.9,1) forwards}'
						+ '#item-detail-preview-loader{transition:opacity .32s ease}'
						+ '#item-detail-preview-loader.pvl-out{opacity:0;pointer-events:none}';
					document.head.appendChild(_pvlStyle);
				}

				layer = document.createElement('div');
				layer.id = 'item-detail-preview-layer';
				layer.style.cssText = 'display:none;position:fixed;inset:0;z-index:10040;background:rgba(15,23,42,0.55);';
				layer.innerHTML = ''
					+ '<div style="position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:min(1200px,calc(100% - 24px));height:min(860px,calc(100% - 24px));background:' + _modalBg + ';border-radius:10px;overflow:hidden;box-shadow:' + _shadow + ';display:flex;flex-direction:column;">'
					+ '  <div style="height:48px;flex-shrink:0;display:flex;align-items:center;justify-content:space-between;gap:8px;padding:0 12px;border-bottom:1px solid ' + _borderCol + ';background:' + _toolbarBg + ';">'
					+ '    <strong style="font-size:14px;color:' + _titleCol + ';">상세페이지 미리보기</strong>'
					+ '    <div style="display:flex;align-items:center;gap:8px;">'
					+ '      <a href="#" id="item-detail-preview-newtab" class="btn_frmline" target="_blank" rel="noopener" style="display:inline-flex;align-items:center;justify-content:center;height:32px !important;min-height:32px !important;line-height:32px !important;padding:0 12px;margin:0 !important;box-sizing:border-box;vertical-align:middle;background:#4b5563 !important;border:1px solid #4b5563 !important;color:#fff !important;border-radius:6px !important;font-size:14px !important;font-weight:600 !important;text-decoration:none !important;cursor:pointer !important;white-space:nowrap;">새탭으로 보기</a>'
					+ '      <button type="button" id="item-detail-preview-close" class="btn_frmline" style="display:inline-flex;align-items:center;justify-content:center;height:32px !important;min-height:32px !important;line-height:32px !important;padding:0 12px;margin:0 !important;box-sizing:border-box;vertical-align:middle;background:#4b5563 !important;border:1px solid #4b5563 !important;color:#fff !important;border-radius:6px !important;font-size:14px !important;font-weight:600 !important;text-decoration:none !important;cursor:pointer !important;white-space:nowrap;">닫기</button>'
					+ '    </div>'
					+ '  </div>'
					+ '  <div style="flex:1 1 auto;position:relative;min-height:0;overflow:hidden;">'
					+ '    <iframe id="item-detail-preview-frame" src="about:blank" style="position:absolute;inset:0;width:100%;height:100%;border:0;background:' + _iframeBg + ';" loading="lazy"></iframe>'
					+ '    <div id="item-detail-preview-loader" style="position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:16px;background:' + _iframeBg + ';z-index:5;">'
					+ '      <div style="position:absolute;top:0;left:0;right:0;height:3px;background:rgba(96,165,250,0.12);overflow:hidden;"><div id="item-detail-preview-bar" style="height:100%;width:0%;background:linear-gradient(90deg,#2563eb,#60a5fa,#93c5fd);border-radius:0 2px 2px 0;"></div></div>'
					+ '      <div id="item-detail-preview-spinner" style="width:44px;height:44px;border:3.5px solid rgba(96,165,250,0.18);border-top-color:#60a5fa;border-radius:50%;flex-shrink:0;"></div>'
					+ '      <span style="font-size:13px;color:' + _hintCol + ';letter-spacing:0.04em;">페이지를 불러오는 중…</span>'
					+ '    </div>'
					+ '  </div>'
					+ '</div>';

				document.body.appendChild(layer);

				var closeBtn = document.getElementById('item-detail-preview-close');
				closeBtn.addEventListener('click', function() {
					closeDetailPreviewLayer();
				});

				layer.addEventListener('click', function(e) {
					if (e.target === layer) {
						closeDetailPreviewLayer();
					}
				});

				document.addEventListener('keydown', function(e) {
					if (e.key === 'Escape' && layer.style.display === 'block') {
						closeDetailPreviewLayer();
					}
				});

				return layer;
			}

			function openDetailPreviewLayer(url) {
				if (!url) return;
				var layer   = ensureDetailPreviewLayer();
				var frame   = document.getElementById('item-detail-preview-frame');
				var newTab  = document.getElementById('item-detail-preview-newtab');
				var loader  = document.getElementById('item-detail-preview-loader');
				var bar     = document.getElementById('item-detail-preview-bar');
				var previewUrl = appendQueryParam(url, 'preview_layer', '1');

				if (newTab) newTab.setAttribute('href', url);

				/* 로더 초기화 & 표시 */
				if (loader) {
					loader.classList.remove('pvl-out');
					loader.style.display = 'flex';
					loader.style.opacity = '1';
				}
				if (bar) {
					bar.classList.remove('pvl-running');
					bar.style.transition = 'none';
					bar.style.width = '0%';
					bar.offsetHeight; /* reflow → 애니메이션 재시작 */
					bar.style.transition = '';
					bar.classList.add('pvl-running');
				}

				if (frame) {
					frame.onload = null;
					frame.onload = function() {
						/* 진행바 100% 완료 */
						if (bar) {
							bar.classList.remove('pvl-running');
							bar.style.transition = 'width 0.22s ease';
							bar.style.width = '100%';
						}
						/* 로더 페이드아웃 */
						setTimeout(function() {
							if (loader) {
								loader.classList.add('pvl-out');
								setTimeout(function() {
									loader.style.display = 'none';
									loader.classList.remove('pvl-out');
									if (bar) { bar.style.width = '0%'; bar.style.transition = 'none'; }
								}, 340);
							}
						}, 180);
					};
					frame.setAttribute('src', previewUrl);
				}

				layer.style.display = 'block';
			}

			function closeDetailPreviewLayer() {
				var layer  = document.getElementById('item-detail-preview-layer');
				if (!layer) return;
				var frame  = document.getElementById('item-detail-preview-frame');
				var loader = document.getElementById('item-detail-preview-loader');
				var bar    = document.getElementById('item-detail-preview-bar');
				if (frame) { frame.onload = null; frame.setAttribute('src', 'about:blank'); }
				if (loader) { loader.style.display = 'none'; loader.classList.remove('pvl-out'); }
				if (bar)    { bar.classList.remove('pvl-running'); bar.style.width = '0%'; bar.style.transition = 'none'; }
				layer.style.display = 'none';
			}

			function decorateFloatingButtons() {
				var submitBtn = primaryMenu.querySelector('input[type="submit"], .btn_submit');
				if (submitBtn) {
					submitBtn.classList.add('rpc-btn-apply');
					submitBtn.value = '✅ 적용하기';
					submitBtn.setAttribute('title', '적용하기');
				}

				var anchors = primaryMenu.querySelectorAll('a');
				for (var ai = 0; ai < anchors.length; ai++) {
					var text = normalizeSpace(anchors[ai].textContent);
					if (/내상품관리|목록보기/.test(text)) {
						anchors[ai].classList.add('rpc-btn-list');
						setCompactAnchorText(anchors[ai], '📋', '목록보기', '내상품관리 목록보기');
						if (window.rpcMenuLeaveConfirm && typeof window.rpcMenuLeaveConfirm.bindToAnchor === 'function') {
							window.rpcMenuLeaveConfirm.bindToAnchor(anchors[ai], '목록보기');
						}
						continue;
					}

					if (/신규등록하기|신규등록/.test(text)) {
						anchors[ai].classList.add('rpc-btn-new');
						setCompactAnchorText(anchors[ai], '🆕', '신규등록', '신규등록하기');
						if (window.rpcMenuLeaveConfirm && typeof window.rpcMenuLeaveConfirm.bindToAnchor === 'function') {
							window.rpcMenuLeaveConfirm.bindToAnchor(anchors[ai], '신규등록하기');
						}
						continue;
					}

					if (/상세페이지보기/.test(text)) {
						anchors[ai].classList.add('rpc-btn-detail');
						setCompactAnchorText(anchors[ai], '🔎', '상세보기', '상세페이지보기');
						if (!anchors[ai].dataset.previewBound) {
							anchors[ai].dataset.previewBound = '1';
							anchors[ai].addEventListener('click', function(e) {
								e.preventDefault();
								e.stopPropagation();
								openDetailPreviewLayer(this.getAttribute('href') || '');
							});
						}
					}
				}

				var recentBtn = primaryMenu.querySelector('.js-recent-config-open');
				if (recentBtn) {
					recentBtn.classList.add('rpc-btn-recent');
					setCompactButtonText(recentBtn, '🗂️', '최근설정', '최근 입력 설정 불러오기');
				}
			}

			function readPositionMap() {
				try {
					var raw = window.localStorage.getItem(storageKey);
					if (!raw) {
						return {};
					}
					var parsed = JSON.parse(raw);
					return (parsed && typeof parsed === 'object') ? parsed : {};
				} catch (e) {
					return {};
				}
			}

			function writePositionMap(map) {
				try {
					window.localStorage.setItem(storageKey, JSON.stringify(map || {}));
				} catch (e) {}
			}

			function clampPosition(left, top) {
				var rect = primaryMenu.getBoundingClientRect();
				var maxLeft = Math.max(8, window.innerWidth - rect.width - 8);
				var maxTop = Math.max(8, window.innerHeight - rect.height - 8);
				return {
					left: Math.min(Math.max(8, left), maxLeft),
					top: Math.min(Math.max(8, top), maxTop)
				};
			}

			function applyPosition(left, top) {
				var pos = clampPosition(left, top);
				primaryMenu.style.left = pos.left + 'px';
				primaryMenu.style.top = pos.top + 'px';
			}

			function getDefaultPosition(mode) {
				var margin = 14;
				var rect = primaryMenu.getBoundingClientRect();

				if (mode === 'vertical') {
					return {
						left: Math.max(margin, window.innerWidth - rect.width - margin),
						top: Math.max(margin, Math.round((window.innerHeight - rect.height) / 2))
					};
				}

				return {
					left: Math.max(margin, Math.round((window.innerWidth - rect.width) / 2)),
					top: margin
				};
			}

			function savePositionForCurrentMode() {
				var left = parseInt(primaryMenu.style.left, 10);
				var top = parseInt(primaryMenu.style.top, 10);
				if (isNaN(left) || isNaN(top)) {
					return;
				}

				var map = readPositionMap();
				map[currentMode] = { left: left, top: top };
				writePositionMap(map);
			}

			function restorePositionForMode(mode) {
				var map = readPositionMap();
				var pos = map[mode];
				if (pos && typeof pos.left === 'number' && typeof pos.top === 'number') {
					applyPosition(pos.left, pos.top);
					return;
				}

				var defaults = getDefaultPosition(mode);
				applyPosition(defaults.left, defaults.top);
			}

			function switchMode(nextMode) {
				savePositionForCurrentMode();
				setMenuMode(nextMode);
				restorePositionForMode(currentMode);
				saveMode(currentMode);
			}

			handle.addEventListener('pointerdown', function(e) {
				if (e.button !== 0) {
					return;
				}

				dragState = {
					diffX: e.clientX - primaryMenu.getBoundingClientRect().left,
					diffY: e.clientY - primaryMenu.getBoundingClientRect().top
				};
				primaryMenu.classList.add('is-dragging');
				try { handle.setPointerCapture(e.pointerId); } catch (err) {}
				e.preventDefault();
			});

			handle.addEventListener('pointermove', function(e) {
				if (!dragState) {
					return;
				}
				applyPosition(e.clientX - dragState.diffX, e.clientY - dragState.diffY);
				e.preventDefault();
			});

			function stopDrag() {
				if (!dragState) {
					return;
				}
				dragState = null;
				primaryMenu.classList.remove('is-dragging');
				savePositionForCurrentMode();
			}

			handle.addEventListener('pointerup', stopDrag);
			handle.addEventListener('pointercancel', stopDrag);

			modeToggleBtn.addEventListener('click', function() {
				switchMode(currentMode === 'horizontal' ? 'vertical' : 'horizontal');
			});

			window.addEventListener('resize', function() {
				var currentLeft = parseInt(primaryMenu.style.left, 10);
				var currentTop = parseInt(primaryMenu.style.top, 10);
				if (isNaN(currentLeft) || isNaN(currentTop)) {
					restorePositionForMode(currentMode);
					return;
				}
				applyPosition(currentLeft, currentTop);
				savePositionForCurrentMode();
			});

			setMenuMode(readMode());
			restorePositionForMode(currentMode);
			decorateFloatingButtons();
			primaryMenu.style.visibility = '';
			clearFloatingInitMask();

			/* ── 폼 변경 감지 (dirty state) ── */
			var _formEl = document.querySelector('form[name="fitemform"]') || document.querySelector('form');
			var _isDirty = false;
			var _submitted = false;

			function _markDirty() {
				if (_submitted || _isDirty) return;
				_isDirty = true;
				primaryMenu.classList.add('rpc-floating-menu-dirty');
				if (handle) handle.setAttribute('title', (handle.getAttribute('title') || '') + ' ⚠ 저장되지 않은 변경이 있습니다');
			}

			function _clearDirty() {
				_isDirty = false;
				_submitted = true;
				primaryMenu.classList.remove('rpc-floating-menu-dirty');
			}

			window.rpcIsFormDirty = function() { return _isDirty && !_submitted; };

			if (_formEl) {
				var _inputs = _formEl.querySelectorAll(
					'input:not([type="hidden"]):not([type="submit"]):not([type="button"]):not([type="reset"]), textarea, select'
				);
				for (var _i = 0; _i < _inputs.length; _i++) {
					_inputs[_i].addEventListener('change', _markDirty);
					_inputs[_i].addEventListener('input', _markDirty);
				}
				_formEl.addEventListener('submit', _clearDirty);
			}

			window.addEventListener('beforeunload', function(e) {
				if (_isDirty && !_submitted) {
					e.preventDefault();
					return (e.returnValue = '입력 중인 내용이 저장되지 않았습니다. 페이지를 떠나시겠습니까?');
				}
			});
		}

		if (document.readyState === 'loading') {
			document.addEventListener('DOMContentLoaded', initFloatingSubmitMenu);
		} else {
			initFloatingSubmitMenu();
		}
	})();
</script>

<?php if ($w == '') { ?>
<script>
	(function() {
		var presetsRaw = <?php echo json_encode($recent_itemform_configs, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
		var presets = Array.isArray(presetsRaw) ? presetsRaw : [];
		var layer = document.getElementById('recent-config-layer');
		var modal = layer ? layer.querySelector('.recent-config-modal') : null;
		if (!layer) {
			return;
		}

		var questionEl = document.getElementById('recent-config-question');
		var selectEl = document.getElementById('recent-config-select');
		var previewEl = document.getElementById('recent-config-preview');
		var pickerEl = document.getElementById('recent-config-picker');
		var questionBtns = document.getElementById('recent-config-question-btns');
		var applyBtns = document.getElementById('recent-config-apply-btns');
		var quickBtn = document.getElementById('recent-config-quick');
		var yesBtn = document.getElementById('recent-config-yes');
		var noBtn = document.getElementById('recent-config-no');
		var openBtns = document.querySelectorAll('.js-recent-config-open');

		if (!modal || !selectEl || !previewEl || !pickerEl || !questionBtns || !applyBtns || !quickBtn || !yesBtn || !noBtn) {
			return;
		}

		function setRecentModalMode(mode) {
			if (!modal) {
				return;
			}

			modal.classList.remove('is-compact', 'is-expanded');
			if (mode === 'expanded') {
				modal.classList.add('is-expanded');
			} else {
				modal.classList.add('is-compact');
				modal.style.height = '';
			}
		}

		function resetRecentLayerState() {
			pickerEl.style.display = 'none';
			questionBtns.style.display = 'flex';
			applyBtns.style.display = 'none';
			renderPreview(getSelectedPresetIndex());
		}

		function openRecentLayer() {
			layer.style.display = 'block';
			setRecentModalMode('compact');
			resetRecentLayerState();

			if (window.innerWidth <= 768) {
				modal.style.left = '12px';
				modal.style.top = '12px';
				modal.style.transform = 'none';
				return;
			}

			modal.style.left = '50%';
			modal.style.top = '56px';
			modal.style.transform = 'translateX(-50%)';
		}

		(function bindRecentModalDrag() {
			var handle = modal.querySelector('.recent-config-title');
			if (!handle) {
				return;
			}

			var dragState = null;

			function clampModalToViewport() {
				var rect = modal.getBoundingClientRect();
				var maxLeft = Math.max(0, window.innerWidth - rect.width - 8);
				var maxTop = Math.max(0, window.innerHeight - rect.height - 8);
				var left = Math.min(Math.max(8, rect.left), maxLeft);
				var top = Math.min(Math.max(8, rect.top), maxTop);

				modal.style.left = left + 'px';
				modal.style.top = top + 'px';
				modal.style.transform = 'none';
			}

			handle.addEventListener('mousedown', function(e) {
				if (e.button !== 0) {
					return;
				}

				var tag = (e.target && e.target.tagName) ? e.target.tagName.toLowerCase() : '';
				if (tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea' || tag === 'label' || tag === 'option') {
					return;
				}

				var rect = modal.getBoundingClientRect();
				modal.style.left = rect.left + 'px';
				modal.style.top = rect.top + 'px';
				modal.style.transform = 'none';

				dragState = {
					diffX: e.clientX - rect.left,
					diffY: e.clientY - rect.top
				};

				e.preventDefault();
			});

			document.addEventListener('mousemove', function(e) {
				if (!dragState || layer.style.display !== 'block') {
					return;
				}

				var rect = modal.getBoundingClientRect();
				var nextLeft = e.clientX - dragState.diffX;
				var nextTop = e.clientY - dragState.diffY;
				var maxLeft = Math.max(0, window.innerWidth - rect.width - 8);
				var maxTop = Math.max(0, window.innerHeight - rect.height - 8);
				modal.style.left = Math.min(Math.max(8, nextLeft), maxLeft) + 'px';
				modal.style.top = Math.min(Math.max(8, nextTop), maxTop) + 'px';
			});

			document.addEventListener('mouseup', function() {
				dragState = null;
			});

			window.addEventListener('resize', function() {
				if (layer.style.display !== 'block') {
					return;
				}
				if (window.innerWidth <= 768) {
					modal.style.left = '12px';
					modal.style.top = '12px';
					modal.style.transform = 'none';
					return;
				}
				clampModalToViewport();
			});
		})();

		noBtn.addEventListener('click', function() {
			setRecentModalMode('compact');
			layer.style.display = 'none';
		});

		function getRecentNoPresetNoticeConfig() {
			if (!window.__recentNoPresetNoticeConfig) {
				window.__recentNoPresetNoticeConfig = {
					message: '불러올 최근 입력 설정이 없습니다. 먼저 상품을 1회 이상 저장해 주세요.',
					type: 'warn',
					key: 'recent-config-empty',
					cooldownMs: 1800,
					durationMs: 3200
				};
			}
			return window.__recentNoPresetNoticeConfig;
		}

		function showNoPresetToast() {
			var notice = getRecentNoPresetNoticeConfig();
			if (typeof window.showCopilotToast === 'function') {
				window.showCopilotToast(notice.message, notice.type, {
					key: notice.key,
					cooldownMs: notice.cooldownMs,
					durationMs: notice.durationMs
				});
			} else {
				alert(notice.message);
			}
		}

		if (!presets.length) {
			if (questionEl) {
				questionEl.innerHTML = '최근 저장된 VPN 설정이 없습니다.<br>기본값으로 시작합니다.';
			}
			quickBtn.style.display = 'none';
			yesBtn.style.display = 'none';
			noBtn.textContent = '확인';
		}

		function escapeHtml(value) {
			return String(value)
				.replace(/&/g, '&amp;')
				.replace(/</g, '&lt;')
				.replace(/>/g, '&gt;')
				.replace(/"/g, '&quot;')
				.replace(/'/g, '&#39;');
		}

		function toArray(fieldRef) {
			if (!fieldRef) {
				return [];
			}
			if (typeof fieldRef.length === 'number' && !fieldRef.tagName) {
				return Array.prototype.slice.call(fieldRef);
			}
			return [fieldRef];
		}

		function getFieldsByName(form, name) {
			var ref = form.elements[name];
			if (!ref && name.slice(-2) !== '[]') {
				ref = form.elements[name + '[]'];
			}
			return toArray(ref);
		}

		function triggerFieldEvents(el) {
			if (!el) {
				return;
			}
			try { el.dispatchEvent(new Event('change', { bubbles: true })); } catch (e) {}
			try { el.dispatchEvent(new Event('input', { bubbles: true })); } catch (e) {}
		}

		function markFieldApplied(el) {
			if (!el || !el.classList) {
				return;
			}

			el.classList.add('recent-applied-highlight');
			if (el.__recentAppliedTimer) {
				clearTimeout(el.__recentAppliedTimer);
			}

			el.__recentAppliedTimer = setTimeout(function() {
				el.classList.remove('recent-applied-highlight');
			}, 10000);
		}

		function renderPreview(index) {
			var preset = presets[index] || presets[0];
			if (!preset) {
				previewEl.innerHTML = '<div>표시할 값이 없습니다.</div>';
				return;
			}

			function getPresetSummaryText(presetObj) {
				if (!presetObj || typeof presetObj !== 'object') {
					return '최근 입력 설정';
				}

				var summary = String(presetObj.summary || '').trim();
				var values = (presetObj.values && typeof presetObj.values === 'object') ? presetObj.values : {};
				var itemName = String(values.__recent_item_name || values.it_name || '').trim();

				if (itemName !== '') {
					if (summary === '') {
						return itemName;
					}

					if (/^VPN분류\s*:/i.test(summary)) {
						var tail = summary.replace(/^VPN분류\s*:[^|]*/i, '').trim();
						if (tail.indexOf('|') === 0) {
							tail = tail.substring(1).trim();
						}
						return tail ? (itemName + ' | ' + tail) : itemName;
					}
				}

				return summary || '최근 입력 설정';
			}

			var presetSummaryText = getPresetSummaryText(preset);

			function toTrimmedArray(v) {
				if (typeof v === 'undefined' || v === null) {
					return [];
				}
				var arr = Array.isArray(v) ? v : [v];
				var out = [];
				for (var i = 0; i < arr.length; i++) {
					var s = String(arr[i] || '').trim();
					if (s !== '') {
						out.push(s);
					}
				}
				return out;
			}

			function normalizePreviewValues(rawValues, summaryText) {
				var values = {};
				var src = rawValues || {};
				Object.keys(src).forEach(function(k) {
					values[k] = src[k];
				});

				function pickArray(keys) {
					for (var i = 0; i < keys.length; i++) {
						var arr = toTrimmedArray(values[keys[i]]);
						if (arr.length) {
							return arr;
						}
					}
					return [];
				}

				function applyCanonicalArray(baseName, arr) {
					if (!arr.length) {
						return;
					}
					values[baseName] = arr.slice();
					values[baseName + '[]'] = arr.slice();
				}

				var remoteProgramArr = pickArray(['remoteProgram[]', 'remoteProgram']);
				var remoteIpArr = pickArray(['remoteIp[]', 'remoteIp']);
				var remoteIdArr = pickArray(['remoteId[]', 'remoteId']);
				var remotePasswordArr = pickArray(['remotePassword[]', 'remotePassword']);

				var remoteRaw = values.it_spec_remote_sw;
				if ((!remoteProgramArr.length || !remoteIpArr.length || !remoteIdArr.length || !remotePasswordArr.length) && remoteRaw) {
					var parsed = null;
					if (typeof remoteRaw === 'string') {
						try {
							parsed = JSON.parse(remoteRaw);
						} catch (e) {}
					} else if (typeof remoteRaw === 'object') {
						parsed = remoteRaw;
					}

					if (Array.isArray(parsed)) {
						if (!remoteProgramArr.length) {
							remoteProgramArr = parsed.map(function(row) { return String((row && (row.remoteProgram || row.remote_program || row.program)) || '').trim(); }).filter(Boolean);
						}
						if (!remoteIpArr.length) {
							remoteIpArr = parsed.map(function(row) { return String((row && (row.remoteIp || row.remote_ip || row.ip || row.host)) || '').trim(); }).filter(Boolean);
						}
						if (!remoteIdArr.length) {
							remoteIdArr = parsed.map(function(row) { return String((row && (row.remoteId || row.remote_id || row.id || row.account)) || '').trim(); }).filter(Boolean);
						}
						if (!remotePasswordArr.length) {
							remotePasswordArr = parsed.map(function(row) { return String((row && (row.remotePassword || row.remote_password || row.password || row.pw)) || '').trim(); }).filter(Boolean);
						}
					} else if (parsed && typeof parsed === 'object') {
						function readParsedArray(obj, keys) {
							for (var kk = 0; kk < keys.length; kk++) {
								var a = toTrimmedArray(obj[keys[kk]]);
								if (a.length) {
									return a;
								}
							}
							return [];
						}

						if (!remoteProgramArr.length) {
							remoteProgramArr = readParsedArray(parsed, ['remoteProgram[]', 'remoteProgram', 'remote_program', 'program']);
						}
						if (!remoteIpArr.length) {
							remoteIpArr = readParsedArray(parsed, ['remoteIp[]', 'remoteIp', 'remote_ip', 'ip', 'host']);
						}
						if (!remoteIdArr.length) {
							remoteIdArr = readParsedArray(parsed, ['remoteId[]', 'remoteId', 'remote_id', 'id', 'account']);
						}
						if (!remotePasswordArr.length) {
							remotePasswordArr = readParsedArray(parsed, ['remotePassword[]', 'remotePassword', 'remote_password', 'password', 'pw']);
						}
					}
				}

				if (!remoteProgramArr.length && values.it_spec_os) {
					remoteProgramArr = toTrimmedArray(values.it_spec_os);
				}

				if ((!remoteProgramArr.length || !remoteIpArr.length) && summaryText) {
					var parts = String(summaryText).split('|').map(function(p) { return p.trim(); });
					if (!remoteProgramArr.length && parts.length >= 2 && parts[1]) {
						remoteProgramArr = toTrimmedArray(parts[1]);
					}
					if (!remoteIpArr.length && parts.length >= 3 && parts[2]) {
						remoteIpArr = toTrimmedArray(parts[2]);
					}
				}

				applyCanonicalArray('remoteProgram', remoteProgramArr);
				applyCanonicalArray('remoteIp', remoteIpArr);
				applyCanonicalArray('remoteId', remoteIdArr);
				applyCanonicalArray('remotePassword', remotePasswordArr);

				return values;
			}

			function previewLabel(key) {
				var labelMap = {
					'remoteProgram': 'VPN상품구분(프로토콜)',
					'remoteProgram[]': 'VPN상품구분(프로토콜)',
					'remoteIp': '서버주소 (IP/Domain)',
					'remoteIp[]': '서버주소 (IP/Domain)',
					'remoteId': 'ID (계정)',
					'remoteId[]': 'ID (계정)',
					'remotePassword': 'PASSWORD (암호)',
					'remotePassword[]': 'PASSWORD (암호)',
					'it_is_hour_sale': '시간권 판매 허용',
					'it_1': '1일권 판매 허용',
					'it_2': '1개월권 판매 허용',
					'it_price': '이용요금(1시간 기준)',
					'it_install_price': '설치비',
					'it_10': '개통비/설치비 면제 기준시간',
					'it_buy_min_qty': '최소구매수량',
					'it_buy_max_qty': '최대구매수량',
					'it_spec_os_disp_lang': 'OS 표시 언어',
					'it_spec_cpu': 'CPU',
					'it_spec_ram': 'RAM',
					'it_spec_ram_type': 'RAM 유형',
					'it_spec_gpu': 'GPU',
					'it_spec_ssd': 'SSD',
					'it_spec_ssd_type': 'SSD 유형',
					'it_spec_hdd': 'HDD',
					'it_spec_hdd_type': 'HDD 유형',
					'it_spec_mgr_nickname': '관리컴퓨터별명',
					'it_shop_memo': '상점메모',
					'it_7': '종량제 판매 허용',
					'it_3': '연간판매허용',
					'billing_day_hours': '1일 시간 환산',
					'billing_month_hours': '1개월 시간 환산',
					'billing_year_hours': '1년 시간 환산'
				};

				if (labelMap[key]) {
					return labelMap[key];
				}

				var form = document.forms['fitemform'];
				if (form) {
					var fields = getFieldsByName(form, key);
					if (fields.length && fields[0].id) {
						var labelEl = document.querySelector('label[for="' + fields[0].id + '"]');
						if (labelEl) {
							var txt = (labelEl.textContent || '').replace(/\s+/g, ' ').trim();
							if (txt) {
								return txt;
							}
						}
					}
				}

				return key;
			}

			function isEmptyValue(v) {
				if (Array.isArray(v)) {
					for (var i = 0; i < v.length; i++) {
						if (String(v[i] || '').trim() !== '') {
							return false;
						}
					}
					return true;
				}
				return String(v || '').trim() === '';
			}

			function shouldDisplayInPreview(key, value) {
				if (!key || key.indexOf('__') === 0) {
					return false;
				}

				var allowedPreviewKeys = {
					'remoteProgram': true,
					'remoteProgram[]': true,
					'remoteIp': true,
					'remoteIp[]': true,
					'remoteId': true,
					'remoteId[]': true,
					'remotePassword': true,
					'remotePassword[]': true,
					'it_is_hour_sale': true,
					'it_1': true,
					'it_2': true,
					'it_3': true,
					'it_7': true,
					'it_price': true,
					'it_install_price': true,
					'it_10': true,
					'it_buy_min_qty': true,
					'it_buy_max_qty': true,
					'billing_day_hours': true,
					'billing_month_hours': true,
					'billing_year_hours': true,
					'it_spec_mgr_nickname': true,
					'it_shop_memo': true
				};

				if (!allowedPreviewKeys[key]) {
					return false;
				}

				if (isEmptyValue(value)) {
					return false;
				}

				return true;
			}

			var values = normalizePreviewValues(preset.values || {}, preset.summary || '');

			function canonicalPreviewKey(key) {
				return String(key || '').replace(/\[\]$/, '');
			}

			function pickCanonicalValue(canonicalKey) {
				if (typeof values[canonicalKey] !== 'undefined') {
					return values[canonicalKey];
				}
				if (typeof values[canonicalKey + '[]'] !== 'undefined') {
					return values[canonicalKey + '[]'];
				}
				return undefined;
			}

			function toPreviewText(key, v) {
				if (Array.isArray(v)) {
					var filtered = [];
					for (var ai = 0; ai < v.length; ai++) {
						var eachVal = String(v[ai] || '').trim();
						if (eachVal !== '') {
							filtered.push(eachVal);
						}
					}
					return filtered.join(' | ');
				}

				if (key === 'it_is_hour_sale' || key === 'it_1' || key === 'it_2' || key === 'it_3' || key === 'it_7') {
					var boolVal = String(v || '').trim();
					return (boolVal === '1' || boolVal.toLowerCase() === 'true' || boolVal === 'yes') ? '예' : '아니오';
				}
				if (key === 'it_10') {
					var thresholdHours = parseInt(v, 10);
					if (isNaN(thresholdHours) || thresholdHours < 0) {
						thresholdHours = 0;
					}
					var thresholdDay = Math.floor(thresholdHours / 24);
					var thresholdHour = thresholdHours % 24;
					return thresholdDay + '일 ' + thresholdHour + '시간 (' + thresholdHours + '시간)';
				}
				return String(v || '').trim();
			}

			var orderedCanonicalKeys = [
				'it_7',
				'it_is_hour_sale',
				'it_1',
				'it_2',
				'it_3',
				'it_price',
				'billing_day_hours',
				'billing_month_hours',
				'billing_year_hours',
				'it_install_price',
				'it_10',
				'it_buy_min_qty',
				'it_buy_max_qty',
				'remoteId',
				'remoteIp',
				'remotePassword',
				'remoteProgram',
				'it_spec_mgr_nickname',
				'it_shop_memo'
			];

			var rows = [];
			var rendered = {};
			var insertedGroups = {};

			function getGroupTitle(canonicalKey) {
				if (canonicalKey === 'it_price' || canonicalKey === 'billing_day_hours' || canonicalKey === 'billing_month_hours' || canonicalKey === 'billing_year_hours' || canonicalKey === 'it_install_price' || canonicalKey === 'it_10' || canonicalKey === 'it_buy_min_qty' || canonicalKey === 'it_buy_max_qty' || canonicalKey === 'it_is_hour_sale' || canonicalKey === 'it_1' || canonicalKey === 'it_2' || canonicalKey === 'it_3' || canonicalKey === 'it_7') {
					return '계약/과금';
				}
				if (canonicalKey === 'it_spec_mgr_nickname') {
					return '관리 정보';
				}
				if (canonicalKey === 'remoteProgram' || canonicalKey === 'remoteIp' || canonicalKey === 'remoteId' || canonicalKey === 'remotePassword') {
					return 'VPN 접속 정보';
				}
				if (canonicalKey === 'it_shop_memo') {
					return '메모';
				}
				return '기타 입력';
			}

			function appendPreviewRow(canonicalKey, groupTitle) {
				if (!canonicalKey || rendered[canonicalKey]) {
					return;
				}

				var raw = pickCanonicalValue(canonicalKey);
				if (typeof raw === 'undefined') {
					return;
				}

				if (!shouldDisplayInPreview(canonicalKey, raw)) {
					return;
				}

				var text = toPreviewText(canonicalKey, raw);
				if (text === '') {
					return;
				}

				var group = groupTitle || '기타 입력';
				if (!insertedGroups[group]) {
					var groupId = 'group-' + String(Object.keys(insertedGroups).length + 1);
					rows.push('<tr class="recent-config-group-row" data-group="' + groupId + '" aria-expanded="true" role="button" tabindex="0"><td colspan="2"><span class="recent-config-group-toggle" aria-hidden="true">▾</span>' + escapeHtml(group) + '</td></tr>');
					insertedGroups[group] = groupId;
				}

				rows.push('<tr class="recent-config-group-item" data-group="' + insertedGroups[group] + '"><th>' + escapeHtml(previewLabel(canonicalKey)) + '</th><td>' + escapeHtml(text) + '</td></tr>');
				rendered[canonicalKey] = true;
			}

			for (var oi = 0; oi < orderedCanonicalKeys.length; oi++) {
				appendPreviewRow(orderedCanonicalKeys[oi], getGroupTitle(orderedCanonicalKeys[oi]));
			}

			var fallbackKeys = Object.keys(values).sort();
			for (var fi = 0; fi < fallbackKeys.length; fi++) {
				var fallbackCanonical = canonicalPreviewKey(fallbackKeys[fi]);
				appendPreviewRow(fallbackCanonical, getGroupTitle(fallbackCanonical));
			}

			if (!rows.length) {
				rows.push('<tr><th>안내</th><td>표시할 사용자 입력 항목이 없습니다.</td></tr>');
			}

			previewEl.innerHTML = ''
				+ '<div style="margin-bottom:8px;"><strong>저장시각:</strong> ' + escapeHtml(preset.saved_at || '') + '</div>'
				+ '<div style="margin-bottom:8px;"><strong>요약:</strong> ' + escapeHtml(presetSummaryText) + '</div>'
				+ '<table><tbody>' + rows.join('') + '</tbody></table>';

			function toggleGroupRow(groupRow) {
				if (!groupRow) {
					return;
				}

				var groupId = groupRow.getAttribute('data-group');
				if (!groupId) {
					return;
				}

				var collapsed = groupRow.classList.toggle('is-collapsed');
				groupRow.setAttribute('aria-expanded', collapsed ? 'false' : 'true');

				var toggle = groupRow.querySelector('.recent-config-group-toggle');
				if (toggle) {
					toggle.textContent = collapsed ? '▸' : '▾';
				}

				var groupItems = previewEl.querySelectorAll('.recent-config-group-item[data-group="' + groupId + '"]');
				for (var gi = 0; gi < groupItems.length; gi++) {
					groupItems[gi].style.display = collapsed ? 'none' : '';
				}
			}

			var groupRows = previewEl.querySelectorAll('.recent-config-group-row');
			for (var gri = 0; gri < groupRows.length; gri++) {
				(function (rowEl) {
					rowEl.addEventListener('click', function () {
						toggleGroupRow(rowEl);
					});
					rowEl.addEventListener('keydown', function (evt) {
						if (evt.key === 'Enter' || evt.key === ' ') {
							evt.preventDefault();
							toggleGroupRow(rowEl);
						}
					});
				})(groupRows[gri]);
			}
		}

		function ensureVpnRowCount(form, targetLen) {
			if (!targetLen || targetLen < 2) {
				return;
			}

			var addBtn = document.getElementById('addVpnConfig');
			if (!addBtn) {
				return;
			}

			var safety = 0;
			while (safety < 30) {
				var nowCount = getFieldsByName(form, 'remoteProgram[]').length;
				if (nowCount >= targetLen) {
					break;
				}
				addBtn.click();
				safety++;
			}
		}

		function applyValueToFields(fields, value) {
			if (!fields.length) {
				return;
			}

			if (Array.isArray(value)) {
				for (var i = 0; i < fields.length; i++) {
					var el = fields[i];
					var type = (el.type || '').toLowerCase();
					if (type === 'checkbox' || type === 'radio') {
						el.checked = value.indexOf(el.value) > -1;
					} else {
						el.value = (typeof value[i] !== 'undefined') ? value[i] : '';
					}
					triggerFieldEvents(el);
					markFieldApplied(el);
				}
				return;
			}

			for (var j = 0; j < fields.length; j++) {
				var f = fields[j];
				var t = (f.type || '').toLowerCase();
				if (t === 'checkbox') {
					if (String(value) === '1' || String(value) === String(f.value)) {
						f.checked = true;
					} else if (fields.length === 1) {
						f.checked = false;
					}
				} else if (t === 'radio') {
					f.checked = (String(f.value) === String(value));
				} else {
					f.value = value;
				}
				triggerFieldEvents(f);
				markFieldApplied(f);
			}
		}

		function applyPreset(index) {
			var preset = presets[index];
			if (!preset || !preset.values) {
				return;
			}

			var form = document.forms['fitemform'];
			if (!form) {
				return;
			}

			var values = preset.values;
			var richEditorKeys = {
				'it_explan': true,
				'it_mobile_explan': true,
				'pt_explan': true,
				'pt_mobile_explan': true,
				'it_head_html': true,
				'it_tail_html': true,
				'it_mobile_head_html': true,
				'it_mobile_tail_html': true
			};

			function applyRichEditorValue(name, value) {
				var fields = getFieldsByName(form, name);
				if (!fields.length) {
					return;
				}

				var html = (typeof value === 'undefined' || value === null) ? '' : String(value);
				applyValueToFields(fields, html);

				try {
					if (window.oEditors && oEditors.getById && oEditors.getById[name] && typeof oEditors.getById[name].exec === 'function') {
						oEditors.getById[name].exec('SET_IR', [html]);
					}
				} catch (e1) {}

				try {
					if (window.tinymce && typeof tinymce.get === 'function') {
						var tm = tinymce.get(name);
						if (tm && typeof tm.setContent === 'function') {
							tm.setContent(html);
						}
					}
				} catch (e2) {}

				try {
					if (window.CKEDITOR && CKEDITOR.instances && CKEDITOR.instances[name] && typeof CKEDITOR.instances[name].setData === 'function') {
						CKEDITOR.instances[name].setData(html);
					}
				} catch (e3) {}
			}

			function toBoolFlag(v) {
				var s = String(v || '').trim().toLowerCase();
				return (s === '1' || s === 'true' || s === 'yes' || s === 'on');
			}

			function syncSalesPeriodCheckboxesFromValues(appliedValues) {
				var map = [
					{ valueKey: 'it_7', checkboxId: 'chk_sell_usage' },
					{ valueKey: 'it_is_hour_sale', checkboxId: 'chk_sell_hour' },
					{ valueKey: 'it_1', checkboxId: 'chk_sell_day' },
					{ valueKey: 'it_2', checkboxId: 'chk_sell_month' },
					{ valueKey: 'it_3', checkboxId: 'chk_sell_year' }
				];

				for (var mi = 0; mi < map.length; mi++) {
					var conf = map[mi];
					if (typeof appliedValues[conf.valueKey] === 'undefined') {
						continue;
					}

					var box = document.getElementById(conf.checkboxId);
					if (!box) {
						continue;
					}

					box.checked = toBoolFlag(appliedValues[conf.valueKey]);
					triggerFieldEvents(box);
					markFieldApplied(box);
				}
			}

			var remoteLen = 0;
			['remoteProgram[]', 'remoteProgram', 'remoteIp[]', 'remoteIp', 'remoteId[]', 'remoteId', 'remotePassword[]', 'remotePassword'].forEach(function(k) {
				if (Array.isArray(values[k]) && values[k].length > remoteLen) {
					remoteLen = values[k].length;
				}
			});
			if (remoteLen > 0) {
				ensureVpnRowCount(form, remoteLen);
			}

			Object.keys(values).forEach(function(name) {
				if (name === 'it_id' || name === 'it_name' || name.indexOf('__') === 0) {
					return;
				}
				if (richEditorKeys[name]) {
					applyRichEditorValue(name, values[name]);
					return;
				}
				var fields = getFieldsByName(form, name);
				applyValueToFields(fields, values[name]);
			});

			if (typeof values.it_10 !== 'undefined') {
				var it10Hours = parseInt(values.it_10, 10);
				if (!isNaN(it10Hours) && it10Hours >= 0) {
					var dayEl = document.getElementById('it_10_day');
					var hourEl = document.getElementById('it_10_hour');
					if (dayEl && hourEl) {
						var it10Day = Math.floor(it10Hours / 24);
						var it10Hour = it10Hours % 24;
						dayEl.value = String(it10Day);
						hourEl.value = String(it10Hour);
						triggerFieldEvents(dayEl);
						triggerFieldEvents(hourEl);
						markFieldApplied(dayEl);
						markFieldApplied(hourEl);
					}
				}
			}

			syncSalesPeriodCheckboxesFromValues(values);

			showCopilotToast('선택한 최근 설정값을 적용했습니다. (상품코드/상품명 제외)', 'success');
		}

		for (var i = 0; i < presets.length; i++) {
			var p = presets[i];
			var pValues = (p && p.values && typeof p.values === 'object') ? p.values : {};
			var pSummary = String(p.summary || '').trim();
			var pItemName = String(pValues.__recent_item_name || pValues.it_name || '').trim();
			if (pItemName !== '' && /^VPN분류\s*:/i.test(pSummary)) {
				var pTail = pSummary.replace(/^VPN분류\s*:[^|]*/i, '').trim();
				if (pTail.indexOf('|') === 0) {
					pTail = pTail.substring(1).trim();
				}
				pSummary = pTail ? (pItemName + ' | ' + pTail) : pItemName;
			} else if (pSummary === '' && pItemName !== '') {
				pSummary = pItemName;
			}

			var opt = document.createElement('option');
			opt.value = String(i);
			opt.text = '[' + (p.saved_at || '-') + '] ' + (pSummary || '최근 입력 설정');
			selectEl.appendChild(opt);
		}

		function getSelectedPresetIndex() {
			var idx = parseInt(selectEl.value, 10);
			if (!isNaN(idx) && idx >= 0 && idx < presets.length) {
				return idx;
			}
			if (typeof selectEl.selectedIndex === 'number' && selectEl.selectedIndex >= 0) {
				return selectEl.selectedIndex;
			}
			return 0;
		}

		if (presets.length) {
			selectEl.value = '0';
		}

		renderPreview(getSelectedPresetIndex());

		yesBtn.addEventListener('click', function() {
			renderPreview(getSelectedPresetIndex());
			pickerEl.style.display = 'block';
			questionBtns.style.display = 'none';
			applyBtns.style.display = 'flex';
			setRecentModalMode('expanded');
		});

		quickBtn.addEventListener('click', function() {
			applyPreset(0);
			setRecentModalMode('compact');
			layer.style.display = 'none';
		});

		document.getElementById('recent-config-cancel').addEventListener('click', function() {
			setRecentModalMode('compact');
			layer.style.display = 'none';
		});

		document.getElementById('recent-config-apply').addEventListener('click', function() {
			var idx = parseInt(selectEl.value, 10) || 0;
			applyPreset(idx);
			setRecentModalMode('compact');
			layer.style.display = 'none';
		});

		selectEl.addEventListener('change', function() {
			renderPreview(parseInt(this.value, 10) || 0);
		});

		if (openBtns && openBtns.length) {
			for (var obi = 0; obi < openBtns.length; obi++) {
				openBtns[obi].addEventListener('click', function() {
					if (!presets.length) {
						showNoPresetToast();
						return;
					}
					openRecentLayer();
				});
			}
		}
	})();
</script>
<?php } ?>

<script>
var f = document.fitemform;

<?php if ($w == 'u') { ?>
$(".banner_or_img").addClass("sit_wimg");
$(function() {
    $(".sit_wimg_view").bind("click", function() {
        var sit_wimg_id = $(this).attr("id").split("_");
        var $img_display = $("#"+sit_wimg_id[1]);

        $img_display.toggle();

        if($img_display.is(":visible")) {
            $(this).text($(this).text().replace("확인", "닫기"));
        } else {
            $(this).text($(this).text().replace("닫기", "확인"));
        }

        var $img = $("#"+sit_wimg_id[1]).children("img");
        var width = $img.width();
        var height = $img.height();
        if(width > 700) {
            var img_width = 700;
            var img_height = Math.round((img_width * height) / width);

            $img.width(img_width).height(img_height);
        }
    });
    $(".sit_wimg_close").bind("click", function() {
        var $img_display = $(this).parents(".banner_or_img");
        var id = $img_display.attr("id");
        $img_display.toggle();
        var $button = $("#it_"+id+"_view");
        $button.text($button.text().replace("닫기", "확인"));
    });
});
<?php } ?>

function codedupcheck(id)
{
    if (!id) {
        alert('상품코드를 입력하십시오.');
        f.it_id.focus();
        return;
    }

    var it_id = id.replace(/[A-Za-z0-9\-_]/g, "");
    if(it_id.length > 0) {
        alert("상품코드는 영문자, 숫자, -, _ 만 사용할 수 있습니다.");
        return false;
    }

    $.post(
        "./codedupcheck.php",
        { it_id: id },
        function(data) {
            if(data.name) {
                alert("코드 '"+data.code+"' 는 '".data.name+"' (으)로 이미 등록되어 있으므로\n\n사용하실 수 없습니다.");
                return false;
            } else {
                alert("'"+data.code+"' 은(는) 등록된 코드가 없으므로 사용하실 수 있습니다.");
                document.fitemform.codedup.value = '';
            }
        }, "json"
    );
}

function fitemformcheck(f)
{
	function syncEditorContentBeforeSnapshot() {
		var editorIds = [
			'it_explan',
			'it_mobile_explan',
			'pt_explan',
			'pt_mobile_explan',
			'it_head_html',
			'it_tail_html',
			'it_mobile_head_html',
			'it_mobile_tail_html'
		];

		for (var i = 0; i < editorIds.length; i++) {
			var editorId = editorIds[i];
			var textarea = document.getElementById(editorId);
			if (!textarea) {
				continue;
			}

			try {
				if (window.oEditors && oEditors.getById && oEditors.getById[editorId] && typeof oEditors.getById[editorId].exec === 'function') {
					oEditors.getById[editorId].exec('UPDATE_CONTENTS_FIELD', []);
				}
			} catch (e1) {}

			try {
				if (window.tinymce && typeof tinymce.get === 'function') {
					var tm = tinymce.get(editorId);
					if (tm && typeof tm.getContent === 'function') {
						textarea.value = tm.getContent();
					}
				}
			} catch (e2) {}

			try {
				if (window.CKEDITOR && CKEDITOR.instances && CKEDITOR.instances[editorId] && typeof CKEDITOR.instances[editorId].getData === 'function') {
					textarea.value = CKEDITOR.instances[editorId].getData();
				}
			} catch (e3) {}
		}
	}

	function collectRecentFormState(form) {
		syncEditorContentBeforeSnapshot();

		var state = {};
		if (!form || !form.elements) {
			return state;
		}

		var processed = {};
		for (var i = 0; i < form.elements.length; i++) {
			var el = form.elements[i];
			if (!el || !el.name) {
				continue;
			}

			var name = el.name;
			if (processed[name]) {
				continue;
			}
			processed[name] = true;

			if (name === 'it_id' || name === 'it_name' || name === '__recent_form_state') {
				continue;
			}

			var refs = form.elements[name];
			var fields = [];
			if (refs && typeof refs.length === 'number' && !refs.tagName) {
				for (var r = 0; r < refs.length; r++) {
					fields.push(refs[r]);
				}
			} else if (refs) {
				fields.push(refs);
			}

			if (!fields.length) {
				continue;
			}

			var first = fields[0];
			var type = (first.type || '').toLowerCase();

			if (type === 'radio') {
				var selected = '';
				for (var rr = 0; rr < fields.length; rr++) {
					if (fields[rr].checked) {
						selected = fields[rr].value;
						break;
					}
				}
				state[name] = selected;
				continue;
			}

			if (type === 'checkbox') {
				if (fields.length === 1) {
					state[name] = first.checked ? (first.value || '1') : '';
				} else {
					var checkedVals = [];
					for (var cc = 0; cc < fields.length; cc++) {
						if (fields[cc].checked) {
							checkedVals.push(fields[cc].value);
						}
					}
					state[name] = checkedVals;
				}
				continue;
			}

			if (first.tagName && first.tagName.toLowerCase() === 'select' && first.multiple) {
				var selectedVals = [];
				for (var s = 0; s < first.options.length; s++) {
					if (first.options[s].selected) {
						selectedVals.push(first.options[s].value);
					}
				}
				state[name] = selectedVals;
				continue;
			}

			state[name] = first.value;
		}

		return state;
	}

	var defaultOwnerId = <?php echo json_encode($member['mb_id']); ?>;
	var ownerFromSpec = $.trim(($('input[name="it_spec_partner_id"]').val() || '').toString());
	var ownerFromPt = $.trim(($('input[name="pt_id"]').val() || '').toString());
	var ownerFinal = ownerFromSpec || ownerFromPt || defaultOwnerId;
	$('input[name="it_spec_partner_id"]').val(ownerFinal);
	$('input[name="pt_id"]').val(ownerFinal);

	try {
		var stateData = collectRecentFormState(f);
		var stateJson = JSON.stringify(stateData || {});
		var stateEl = document.getElementById('__recent_form_state');
		if (!stateEl) {
			stateEl = document.createElement('input');
			stateEl.type = 'hidden';
			stateEl.name = '__recent_form_state';
			stateEl.id = '__recent_form_state';
			f.appendChild(stateEl);
		}
		stateEl.value = stateJson;
	} catch (e) {}

    if (!f.ca_id.value) {
        //alert("기본분류를 선택하십시오.");
		alert("VPN 종류를 선택하십시오.");
        f.ca_id.focus();
        return false;
    }

    if (f.w.value == "") {
        var error = "";
        $.ajax({
            url: "./ajax.it_id.php",
            type: "POST",
            data: {
                "it_id": f.it_id.value
            },
            dataType: "json",
            async: false,
            cache: false,
            success: function(data, textStatus) {
                error = data.error;
            }
        });

        if (error) {
            alert(error);
            return false;
        }
    }

    if(f.it_point_type.value == "1" || f.it_point_type.value == "2") {
        var point = parseInt(f.it_point.value);
        if(point > 99) {
            alert("포인트 비율을 0과 99 사이의 값으로 입력해 주십시오.");
            return false;
        }
    }

    if(parseInt(f.it_sc_type.value) > 1) {
        if(!f.it_sc_price.value || f.it_sc_price.value == "0") {
            alert("기본배송비를 입력해 주십시오.");
            return false;
        }

        if(f.it_sc_type.value == "2" && (!f.it_sc_minimum.value || f.it_sc_minimum.value == "0")) {
            alert("배송비 상세조건의 주문금액을 입력해 주십시오.");
            return false;
        }

        if(f.it_sc_type.value == "4" && (!f.it_sc_qty.value || f.it_sc_qty.value == "0")) {
            alert("배송비 상세조건의 주문수량을 입력해 주십시오.");
            return false;
        }
    }

    // 관련상품처리
    var item = new Array();
    var re_item = it_id = "";

    $("#reg_relation input[name='re_it_id[]']").each(function() {
        it_id = $(this).val();
        if(it_id == "")
            return true;

        item.push(it_id);
    });

    if(item.length > 0)
        re_item = item.join();

    $("input[name=it_list]").val(re_item);

	<?php if($is_auth) { // 관리자 일 때 ?>
	// 이벤트처리
	var evnt = new Array();
	var ev = ev_id = "";

	$("#reg_event_list input[name='ev_id[]']").each(function() {
		ev_id = $(this).val();
		if(ev_id == "")
			return true;

		evnt.push(ev_id);
	});

	if(evnt.length > 0)
		ev = evnt.join();

	$("input[name=ev_list]").val(ev);
	<?php } // 관리자 끝 ?>

	function ensureEditorFieldRef(form, id) {
		if (!form || !id) {
			return;
		}
		if (typeof form[id] !== 'undefined' && form[id] !== null) {
			return;
		}
		var el = document.getElementById(id);
		if (el) {
			form[id] = el;
			return;
		}
		form[id] = { value: '' };
	}

	ensureEditorFieldRef(f, 'it_explan');
	ensureEditorFieldRef(f, 'pt_explan');
	ensureEditorFieldRef(f, 'it_mobile_explan');
	ensureEditorFieldRef(f, 'pt_mobile_explan');
	ensureEditorFieldRef(f, 'it_head_html');
	ensureEditorFieldRef(f, 'it_tail_html');
	ensureEditorFieldRef(f, 'it_mobile_head_html');
	ensureEditorFieldRef(f, 'it_mobile_tail_html');

	// get_editor_js()는 에디터 인스턴스(oEditors.getById)가 없는 환경에서
	// "Cannot read properties of undefined (reading 'it_explan')" 예외를 유발할 수 있으므로,
	// 위의 syncEditorContentBeforeSnapshot()로만 제출 직전 값을 동기화한다.
	try {
		syncEditorContentBeforeSnapshot();
	} catch (e_sync) {}



	// 로딩 효과 표시
	$("#loading-overlay_enter").css("display", "block");

    return true;
}

function categorychange(f)
{
	var _ca_stock_qty = (typeof window.ca_stock_qty !== 'undefined' && window.ca_stock_qty) ? window.ca_stock_qty : {};
	var _ca_sell_email = (typeof window.ca_sell_email !== 'undefined' && window.ca_sell_email) ? window.ca_sell_email : {};

	if (!f || !f.ca_id) {
		return;
	}

    var idx = f.ca_id.value;

    if (f.w.value == "" && idx)
    {
        //f.it_use.checked = ca_use[idx] ? true : false;
		if (f.it_stock_qty && typeof _ca_stock_qty[idx] !== 'undefined') {
			f.it_stock_qty.value = _ca_stock_qty[idx];
		}
		<?php if($is_auth) { // 관리자 일 때 ?>
		if (f.it_sell_email && typeof _ca_sell_email[idx] !== 'undefined') {
        	f.it_sell_email.value = _ca_sell_email[idx];
		}
		<?php } ?>
    }
}

if (document.fitemform) {
	categorychange(document.fitemform);
}

</script>


