<?php
if (!defined('_GNUBOARD_')) exit; // 개별 페이지 접근 불가

if(!function_exists('vpn_grade_badge_html')) {
    function vpn_grade_badge_html($grade) {
        $grade = strtoupper(trim((string)$grade));
        if($grade === '') return '';
        $c = array('BASIC'=>'#6c757d','PLUS'=>'#0d6efd','PRO'=>'#198754','ULTRA'=>'#6f42c1','MAX'=>'#dc3545');
        $bg = isset($c[$grade]) ? $c[$grade] : '#555';
        return '<span class="vpn-grade-badge" style="display:inline-block;padding:1px 8px;border-radius:0;font-size:11px;font-weight:700;letter-spacing:.4px;background:'.htmlspecialchars($bg,ENT_QUOTES).';color:#fff;margin-right:4px;vertical-align:middle;">'.htmlspecialchars($grade,ENT_QUOTES).'</span>';
    }
}
if(!function_exists('vpn_category_badge_html')) {
    function vpn_category_badge_html($spec_os) {
        $parts = explode('-', trim((string)$spec_os));
        $cat = strtoupper(trim($parts[0]));
        if($cat === '') return '';
        return '<span class="vpn-category-badge" style="display:inline-block;padding:1px 8px;border-radius:0;font-size:11px;font-weight:700;letter-spacing:.4px;background:#0891b2;color:#fff;margin-right:4px;vertical-align:middle;">'.htmlspecialchars($cat,ENT_QUOTES).'</span>';
    }
}

// add_stylesheet('css 구문', 출력순서); 숫자가 작을 수록 먼저 출력됨
add_stylesheet('<link rel="stylesheet" href="'.$skin_url.'/style.css" media="screen">', 0);

// 목록헤드
if(isset($wset['ivhead']) && $wset['ivhead']) {
	add_stylesheet('<link rel="stylesheet" href="'.G5_CSS_URL.'/head/'.$wset['ivhead'].'.css" media="screen">', 0);
	$head_class = 'list-head';
} else {
	$head_class = (isset($wset['ivcolor']) && $wset['ivcolor']) ? 'tr-head border-'.$wset['ivcolor'] : 'tr-head border-black';
}
$_skin_dark = (!empty($_COOKIE['vpnlink_dark']) && $_COOKIE['vpnlink_dark'] === '1');
$_dark_tbl_style = $_skin_dark ? ' style="background-color:#1e1e24;"' : '';
$_dark_th_style  = $_skin_dark ? ' style="background-color:#1e1e24;color:#9ca3af;"' : '';
$_dark_td_style  = $_skin_dark ? ' style="background-color:#18181e;color:#c4c4cc;"' : '';

// 헤더 출력
if($header_skin)
	include_once('./header.php');

if (!function_exists('apms_display_point_plain')) {
	function apms_display_point_plain($point) {
		return number_format((float)$point);
	}
}

if (!function_exists('apms_remote_program_official_url')) {
	function apms_remote_program_official_url($program_name, $program_type = 'all') {
		if (function_exists('oi_remote_program_official_url')) {
			return oi_remote_program_official_url($program_name, $program_type);
		}

		$name = trim((string)$program_name);
		$lower = strtolower($name);
		if ($lower === '') {
			return '';
		}

		$map = array(
			'rpcviewer' => 'https://www.rpcviewer.com',
			'teamviewer' => 'https://www.teamviewer.com',
			'anydesk' => 'https://anydesk.com',
			'parsec' => 'https://parsec.app',
			'rustdesk' => 'https://rustdesk.com',
			'chrome remote desktop' => 'https://remotedesktop.google.com',
			'remote desktop' => 'https://remotedesktop.google.com',
			'vnc' => 'https://www.realvnc.com',
			'radmin' => 'https://www.radmin.com'
		);

		foreach ($map as $key => $url) {
			if (strpos($lower, $key) !== false) {
				return $url;
			}
		}

		return 'https://www.google.com/search?q=' . rawurlencode($name . ' official site');
	}
}

if (!function_exists('apms_remote_program_download_urls')) {
	function apms_remote_program_download_urls($program_name, $program_type = 'all') {
		if (function_exists('oi_remote_program_download_urls')) {
			return oi_remote_program_download_urls($program_name, $program_type);
		}

		return array(
			'windows' => '',
			'macos' => '',
			'linux' => '',
			'android' => '',
			'ios' => ''
		);
	}
}

?>

<div class="modal fade" id="statusModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
				<h4 class="modal-title" id="myModalLabel">상태설명</h4>
			</div>
			<div class="modal-body">
				<ul>
				<li>주문 : 주문이 접수되었습니다.</li>
				<li>입금 : 입금(결제)이 완료 되었습니다.</li>
				<?php /* ?>
				<li>준비 : 상품 준비 중입니다.</li>
				<li>배송 : 상품 배송 중입니다.</li>
				<li>완료 : 상품 배송이 완료 되었습니다.</li>
				<?php */ ?>
				<li>완료 : 주문완료 되었습니다. (온라인 상품인 경우 원격접속가능)</li>
				</ul>
				<br>
				<p class="text-center">
					<button type="button" class="btn btn-black btn-sm" data-dismiss="modal">닫기</button>
				</p>
			</div>
		</div>
	</div>
</div>


<div class="well well-sm">
	<span class="print-hide cursor pull-right hidden-xs" data-toggle="modal" data-target="#statusModal">
		<i class="fa fa-info-circle"></i> 상태설명
	</span>
	<i class="fa fa-shopping-cart fa-lg"></i> 주문번호 : <strong><?php echo $od_id; ?></strong>
</div>

<div class="text-muted" style="margin:0 0 8px; font-size:12px; text-align:right;">※ 본 화면의 금액 단위는 Point입니다.</div>

<style>
	.delivery-info { margin:0px; padding:0px; padding-left:15px; line-height:22px; white-space:nowrap; }
	.extend-layer-box { max-width:100%; margin:0 auto; padding:16px 14px 14px; border-radius:10px; background:#ffffff; border:1px solid #e5e7eb; }
	.extend-current-end { width:100%; margin-bottom:6px; font-size:1.1rem; }
	.extend-fee-guide { margin-bottom:6px; font-size:12px; color:#555; line-height:1.35; text-align:left; }
	.extend-pricing-row { display:flex; align-items:center; gap:6px; width:100%; }
	.extend-unit-select { flex:1 1 auto; min-width:0; }
	.extend-count-wrap { display:flex; align-items:center; gap:4px; flex:0 0 auto; }
	.extend-count-input { width:72px; text-align:center; }
	.extend-count-suffix { min-width:42px; text-align:center; border:1px solid #ccc; background:#f8f8f8; height:34px; line-height:32px; padding:0 8px; }
	.extend-submit-row { margin-top:8px; text-align:right; width:100%; }
	.extend-summary { margin-top:6px; font-size:13px; text-align:right; font-weight:700; }
	.btn-extend-expired {
		background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
		border-color: #b91c1c;
		color: #fff !important;
		font-weight: 700;
		box-shadow: 0 6px 16px rgba(185, 28, 28, 0.28);
	}
	.btn-extend-expired:hover,
	.btn-extend-expired:focus {
		background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
		border-color: #991b1b;
		color: #fff !important;
	}
	.extend-expired-hint {
		margin-top: 8px;
		font-size: 11px;
		line-height: 1.3;
		color: #b91c1c;
		font-weight: 700;
		display: block;
		max-width: 210px;
		margin-left: auto;
		margin-right: auto;
		text-align: center;
		white-space: normal;
		word-break: keep-all;
	}
	.extend-popup-backdrop {
		position: fixed;
		inset: 0;
		background: rgba(17, 24, 39, 0.45);
		z-index: 1050;
		display: none;
	}
	.extend-popup-window {
		position: fixed;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		width: 520px;
		height: 390px;
		min-width: 420px;
		min-height: 300px;
		max-width: 92vw;
		max-height: 88vh;
		background: #f7f8fb;
		border: 1px solid #d7dbe3;
		border-radius: 12px;
		box-shadow: 0 18px 45px rgba(17, 24, 39, 0.28);
		z-index: 1060;
		display: none;
		overflow: hidden;
	}
	.extend-popup-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 11px 14px;
		color: #fff;
		background: linear-gradient(135deg, #111827 0%, #2d3748 100%);
		cursor: move;
		user-select: none;
	}
	.extend-popup-title {
		font-size: 14px;
		font-weight: 700;
		line-height: 1.35;
		padding-right: 10px;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	.extend-popup-close {
		border: 0;
		background: rgba(255,255,255,0.14);
		color: #fff;
		width: 30px;
		height: 30px;
		border-radius: 8px;
		font-size: 18px;
		line-height: 30px;
		padding: 0;
	}
	.extend-popup-close:hover { background: rgba(255,255,255,0.24); }
	.extend-popup-body {
		height: calc(100% - 52px);
		overflow: auto;
		padding: 14px;
	}
	.extend-popup-resizer {
		position: absolute;
		right: 6px;
		bottom: 6px;
		width: 16px;
		height: 16px;
		cursor: nwse-resize;
		background: linear-gradient(135deg, transparent 0%, transparent 45%, #96a0b5 46%, #96a0b5 54%, transparent 55%, transparent 100%);
	}
	.refund-popup-window {
		height: 440px;
		min-height: 320px;
	}
	@media (max-width: 640px) {
		.extend-popup-window {
			width: 94vw;
			height: 78vh;
			min-width: 0;
			min-height: 0;
		}
	}
	.extend-confirm-backdrop {
		position: fixed;
		inset: 0;
		background: rgba(17, 24, 39, 0.68);
		backdrop-filter: blur(2px);
		z-index: 2000;
		display: none;
	}
	.extend-confirm-modal {
		position: fixed;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		width: 560px;
		max-width: 92vw;
		background: linear-gradient(180deg, #ffffff 0%, #fafafa 100%);
		border-radius: 18px;
		border: 1px solid #d5d9e0;
		box-shadow: 0 30px 70px rgba(2, 6, 23, 0.42);
		z-index: 2010;
		display: none;
		overflow: hidden;
	}
	.extend-confirm-head {
		display:flex;
		align-items:center;
		gap:10px;
		padding: 15px 20px;
		font-size: 20px;
		font-weight: 700;
		color: #0f172a;
		border-bottom: 1px solid #e9edf5;
		background: linear-gradient(135deg, #f8f9fb 0%, #f1f3f6 100%);
	}
	.extend-confirm-icon {
		display:inline-flex;
		align-items:center;
		justify-content:center;
		width:30px;
		height:30px;
		border-radius:999px;
		background:#1f2937;
		color:#fff;
		font-size:14px;
		font-weight:700;
		box-shadow:0 6px 14px rgba(15,23,42,0.35);
	}
	.extend-confirm-body {
		padding: 20px;
		font-size: 16px;
		line-height: 1.7;
		color: #273142;
	}
	.extend-confirm-body .warn { margin-bottom: 10px; font-weight: 800; font-size: 17px; letter-spacing:-0.2px; }
	.extend-confirm-sub { margin-bottom:12px; color:#4b5563; }
	.extend-confirm-list { margin: 0; padding-left: 0; list-style: none; }
	.extend-confirm-list li {
		margin: 8px 0;
		padding: 8px 10px;
		background: #f5f6f8;
		border: 1px solid #e1e4ea;
		border-radius: 10px;
	}
	.extend-confirm-actions {
		display: flex;
		justify-content: flex-end;
		gap: 10px;
		padding: 14px 20px 20px;
		border-top: 1px solid #edf0f5;
		background: #fcfdff;
	}
	.extend-confirm-btn {
		min-width: 116px;
		height: 44px;
		border-radius: 999px;
		font-size: 16px;
		font-weight: 700;
		border: 1px solid #d5dbe7;
		background: #fff;
		color: #334155;
		padding: 0 18px;
	}
	.extend-confirm-btn.primary {
		background: linear-gradient(135deg, #1f2937 0%, #111827 100%);
		border-color: #1f2937;
		color: #fff;
		box-shadow: 0 8px 18px rgba(17, 24, 39, 0.34);
	}
	.extend-confirm-btn.primary:hover {
		background: linear-gradient(135deg, #111827 0%, #0b1220 100%);
		border-color: #111827;
		color: #fff;
	}
	.extend-confirm-btn:hover:not(.primary) { background:#f3f4f6; }
	.contract-status-badge {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		min-width: 86px;
		height: 28px;
		padding: 0 12px;
		border-radius: 999px;
		font-size: 12px;
		font-weight: 700;
		letter-spacing: 0.1px;
		border: 1px solid transparent;
	}
	.contract-status-badge.active {
		background: #ecfdf5;
		color: #065f46;
		border-color: #a7f3d0;
	}
	.contract-status-badge.expired {
		background: #fef2f2;
		color: #b91c1c;
		border-color: #fecaca;
	}
	.refund-point-cell {
		font-variant-numeric: tabular-nums;
		font-feature-settings: "tnum" 1, "lnum" 1;
		letter-spacing: 0.1px;
		white-space: nowrap;
	}
	.refund-amount-note {
		display: block;
		margin-top: 8px;
		padding: 0 2px;
		font-size: 11px;
		color: #6b7280;
		line-height: 1.5;
	}
	.refund-calc-guide {
		margin-top: 10px;
		padding: 10px 12px;
		border: 1px solid #dbe2ea;
		background: #f8fafc;
		border-radius: 8px;
		font-size: 12px;
		line-height: 1.55;
		color: #334155;
	}
	.refund-calc-guide strong {
		color: #0f172a;
	}
	.refund-calc-guide .formula-current {
		display: block;
		margin-top: 4px;
		color: #475569;
	}
	.refund-fee-head {
		display: inline-flex;
		align-items: center;
		gap: 6px;
	}
	.refund-calc-toggle {
		width: 18px;
		height: 18px;
		line-height: 18px;
		padding: 0;
		border: 0;
		background: transparent;
		color: #475569;
		cursor: pointer;
		font-size: 15px;
	}
	.refund-calc-toggle:hover {
		color: #111827;
	}
	.refund-calc-guide {
		display: none;
	}
	.refund-calc-modal-body {
		padding: 18px 20px;
		font-size: 14px;
		line-height: 1.65;
		color: #273142;
	}
	.refund-calc-modal-body .refund-calc-guide {
		display: block;
		margin: 0;
	}
	.refund-calc-table {
		width: 100%;
		border-collapse: collapse;
		margin-top: 8px;
	}
	.refund-calc-table td {
		padding: 3px 0;
		vertical-align: top;
	}
	.refund-calc-table .rct-label {
		color: #475569;
		white-space: nowrap;
		padding-right: 12px;
		width: 1%;
	}
	.refund-calc-table .rct-value {
		color: #1e293b;
		text-align: right;
		font-variant-numeric: tabular-nums;
	}
	.refund-calc-table .rct-result-row td {
		border-top: 1px solid #cbd5e1;
		padding-top: 6px;
		font-weight: 700;
		color: #0f172a;
	}
	.refund-calc-table .rct-ratio-row td {
		padding-top: 4px;
		padding-bottom: 4px;
		color: #64748b;
		font-size: 0.92em;
	}
	/* ── 다크모드 ── */
	[data-site-theme="dark"] .extend-layer-box {
		background: #1e1e24 !important;
		border-color: #3a3a42 !important;
	}
	[data-site-theme="dark"] .extend-count-suffix {
		background: #252528 !important;
		border-color: #4a4a52 !important;
		color: #c4c4cc !important;
	}
	[data-site-theme="dark"] .extend-fee-guide {
		color: #9ca3af !important;
	}
	[data-site-theme="dark"] .extend-popup-window {
		background: #1e1e24 !important;
		border-color: #3a3a42 !important;
	}
	[data-site-theme="dark"] .extend-confirm-modal {
		background: #1e1e24 !important;
		border-color: #3a3a42 !important;
	}
	[data-site-theme="dark"] .extend-confirm-head {
		background: #252528 !important;
		border-color: #3a3a42 !important;
		color: #e4e4e7 !important;
	}
	[data-site-theme="dark"] .extend-confirm-body {
		color: #c4c4cc !important;
	}
	[data-site-theme="dark"] .extend-confirm-body .warn {
		color: #e4e4e7 !important;
	}
	[data-site-theme="dark"] .extend-confirm-sub {
		color: #9ca3af !important;
	}
	[data-site-theme="dark"] .extend-confirm-list li {
		background: #252528 !important;
		border-color: #3a3a42 !important;
		color: #c4c4cc !important;
	}
	[data-site-theme="dark"] .extend-confirm-actions {
		background: #1e1e24 !important;
		border-color: #3a3a42 !important;
	}
	[data-site-theme="dark"] .extend-confirm-btn {
		background: #252528 !important;
		border-color: #4a4a52 !important;
		color: #c4c4cc !important;
	}
	[data-site-theme="dark"] .extend-confirm-btn.primary {
		background: linear-gradient(135deg, #2d3a4a 0%, #1a2638 100%) !important;
		border-color: #3a5a78 !important;
		color: #e4e4e7 !important;
	}
	[data-site-theme="dark"] .refund-calc-table .rct-result-row td {
		color: #e4e4e7 !important;
		border-color: #3a3a42 !important;
	}
	[data-site-theme="dark"] .refund-calc-table .rct-ratio-row td {
		color: #9ca3af !important;
	}
	/* ── #orderinquiryview 다크모드 ── */
	[data-site-theme="dark"] #orderinquiryview,
	[data-site-theme="dark"] #orderinquiryview table {
		background-color: #18181e !important;
		border-color: #454552 !important;
	}
	[data-site-theme="dark"] #orderinquiryview tr {
		background-color: #18181e !important;
	}
	[data-site-theme="dark"] #orderinquiryview th,
	[data-site-theme="dark"] #orderinquiryview td {
		border-top-color: #454552 !important;
		border-bottom-color: #454552 !important;
		background-color: #18181e !important;
		color: #e4e4e7 !important;
	}
	[data-site-theme="dark"] #orderinquiryview th {
		background-color: #252528 !important;
		color: #e4e4e7 !important;
	}
	[data-site-theme="dark"] #orderinquiryview tr:nth-child(even) td {
		background-color: #1d1d24 !important;
	}
	[data-site-theme="dark"] #orderinquiryview tr:hover td,
	[data-site-theme="dark"] #orderinquiryview tr:hover th {
		background-color: #252530 !important;
	}
	[data-site-theme="dark"] #orderinquiryview label {
		background: #1a1a1f !important;
		border-color: #3a3a42 !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-ip-panel {
		background: #0f1929 !important;
		border-color: #2d3d52 !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-ip-title {
		color: #c4c4cc !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-ip-help {
		color: #9ca3af !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-access-mini-guide {
		background: #1a1a20 !important;
		border-color: #3a3a42 !important;
		color: #c4c4cc !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-access-mini-guide summary {
		color: #c4c4cc !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-access-guide-body {
		border-top-color: #3a3a42 !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-access-card {
		background: #18181e !important;
		border-color: #3a3a42 !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-access-card.expired-access {
		background: #1e1216 !important;
		border-color: #4a2530 !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-expired-notice {
		background: #2d0f14 !important;
		border-color: #7f1d1d !important;
		color: #fca5a5 !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-program-title { color: #e4e4e7 !important; }
	[data-site-theme="dark"] #orderinquiryview .remote-access-head { color: #e4e4e7 !important; }
	[data-site-theme="dark"] #orderinquiryview .remote-manual-section {
		background: #18181e !important;
		border-color: #3a3a42 !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-manual-btn {
		background: #252528 !important;
		border-color: #4a4a52 !important;
		color: #c4c4cc !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-manual-btn:hover {
		background: #2e2e36 !important;
		color: #e4e4e7 !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-manual-btn.is-active {
		background: #1e2535 !important;
		border-color: #3d5a80 !important;
		color: #93c5fd !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-manual-badge {
		background: #0d2d1e !important;
		border-color: #1a5c38 !important;
		color: #6ee7b7 !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-manual-panel {
		background: #161620 !important;
		border-color: #3a3a42 !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-manual-image {
		background: #1e1e24 !important;
		border-color: #3a3a42 !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-manual-zoom-btn {
		background: rgba(15,25,40,0.92) !important;
		border-color: #3a5a80 !important;
		color: #93c5fd !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-manual-zoom-btn:hover {
		background: rgba(20,35,60,0.96) !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-manual-steps {
		color: #c4c4cc !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-manual-tip {
		background: #1a2035 !important;
		border-color: #2d4270 !important;
		color: #93c5fd !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-cert-download {
		background: #0f1929 !important;
		border-color: #2d4270 !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-cert-title {
		color: #93c5fd !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-cert-btn {
		background: #1e1e24 !important;
		border-color: #3a5a80 !important;
		color: #93c5fd !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-cert-btn:hover {
		background: #1a2435 !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-download-btn {
		background: #252528 !important;
		border-color: #4a4a52 !important;
		color: #c4c4cc !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-download-btn:hover {
		background: #363640 !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-site-btn {
		border-color: #4a4a52 !important;
		background: #252528 !important;
		color: #c4c4cc !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-site-btn:hover {
		background: #363640 !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-credential-item {
		background: #18181e !important;
		border-color: #3a3a42 !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-credential-label {
		color: #9ca3af !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-credential-value {
		color: #e4e4e7 !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-field-row {
		border-top-color: #3a3a42 !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-field-label {
		color: #9ca3af !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-field-value {
		color: #e4e4e7 !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-copy-btn {
		background: #252528 !important;
		border-color: #4a4a52 !important;
		color: #c4c4cc !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-copy-btn:hover {
		background: #363640 !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-copy-btn.copied {
		background: #0d2d1e !important;
		border-color: #1a5c38 !important;
		color: #6ee7b7 !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-download-title {
		color: #9ca3af !important;
	}
	[data-site-theme="dark"] #orderinquiryview .remote-program-caption {
		color: #9ca3af !important;
	}
	[data-site-theme="dark"] .remote-manual-preview-window {
		background: #1e1e24 !important;
		border-color: #3a3a42 !important;
	}
	[data-site-theme="dark"] .remote-manual-preview-body {
		background: #161620 !important;
	}
	[data-site-theme="dark"] .remote-manual-preview-image {
		background: #1e1e24 !important;
		border-color: #3a3a42 !important;
	}
	/* ── 이 페이지 전용: list-head / tr-head / btn-gray 다크모드 보정 ── */
	[data-site-theme="dark"] .list-head,
	[data-site-theme="dark"] .tr-head {
		background: #1e1e24 !important;
		background-image: none !important;
		border-color: #4a4a55 !important;
	}
	[data-site-theme="dark"] .list-head > th,
	[data-site-theme="dark"] .tr-head > th {
		background: #1e1e24 !important;
		background-image: none !important;
		color: #9ca3af !important;
		border-color: #4a4a55 !important;
	}
	[data-site-theme="dark"] .list-head > th > span,
	[data-site-theme="dark"] .tr-head > th > span {
		color: #9ca3af !important;
		border-right-color: #4a4a55 !important;
	}
	[data-site-theme="dark"] .border-black {
		border-top-color: #3f65a8 !important;
	}
	[data-site-theme="dark"] .btn.btn-gray {
		background-color: #2a2a32 !important;
		background-image: none !important;
		border-color: #4a4a52 !important;
		color: #c4c4cc !important;
	}
	[data-site-theme="dark"] .btn.btn-gray:hover,
	[data-site-theme="dark"] .btn.btn-gray:focus,
	[data-site-theme="dark"] .btn.btn-gray:active,
	[data-site-theme="dark"] .btn.active.btn-gray {
		background-color: #363640 !important;
		background-image: none !important;
		border-color: #5a5a68 !important;
		color: #e4e4e7 !important;
	}
	/* ── 최고 우선순위 확보: html 요소 포함 ── */
	html[data-site-theme="dark"] .list-head > th,
	html[data-site-theme="dark"] .tr-head > th {
		background: #1e1e24 !important;
		background-image: none !important;
		color: #9ca3af !important;
		border-color: #4a4a55 !important;
	}
	html[data-site-theme="dark"] .list-head,
	html[data-site-theme="dark"] .tr-head {
		background: #1e1e24 !important;
		background-image: none !important;
	}
	html[data-site-theme="dark"] .bsk-tbl th,
	html[data-site-theme="dark"] .bsk-tbl td {
		background: #18181e !important;
		background-image: none !important;
		color: #c4c4cc !important;
		border-color: #454552 !important;
	}
	html[data-site-theme="dark"] .table.bg-white,
	html[data-site-theme="dark"] .bsk-tbl {
		background-color: #18181e !important;
	}
	html[data-site-theme="dark"] .btn.btn-gray {
		background-color: #2a2a32 !important;
		background-image: none !important;
		border-color: #4a4a52 !important;
		color: #c4c4cc !important;
	}
</style>
<script>
/* 다크모드 tr-head / btn-gray: setProperty 'important'로 CSS !important 우회 */
(function () {
	var ATTR = 'data-site-theme';
	function sp(el, prop, val, pri) {
		try { el.style.setProperty(prop, val, pri); } catch(e) { el.style[prop] = val; }
	}
	function applyOrderDark() {
		var isDark = (document.documentElement.getAttribute(ATTR) === 'dark');
		var pri = isDark ? 'important' : '';
		/* PHP-generated server-side style block — toggle disabled based on current theme */
		var skStyle = document.getElementById('sk-dark-tbl-override');
		if (skStyle) { skStyle.disabled = !isDark; }
		var ths = document.querySelectorAll('.tr-head > th, .list-head > th');
		for (var i = 0; i < ths.length; i++) {
			sp(ths[i], 'background',       isDark ? '#1e1e24' : '', pri);
			sp(ths[i], 'background-image', isDark ? 'none'    : '', pri);
			sp(ths[i], 'color',            isDark ? '#9ca3af' : '', pri);
		}
		var trs = document.querySelectorAll('.tr-head, .list-head');
		for (var j = 0; j < trs.length; j++) {
			sp(trs[j], 'background',       isDark ? '#1e1e24' : '', pri);
			sp(trs[j], 'background-image', isDark ? 'none'    : '', pri);
		}
		var bsktbls = document.querySelectorAll('.div-table.bsk-tbl');
		for (var b = 0; b < bsktbls.length; b++) {
			sp(bsktbls[b], 'background-color', isDark ? '#18181e' : '', pri);
		}
		var grays = document.querySelectorAll('.btn.btn-gray');
		for (var k = 0; k < grays.length; k++) {
			sp(grays[k], 'background-color', isDark ? '#2a2a32' : '', pri);
			sp(grays[k], 'background-image', isDark ? 'none'    : '', pri);
			sp(grays[k], 'color',            isDark ? '#c4c4cc' : '', pri);
			sp(grays[k], 'border-color',     isDark ? '#4a4a52' : '', pri);
		}
	}
	applyOrderDark();
	document.addEventListener('DOMContentLoaded', applyOrderDark);
	if (window.MutationObserver) {
		new MutationObserver(function (ms) {
			for (var i = 0; i < ms.length; i++) {
				if (ms[i].attributeName === ATTR) { applyOrderDark(); return; }
			}
		}).observe(document.documentElement, { attributes: true });
	}
}());
</script>

<div id="extendConfirmBackdrop" class="extend-confirm-backdrop" onclick="closeExtendConfirmModal()"></div>
<div id="extendConfirmModal" class="extend-confirm-modal" role="dialog" aria-modal="true" aria-labelledby="extendConfirmHead">
	<div id="extendConfirmHead" class="extend-confirm-head"><span class="extend-confirm-icon">✓</span><span id="extendConfirmHeadText">계약연장 확인</span></div>
	<div class="extend-confirm-body">
		<div class="warn">정말로 계약연장 하시겠습니까?</div>
		<div class="extend-confirm-sub">이 작업은 취소할 수 없습니다.</div>
		<ul class="extend-confirm-list">
			<li id="extendConfirmItem">계약연장 상품명 : -</li>
			<li id="extendConfirmPeriod">계약연장기간 : -</li>
			<li id="extendConfirmAmount">결제(포인트 차감)금액 : -</li>
			<li id="extendConfirmEnd">계약연장후 종료일시 : -</li>
		</ul>
	</div>
	<div class="extend-confirm-actions">
		<button type="button" class="extend-confirm-btn primary" id="extendConfirmOk">결제하기</button>
		<button type="button" class="extend-confirm-btn" onclick="closeExtendConfirmModal()">취소</button>
	</div>
</div>

<div id="refundConfirmBackdrop" class="extend-confirm-backdrop" onclick="closeRefundConfirmModal()"></div>
<div id="refundConfirmModal" class="extend-confirm-modal" role="dialog" aria-modal="true" aria-labelledby="refundConfirmHead">
	<div id="refundConfirmHead" class="extend-confirm-head"><span class="extend-confirm-icon">!</span><span id="refundConfirmHeadText">계약해지 확인</span></div>
	<div class="extend-confirm-body">
		<div class="warn">정말로 계약해지 하시겠습니까?</div>
		<div class="extend-confirm-sub">이 작업은 취소할 수 없습니다.</div>
		<ul class="extend-confirm-list">
			<li id="refundConfirmItem">계약해지 상품명 : -</li>
			<li id="refundConfirmAmount">환불예정금액 : -</li>
			<li id="refundConfirmMemo">해지사유 : -</li>
		</ul>
	</div>
	<div class="extend-confirm-actions">
		<button type="button" class="extend-confirm-btn primary" id="refundConfirmOk">해지신청</button>
		<button type="button" class="extend-confirm-btn" onclick="closeRefundConfirmModal()">취소</button>
	</div>
</div>

<div id="refundCalcGuideBackdrop" class="extend-confirm-backdrop" onclick="closeRefundCalcGuideModal()"></div>
<div id="refundCalcGuideModal" class="extend-confirm-modal" role="dialog" aria-modal="true" aria-labelledby="refundCalcGuideHead">
	<div id="refundCalcGuideHead" class="extend-confirm-head"><span class="extend-confirm-icon">i</span><span>해지수수료 계산식 안내</span></div>
	<div class="refund-calc-modal-body" id="refundCalcGuideBody"></div>
	<div class="extend-confirm-actions">
		<button type="button" class="extend-confirm-btn primary" id="refundCalcGuideCloseBtn" onclick="closeRefundCalcGuideModal()">닫기</button>
	</div>
</div>

<?php if ($_skin_dark): ?>
<style id="sk-dark-tbl-override">
/* list-head (ivhead 설정 시) 및 tr-head (기본) 모두 커버 */
body .div-table.bsk-tbl .list-head,
body .div-table.bsk-tbl tr.list-head > th,
body .div-table.bsk-tbl .tr-head,
body .div-table.bsk-tbl tr.tr-head > th {
    background: #1e1e24 !important;
    background-image: none !important;
    color: #9ca3af !important;
    border-color: #4a4a55 !important;
}
body .div-table.bsk-tbl tr.list-head > th > span,
body .div-table.bsk-tbl tr.tr-head > th > span {
    color: #9ca3af !important;
    border-right-color: #4a4a55 !important;
}
body .div-table.bsk-tbl td,
body .div-table.bsk-tbl th {
    background: #18181e !important;
    background-image: none !important;
    color: #c4c4cc !important;
    border-color: #454552 !important;
}
/* 헤더행 상단 2px 라인(라이트모드의 border-black에 대응) */
body .div-table.bsk-tbl tr.tr-head,
body .div-table.bsk-tbl tr.list-head {
    border-top-color: #3f65a8 !important;
    border-bottom-color: #4a4a55 !important;
}
</style>
<?php endif; ?>
<div class="table-responsive">
	<table class="div-table table bsk-tbl bg-white">
	<tbody>
	<?php for($i=0;$i < count($item); $i++) { ?>
		<?php
			$real_refund_amount_raw = isset($item[$i]['real_refund_amount']) ? trim((string)$item[$i]['real_refund_amount']) : '0';
			$real_refund_datetime_raw = isset($item[$i]['real_refund_datetime']) ? trim((string)$item[$i]['real_refund_datetime']) : '';
			$has_refund_amount = ((float)$real_refund_amount_raw > 0);
			$has_refund_datetime = ($real_refund_datetime_raw !== '' && $real_refund_datetime_raw !== '0000-00-00 00:00:00');
			// 환불금액이 0이어도 환불 처리일시가 있으면 환불완료 상태로 본다.
			$is_refunded = ($has_refund_amount || $has_refund_datetime);
			$item_name_upper_for_head = strtoupper((string)$item[$i]['it_name']);
			$is_vpn_item_for_head = (strpos($item_name_upper_for_head, 'VPN') !== false && strpos($item_name_upper_for_head, 'RPC') === false);
			$first_col_label = $is_vpn_item_for_head ? 'VPN종류' : '운영체제';
		?>
		<tr class="<?php echo $head_class;?>"<?php echo $_dark_tbl_style;?>>
			<th scope="col"<?php echo $_dark_th_style;?>><span><?php echo $first_col_label; ?></span></th>
			<th scope="col"<?php echo $_dark_th_style;?>><span><?php echo $is_vpn_item_for_head ? 'VPN등급' : ''; ?></span></th>
			<th scope="col"<?php echo $_dark_th_style;?>><span>상품명</span></th>
			<th scope="col"<?php echo $_dark_th_style;?>><span>판매자</span></th>
			<th scope="col"<?php echo $_dark_th_style;?>><span>주문기간</span></th>
			<th scope="col"<?php echo $_dark_th_style;?>><span>이용권 금액</span></th>
			<th scope="col"<?php echo $_dark_th_style;?>><span>개통비/설치비</span></th>
			<th scope="col"<?php echo $_dark_th_style;?>><span>소계</span></th>
			<!-- <th scope="col"><span>포인트</span></th> -->
			<th scope="col"<?php echo $_dark_th_style;?>><span>상태</span></th>
			<th scope="col"<?php echo $_dark_th_style;?>><span>계약연장</span></th>
			<th scope="col"<?php echo $_dark_th_style;?>><span>계약해지</span></th>
			<!-- <th scope="col"><span class="last">배송/이용정보</span></th> -->
		</tr>
		<?php for($k=0; $k < count($item[$i]['opt']); $k++) { ?>
			<?php if($k == 0) { ?>
				<?php
					$item_expire_ts = strtotime((string)$item[$i]['it_spec_to_datetime']);
					$is_contract_expired = ($item_expire_ts !== false && $item_expire_ts > 0 && $item_expire_ts <= strtotime(G5_TIME_YMDHIS));
				?>
				<?php
					// VPN 상품인 경우 item 레코드 없어도 provision queue에서 종류/등급 보완
					$row_os = sql_fetch("SELECT * FROM {$g5['g5_shop_item_table']} WHERE it_id='{$item[$i]['it_id']}'");
					$_oi_spec_os    = isset($row_os['it_spec_os'])    ? trim((string)$row_os['it_spec_os'])    : '';
					$_oi_spec_grade = isset($row_os['it_spec_grade']) ? trim((string)$row_os['it_spec_grade']) : '';
					if ($is_vpn_item_for_head && $_oi_spec_os === '') {
						$_pq_row = sql_fetch("SELECT protocol FROM app_ikev2_provision_queue WHERE it_id='{$item[$i]['it_id']}' AND od_id='$od_id' ORDER BY queue_id DESC LIMIT 1", false);
						if (!empty($_pq_row['protocol'])) { $_oi_spec_os = $_pq_row['protocol']; }
					}
				?>
				<tr<?php echo ($i == 0) ? ' class="tr-line"' : '';?>>
					<td class="text-center">
						<?php if ($is_vpn_item_for_head): ?>
							<div style="padding:4px 2px;">
								<?php echo vpn_category_badge_html($_oi_spec_os); ?>
							</div>
						<?php else: ?>
							<div class="item-img">
								<?php echo get_it_image($item[$i]['it_id'], 70, 70); ?>
								<div class="item-type" style="letter-spacing: -0.5px;">
									<?php echo trim(str_ireplace(array("Microsoft", "Windows"), array("", "Win"), $_oi_spec_os)); ?>
								</div>
							</div>
						<?php endif; ?>
					</td>
					<td class="text-center">
						<?php if ($is_vpn_item_for_head): ?>
							<div style="padding:4px 2px;">
								<?php echo vpn_grade_badge_html($_oi_spec_grade); ?>
							</div>
						<?php endif; ?>
					</td>
					<td class="text-center">
						<input type="hidden" name="it_id[<?php echo $i; ?>]" value="<?php echo $item[$i]['it_id']; ?>">
						<input type="hidden" name="it_name[<?php echo $i; ?>]" value="<?php echo get_text($item[$i]['it_name']); ?>">
						<a href="./item.php?it_id=<?php echo $item[$i]['it_id'];?>"><b><?php echo stripslashes($item[$i]['it_name']); ?></b><br>[<?php echo $item[$i]['pt_it']; ?>]</a>
						<?php // 옵션사항이 있을 때만 메뉴 표시되도록 되어 있는 걸 항상 표시되도록 계약일수 아래로 이동 JSLEE
						/*
						if($item[$i]['it_options']) {
						<div class="well well-sm"><?php echo $item[$i]['it_options'];?></div>
						<button type="button" class="btn btn-primary btn-sm btn-block mod_options">선택사항수정</button>
						*/
						?>
					</td>
					<td class="text-center vplat-seller-cell">
						<?php
							// 판매자 표시 (통신판매중개 플랫폼: 상품별 판매자 명시)
							$seller_pt_id = isset($row_os['pt_id']) ? trim((string)$row_os['pt_id']) : '';
							$seller_nick = '';
							if ($seller_pt_id !== '' && function_exists('get_pt_seller_name')) {
								$seller_nick = trim((string)get_pt_seller_name($seller_pt_id));
							}
							if ($seller_nick !== '') {
								echo '<div style="font-weight:600; letter-spacing:-0.3px; word-break:keep-all;">'.get_text(cut_str($seller_nick, 18, '…')).'</div>';
								if (function_exists('get_pt_manner_temperature')) {
									echo '<div style="font-size:11px; color:#8a97a5; margin-top:2px; white-space:nowrap;">매너온도 '.get_pt_manner_temperature($seller_pt_id).'</div>';
								}
							} else {
								echo '-';
							}
						?>
					</td>
					<td class="text-center">
						<?php
							$base_contract_hours = apms_contract_hours_from_day_hour(
								(int)$item[$i]['opt'][$k]['ct_qty'],
								(int)$item[$i]['opt'][$k]['ct_qty_hour']
							);
							$base_unit = apms_pricing_unit_from_day_hour(
								(int)$item[$i]['opt'][$k]['ct_qty'],
								(int)$item[$i]['opt'][$k]['ct_qty_hour']
							);
							$base_count = apms_pricing_count_from_day_hour(
								(int)$item[$i]['opt'][$k]['ct_qty'],
								(int)$item[$i]['opt'][$k]['ct_qty_hour'],
								$base_unit
							);
							$ext_contract_hours = apms_contract_hours_from_day_hour(
								(int)$item[$i]['opt'][$k]['ct_qty_for_extension_of_period'],
								(int)$item[$i]['opt'][$k]['ct_qty_hour_for_extension_of_period']
							);
							echo apms_contract_hours_text($base_contract_hours);
						?>
						<br>[연장 +<?php echo apms_contract_hours_text($ext_contract_hours); ?>]
					</td>
					<?php $license_price = (int)$item[$i]['opt'][$k]['sell_price'] - (int)$item[$i]['opt'][$k]['ct_install_price']; ?>
					<td class="text-center"><?php echo number_format($license_price); ?></td>
					<td class="text-center"><?php echo number_format($item[$i]['opt'][$k]['ct_install_price']); ?></td>
					<td class="text-center"><?php echo number_format($item[$i]['opt'][$k]['sell_price']); ?><br>[연장 +<?php echo number_format($item[$i]['opt'][$k]['ct_price_for_extension_of_period']); ?>]</td>
					<td class="text-center"><?php echo $item[$i]['opt'][$k]['ct_status']; ?></td>
					<td class="text-center">
						<div class="print-hide text-center h15">
							<?php if (!$is_refunded) { // 환불되지 않았다면 ?>
								<button type="button" onclick="openExtendPopup('<?php echo $od_id . "_" . $item[$i]['it_id']; ?>')" class="btn btn-sm <?php echo $is_contract_expired ? 'btn-extend-expired' : 'btn-gray'; ?>" style="font-size:1.1rem;<?php if($_skin_dark && !$is_contract_expired){echo 'background-color:#2a2a32;background-image:none;border-color:#4a4a52;color:#c4c4cc;';}?>"><?php echo $is_contract_expired ? '만료됨 · 연장하기' : '연장하기'; ?></button>
								<?php if ($is_contract_expired) { ?>
									<div class="extend-expired-hint">연장 후 다시 이용 가능합니다.</div>
								<?php } ?>
							<?php } else { ?>
								<button type="button" class="btn btn-gray btn-sm" style="font-size:1.1rem;<?php if($_skin_dark){echo 'background-color:#2a2a32;background-image:none;border-color:#4a4a52;color:#c4c4cc;';}?>" disabled>연장불가</button>
							<?php } ?>
						</div>

						<div class="h15"></div>
						<?php if (!$is_refunded) { ?>
						<div id="sod_fin_ExtendPeriodBackdrop_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>" class="extend-popup-backdrop" onclick="closeExtendPopup('<?php echo $od_id . "_" . $item[$i]['it_id']; ?>')"></div>
						<div id="sod_fin_ExtendPeriodfrm_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>" class="extend-popup-window" data-popup-id="<?php echo $od_id . "_" . $item[$i]['it_id']; ?>">
							<div class="extend-popup-header">
								<div class="extend-popup-title">계약연장 · <?php echo get_text(stripslashes($item[$i]['it_name'])); ?></div>
								<button type="button" class="extend-popup-close" onclick="closeExtendPopup('<?php echo $od_id . "_" . $item[$i]['it_id']; ?>')">×</button>
							</div>
							<div class="extend-popup-body">
								<div class="well extend-layer-box">
								<form class="form" role="form" method="post" action="./orderinquiryExtendPeriod.php" onsubmit="return fExtendPeriod_check(this);">
								<input type="hidden" name="od_id"  value="<?php echo $od['od_id']; ?>">
								<input type="hidden" name="it_id"  value="<?php echo $item[$i]['it_id']; ?>">
								<input type="hidden" name="it_name" value="<?php echo get_text(stripslashes($item[$i]['it_name'])); ?>">
								<input type="hidden" name="ExtendPeriod_amount" id="ExtendPeriod_amount_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>" value="0">
								<input type="hidden" name="ExtendPeriod_datetime" id="ExtendPeriod_datetime_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>" value="0000-00-00 00:00:00">
								<input type="hidden" name="check_code2" id="check_code2_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>" value="<?php echo md5(md5(md5(md5(md5($item[$i]['it_id']."Ž".$member['mb_id']."Ž".$member['mb_today_login'])))))?>">

								<input type="hidden" name="token"  value="<?php echo $token; ?>">
								<input type="hidden" name="idempotency_key" value="<?php echo md5($member['mb_id'].'|'.$od['od_id'].'|'.$item[$i]['it_id'].'|extend|'.uniqid('', true)); ?>">

								<div class="input-group text-center extend-current-end"><strong>현재 종료일 <?php echo $item[$i]['it_spec_to_datetime']?></strong></div>

								<div class="input-group input-group-sm" style="display:block; width:100%;">
									<?php
									// // 현재 시간
									// $current_time = new DateTime(G5_TIME_YMDHIS);

									// // 시작 및 종료 시간
									// $start_time = new DateTime($item[$i]['it_spec_from_datetime']);
									// $end_time = new DateTime($item[$i]['it_spec_to_datetime']);

									// // 총 사용 시간 (초 단위로 계산 후 분으로 변환)
									// $total_usage_time = $end_time->getTimestamp() - $start_time->getTimestamp();
									// $total_usage_minutes = $total_usage_time / 60;

									// // 분당 요금 계산
									// $minute_rate = (($item[$i]['opt'][$k]['ct_price'] * $item[$i]['opt'][$k]['ct_qty']) + $item[$i]['opt'][$k]['sell_price_for_extension_of_period']) / $total_usage_minutes;

									// 상품상세와 동일한 이용권 단위/할인 기준 사용
									$extend_item_pricing = sql_fetch("SELECT * FROM {$g5['g5_shop_item_table']} WHERE it_id = '{$item[$i]['it_id']}'");
									$extend_hourly_price = apms_item_hourly_base_price($extend_item_pricing);
									$extend_allowed_units = apms_allowed_pricing_units_from_item($extend_item_pricing);
									$extend_unit_candidates = array('hour', 'day', 'month', 'year');
									$extend_default_unit = 'hour';
									if (empty($extend_allowed_units[$extend_default_unit])) {
										foreach ($extend_unit_candidates as $candidate_unit) {
											if (!empty($extend_allowed_units[$candidate_unit])) {
												$extend_default_unit = $candidate_unit;
												break;
											}
										}
									}
									$extend_default_count = 1;
									list($extend_default_days, $extend_default_hours) = apms_day_hour_from_pricing_unit($extend_default_unit, $extend_default_count);
									$extend_fee_guide_by_unit = array(
										'hour' => '1시간 이용권: '.apms_display_point_plain(apms_pricing_unit_package_price_by_item($extend_item_pricing, 'hour', $extend_hourly_price)),
										'day' => '1일 이용권: '.apms_display_point_plain(apms_pricing_unit_package_price_by_item($extend_item_pricing, 'day', $extend_hourly_price)),
										'month' => '1개월(30일) 이용권: '.apms_display_point_plain(apms_pricing_unit_package_price_by_item($extend_item_pricing, 'month', $extend_hourly_price)),
										'year' => '1년(365일) 이용권: '.apms_display_point_plain(apms_pricing_unit_package_price_by_item($extend_item_pricing, 'year', $extend_hourly_price))
									);
									$extend_fee_guide_text = isset($extend_fee_guide_by_unit[$extend_default_unit]) ? $extend_fee_guide_by_unit[$extend_default_unit] : '-';
									$extend_default_suffix = '시간';
									if ($extend_default_unit === 'day') {
										$extend_default_suffix = '일';
									} else if ($extend_default_unit === 'month') {
										$extend_default_suffix = '개월';
									} else if ($extend_default_unit === 'year') {
										$extend_default_suffix = '년';
									}
									?>
									<div id="ExtendPeriod_fee_guide_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>" class="extend-fee-guide"><?php echo $extend_fee_guide_text; ?></div>

									<div class="extend-pricing-row">
									<select name="ExtendPeriod_pricing_unit" id="ExtendPeriod_pricing_unit_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>" class="form-control input-sm extend-unit-select" style="font-size:1.1rem;"
										data-hourly-price="<?php echo (float)$extend_hourly_price; ?>"
										data-discount-hour="<?php echo apms_pricing_unit_discount_for_item($extend_item_pricing, 'hour'); ?>"
										data-discount-day="<?php echo apms_pricing_unit_discount_for_item($extend_item_pricing, 'day'); ?>"
										data-discount-month="<?php echo apms_pricing_unit_discount_for_item($extend_item_pricing, 'month'); ?>"
										data-discount-year="<?php echo apms_pricing_unit_discount_for_item($extend_item_pricing, 'year'); ?>"
										data-allow-hour="<?php echo !empty($extend_allowed_units['hour']) ? '1' : '0'; ?>"
										data-allow-day="<?php echo !empty($extend_allowed_units['day']) ? '1' : '0'; ?>"
										data-allow-month="<?php echo !empty($extend_allowed_units['month']) ? '1' : '0'; ?>"
										data-allow-year="<?php echo !empty($extend_allowed_units['year']) ? '1' : '0'; ?>"
										data-fee-hour="<?php echo htmlspecialchars($extend_fee_guide_by_unit['hour'], ENT_QUOTES); ?>"
										data-fee-day="<?php echo htmlspecialchars($extend_fee_guide_by_unit['day'], ENT_QUOTES); ?>"
										data-fee-month="<?php echo htmlspecialchars($extend_fee_guide_by_unit['month'], ENT_QUOTES); ?>"
										data-fee-year="<?php echo htmlspecialchars($extend_fee_guide_by_unit['year'], ENT_QUOTES); ?>"
										onchange="updatePaymentButton('<?php echo $od_id . "_" . $item[$i]['it_id']; ?>' , <?php echo $item[$i]['it_id']; ?>)">
										<?php if(!empty($extend_allowed_units['hour'])) { ?><option value="hour" <?php echo get_selected('hour', $extend_default_unit); ?>>1시간 이용권 (<?php echo apms_display_point_plain(apms_pricing_unit_package_price_by_item($extend_item_pricing, 'hour', $extend_hourly_price)); ?>)</option><?php } ?>
										<?php if(!empty($extend_allowed_units['day'])) { ?><option value="day" <?php echo get_selected('day', $extend_default_unit); ?>>1일 이용권 (<?php echo apms_display_point_plain(apms_pricing_unit_package_price_by_item($extend_item_pricing, 'day', $extend_hourly_price)); ?>)</option><?php } ?>
										<?php if(!empty($extend_allowed_units['month'])) { ?><option value="month" <?php echo get_selected('month', $extend_default_unit); ?>>1개월(30일) 이용권 (<?php echo apms_display_point_plain(apms_pricing_unit_package_price_by_item($extend_item_pricing, 'month', $extend_hourly_price)); ?>)</option><?php } ?>
										<?php if(!empty($extend_allowed_units['year'])) { ?><option value="year" <?php echo get_selected('year', $extend_default_unit); ?>>1년(365일) 이용권 (<?php echo apms_display_point_plain(apms_pricing_unit_package_price_by_item($extend_item_pricing, 'year', $extend_hourly_price)); ?>)</option><?php } ?>
									</select>
									<div class="extend-count-wrap">
										<input type="number" name="ExtendPeriod_pricing_count" id="ExtendPeriod_pricing_count_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>" min="1" step="1" value="<?php echo (int)$extend_default_count; ?>" class="form-control input-sm extend-count-input" style="font-size:1.1rem;" oninput="updatePaymentButton('<?php echo $od_id . "_" . $item[$i]['it_id']; ?>' , <?php echo $item[$i]['it_id']; ?>)">
										<span class="extend-count-suffix" id="ExtendPeriod_pricing_suffix_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>"><?php echo $extend_default_suffix; ?></span>
									</div>
									</div>
									<input type="hidden" name="ExtendPeriod_days" id="ExtendPeriod_days_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>" value="<?php echo (int)$extend_default_days; ?>">
									<input type="hidden" name="ExtendPeriod_hours" id="ExtendPeriod_hours_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>" value="<?php echo (int)$extend_default_hours; ?>">
								</div>
								<div class="extend-submit-row">
									<button type="submit" id="paymentButton_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>" class="btn btn-black btn-sm" style="font-size:1.1rem; min-width:88px;" disabled>결제하기</button>
								</div>
								<div id="ExtendPeriod_human_hint_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>" style="margin-top:6px; font-size:12px; color:#666;">선택기간: -</div>
								<div id="ExtendPeriod_auto_notice_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>" style="margin-top:4px; font-size:12px; color:#0b6e4f; display:none;"></div>
								<div class="extend-summary">연장 주문합계: <span id="ExtendPeriod_total_disp_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>">0</span></div>
								<div id="paymentButton_msg_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>"></div>
								</form>
							</div>
							</div>
							<div class="extend-popup-resizer"></div>
						</div>
						<?php } ?>
						<script>
							// 초기 로드 시 결제금액/종료일시 계산
							document.addEventListener('DOMContentLoaded', function() {
								updatePaymentButton('<?php echo $od_id . "_" . $item[$i]['it_id']; ?>', <?php echo (int)$item[$i]['it_id']; ?>);
								initExtendPopup('<?php echo $od_id . "_" . $item[$i]['it_id']; ?>');
							});
						</script>
					</td>


					<td class="text-center" style="padding-right:0;">
					<?php if (!$is_refunded) { // 환불되지 않았다면 ?>
						<div class="print-hide text-center h15">
							<button type="button" onclick="openRefundPopup('<?php echo $od_id . "_" . $item[$i]['it_id']; ?>')" class="btn btn-gray btn-sm" style="font-size:1.1rem;<?php if($_skin_dark){echo 'background-color:#2a2a32;background-image:none;border-color:#4a4a52;color:#c4c4cc;';}?>">해지하기</button>
						</div>

						<div class="h15"></div>
						<div id="sod_fin_refundBackdrop_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>" class="extend-popup-backdrop" onclick="closeRefundPopup('<?php echo $od_id . "_" . $item[$i]['it_id']; ?>')"></div>
						<div id="sod_fin_refundfrm_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>" class="extend-popup-window refund-popup-window" data-refund-popup-id="<?php echo $od_id . "_" . $item[$i]['it_id']; ?>">
							<div class="extend-popup-header">
								<div class="extend-popup-title">계약해지 · <?php echo get_text(stripslashes($item[$i]['it_name'])); ?></div>
								<button type="button" class="extend-popup-close" onclick="closeRefundPopup('<?php echo $od_id . "_" . $item[$i]['it_id']; ?>')">×</button>
							</div>
							<div class="extend-popup-body">
							<div class="well" style="padding-bottom:16px;">
								<form class="form" role="form" method="post" action="./orderinquiryrefund.php" onsubmit="return frefund_check(this);">
								<input type="hidden" name="od_id"  value="<?php echo $od['od_id']; ?>">
								<input type="hidden" name="it_id"  value="<?php echo $item[$i]['it_id']; ?>">
								<input type="hidden" name="it_name" value="<?php echo get_text(stripslashes($item[$i]['it_name'])); ?>">
								<input type="hidden" name="contract_is_expired" id="contract_is_expired_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>" value="<?php echo $contract_is_expired ? '1' : '0'; ?>">

								<?php
									// 현재 시간
									$current_time = new DateTime(G5_TIME_YMDHIS);

									// 시작 및 종료 시간
									$start_time = new DateTime($item[$i]['it_spec_from_datetime']);
									$end_time = new DateTime($item[$i]['it_spec_to_datetime']);

									// 총 계약 시간(초)
									$total_usage_time = max(0, $end_time->getTimestamp() - $start_time->getTimestamp());
									$total_usage_minutes = $total_usage_time / 60;

									$paid_total_amount = (($item[$i]['opt'][$k]['ct_price'] * $item[$i]['opt'][$k]['ct_qty']) + $item[$i]['opt'][$k]['ct_price_for_extension_of_period']);
									$minute_rate = ($total_usage_minutes > 0) ? ($paid_total_amount / $total_usage_minutes) : 0;

									// ── 마지막 연속 블록 감지: 모든 주문 조회 후 환불 대상 블록 결정 ──
									$_itIdBdEsc2 = (string)(int)$item[$i]["it_id"];
									$_mbIdBdEsc2 = addslashes((string)$member["mb_id"]);
									$_bd_res2 = sql_query(
										"SELECT o.od_id, o.od_time, o.od_receipt_point,"
										. " o.od_receipt_point_for_extension_of_period, o.od_mod_history"
										. " FROM {$g5['g5_shop_order_table']} o"
										. " INNER JOIN {$g5['g5_shop_cart_table']} c ON c.od_id=o.od_id AND c.mb_id=o.mb_id"
										. " WHERE o.mb_id='{$_mbIdBdEsc2}'"
										. "   AND c.it_id='{$_itIdBdEsc2}'"
										. "   AND c.ct_status IN ('입금','완료')"
										. " ORDER BY o.od_time ASC", false);
									$_orders_bd2 = array();
									$_newEnd2_carry = '';
									while ($_bd_row2 = sql_fetch_array($_bd_res2, false)) {
										$_newAmt2 = (int)$_bd_row2['od_receipt_point'];
										$_extAmt2 = (int)$_bd_row2['od_receipt_point_for_extension_of_period'];
										$_hist2   = (string)($_bd_row2['od_mod_history'] ?? '');
										$_newEnd2 = '';
										if ($_newAmt2 > 0) {
											$_lbl2 = '';
											if ($_hist2 && preg_match('/신규계약\s*\((\d+)일(\d+)시간\)/', $_hist2, $_mN2)) {
												$_d2=(int)$_mN2[1];$_h2=(int)$_mN2[2];
												$_lbl2=($_d2>0?$_d2.'일':'').($_h2>0?$_h2.'시간':'');
												if(!$_lbl2)$_lbl2='0시간';
												$_ts2=strtotime($_bd_row2['od_time'])+$_d2*86400+$_h2*3600;
												if($_ts2>0){$_newEnd2=date('Y-m-d H:i:s',$_ts2);$_newEnd2_carry=$_newEnd2;}
											}
											$_orders_bd2[]=array('od_id'=>(string)$_bd_row2['od_id'],'od_time'=>(string)$_bd_row2['od_time'],'end_time'=>$_newEnd2,'period_label'=>$_lbl2,'amount'=>$_newAmt2,'type'=>'신규계약','refundable'=>true);
										}
										if ($_extAmt2 > 0) {
											$_extTime2=(string)$_bd_row2['od_time'];$_extEnd2='';$_extLbl2='';
											if($_hist2){
												if(preg_match('/(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\s+계약연장/',$_hist2,$_mE2))$_extTime2=$_mE2[1];
												if(preg_match('/계약연장\s*\((\d+)일(\d+)시간\)/',$_hist2,$_mEP2)){
													$_ed2=(int)$_mEP2[1];$_eh2=(int)$_mEP2[2];
													$_extLbl2=($_ed2>0?$_ed2.'일':'').($_eh2>0?$_eh2.'시간':'');
													if(!$_extLbl2)$_extLbl2='0시간';
													$_baseTs2=$_newEnd2_carry?strtotime($_newEnd2_carry):strtotime($_extTime2);
													$_ts2=$_baseTs2+$_ed2*86400+$_eh2*3600;
													if($_ts2>0)$_extEnd2=date('Y-m-d H:i:s',$_ts2);
												}
											}
											$_orders_bd2[]=array('od_id'=>(string)$_bd_row2['od_id'],'od_time'=>$_extTime2,'end_time'=>$_extEnd2,'period_label'=>$_extLbl2,'amount'=>$_extAmt2,'type'=>'계약연장','refundable'=>true);
										}
									}
									// 마지막 갭 찾기
									$_lastGapIdx2 = -1; $_prevEndTs2 = null; $_bdCount2 = count($_orders_bd2);
									for($_bi2=0;$_bi2<$_bdCount2;$_bi2++){
										$_eOdTs2=!empty($_orders_bd2[$_bi2]['od_time'])?strtotime($_orders_bd2[$_bi2]['od_time']):0;
										if($_prevEndTs2!==null&&$_eOdTs2>0&&$_eOdTs2>$_prevEndTs2+300)$_lastGapIdx2=$_bi2;
										if(!empty($_orders_bd2[$_bi2]['end_time']))$_prevEndTs2=strtotime($_orders_bd2[$_bi2]['end_time']);
									}
									// 환불 대상 블록 파라미터 추출
									$_refundAmt2=0;$_refundStartTs2=null;
									for($_bi2=0;$_bi2<$_bdCount2;$_bi2++){
										$_isRef2=($_lastGapIdx2<0||$_bi2>=$_lastGapIdx2);
										$_orders_bd2[$_bi2]['refundable']=$_isRef2;
										if($_isRef2){
											$_refundAmt2+=(int)$_orders_bd2[$_bi2]['amount'];
											if($_refundStartTs2===null&&!empty($_orders_bd2[$_bi2]['od_time']))$_refundStartTs2=strtotime($_orders_bd2[$_bi2]['od_time']);
										}
									}
									// 갭이 있으면 환불 대상 블록 기준으로 계산 파라미터 재설정
									// ct_qty=0 버그 보정: paid_total_amount가 0이면 DB 실제 결제금액으로 대체
									if ($paid_total_amount <= 0 && $_refundAmt2 > 0 && $_lastGapIdx2 < 0) {
										$paid_total_amount = (float)$_refundAmt2;
										$total_usage_minutes = $total_usage_time / 60;
										$minute_rate = ($total_usage_minutes > 0) ? ($paid_total_amount / $total_usage_minutes) : 0;
									}
									if($_lastGapIdx2>0&&$_refundStartTs2!==null&&$_refundAmt2>0){
										$start_time = new DateTime(date('Y-m-d H:i:s',$_refundStartTs2));
										$_refund_total_sec = max(0, $end_time->getTimestamp()-$_refundStartTs2);
										$total_usage_time = $_refund_total_sec;
										$paid_total_amount = (float)$_refundAmt2;
										$total_usage_minutes = $total_usage_time/60;
										$minute_rate = ($total_usage_minutes>0)?($paid_total_amount/$total_usage_minutes):0;
									}
									// 현재까지 경과 시간(0 ~ 총계약시간으로 보정)
									$elapsed_time_raw = $current_time->getTimestamp() - $start_time->getTimestamp();
									$elapsed_time = min(max(0, $elapsed_time_raw), $total_usage_time);
									$remaining_time = max(0, $total_usage_time - $elapsed_time);
									$elapsed_minutes = $elapsed_time / 60;
									$remaining_minutes = $remaining_time / 60;

									// 환불액 계산 (해지수수료율은 common.php VPNLINK_CANCELLATION_FEE_RATE 참조)
									$remaining_cost = max(0, $remaining_minutes * $minute_rate);
									$_fee_rate = defined('VPNLINK_CANCELLATION_FEE_RATE') ? VPNLINK_CANCELLATION_FEE_RATE : 0.15;
									$penalty_amount = $remaining_cost * $_fee_rate;
									$refund_amount_after_penalty = max(0, $remaining_cost - $penalty_amount);
									$_ct_install_price = max(0, (int)$item[$i]['opt'][$k]['ct_install_price']);

									// 현재까지 경과된 시간에 대한 요금 계산
									$elapsed_cost = max(0, $elapsed_minutes * $minute_rate);

									// 총 계약 시간 계산 (일, 시간, 분 단위)
									$total_usage_days = floor($total_usage_time / 86400);
									$total_usage_hours = floor(($total_usage_time % 86400) / 3600);
									$total_usage_remaining_minutes = floor(($total_usage_time % 3600) / 60);

									// 잔여 시간 계산 (일, 시간, 분 단위)
									$remaining_days = floor($remaining_time / 86400);
									$remaining_hours = floor(($remaining_time % 86400) / 3600);
									$remaining_remaining_minutes = floor(($remaining_time % 3600) / 60);

									// 현재까지 경과된 시간 계산 (일, 시간, 분 단위)
									$elapsed_days = floor($elapsed_time / 86400);
									$elapsed_hours = floor(($elapsed_time % 86400) / 3600);
									$elapsed_remaining_minutes = floor(($elapsed_time % 3600) / 60);

									$contract_period_text = "{$total_usage_days}일 {$total_usage_hours}시간 {$total_usage_remaining_minutes}분";
									$contract_is_expired = ($remaining_time <= 0);
									$contract_status_text = $contract_is_expired ? '계약기간 만료' : '계약 유지중';
									$contract_status_class = $contract_is_expired ? 'expired' : 'active';
									$elapsed_cost_disp = number_format((float)$elapsed_cost, 2, '.', ',');
									$remaining_cost_disp = number_format((float)$remaining_cost, 2, '.', ',');
									$penalty_amount_rounded = round((float)$penalty_amount);
									$refund_amount_after_penalty_rounded = round((float)$refund_amount_after_penalty);
									$penalty_amount_disp = number_format((float)$penalty_amount_rounded, 0, '.', ',');
									$refund_amount_after_penalty_disp = number_format((float)$refund_amount_after_penalty_rounded, 0, '.', ',');
									$penalty_formula_base_disp = number_format((float)$remaining_cost, 2, '.', ',');
									$penalty_formula_raw_disp = number_format((float)$penalty_amount, 3, '.', ',');
									$refund_formula_raw_disp = number_format((float)$refund_amount_after_penalty, 3, '.', ',');
									$_total_paid_all = $paid_total_amount + $_ct_install_price;
									$_total_paid_all_disp = number_format((float)$_total_paid_all, 0, '.', ',');
									$_install_price_disp = number_format((float)$_ct_install_price, 0, '.', ',');
									$_subscription_fee_disp = number_format((float)$paid_total_amount, 0, '.', ',');

									// 결과 출력
									// echo "[계약해지 명세서]<br>";
									// // echo "계약기간: {$total_usage_days}일 {$total_usage_hours}시간 {$total_usage_remaining_minutes}분<br>";
									// echo "사용한요금: " . display_point($elapsed_cost);
									// echo " (사용한시간: {$elapsed_days}일 {$elapsed_hours}시간 {$elapsed_remaining_minutes}분)<br>";

									// echo "미사용요금: " . display_point($remaining_cost);
									// echo " (미사용시간: {$remaining_days}일 {$remaining_hours}시간 {$remaining_remaining_minutes}분)<br>";

									// echo "해지수수료: " . display_point($penalty_amount) . " (미사용요금 x 0.3)<br>";
									// echo "환불금액: " . display_point($refund_amount_after_penalty) . " (미사용요금 - 해지수수료)<br>";
								?>


								<input type="hidden" name="token"  value="<?php echo $token; ?>">
								<input type="hidden" name="idempotency_key" value="<?php echo md5($member['mb_id'].'|'.$od['od_id'].'|'.$item[$i]['it_id'].'|refund|'.uniqid('', true)); ?>">
									<div class="input-group input-group-sm">
										<span class="input-group-addon" style="font-size:1.1rem;">해지사유</span>
										<input type="text" name="refund_memo" required class="form-control input-sm" style="font-size:1.1rem;" size="40" maxlength="100">
										<span class="input-group-btn">
											<button type="submit" id="refund_submit_btn_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>" class="btn btn-black btn-sm" style="font-size:1.1rem;" <?php echo $contract_is_expired ? 'disabled' : ''; ?>><?php echo $contract_is_expired ? '환불불가(계약만료)' : '환불받기'; ?></button>
										</span>
									</div>
								</form>
							</div>

							<div class="well text-left">

								<?php /* ?>
								<div class="text-center font-11" style="margin-bottom:5px;">
									<i class="fa fa-info-circle"></i>
									<span id="toggle-content" class="toggle-content">환불금액 : 미사용요금 - 해지수수료&nbsp; ※해지수수료 : 미사용요금 x 0.3</span>
								</div>
								<?php */ ?>
								<?php if($_bdCount2>0){ ?>
								<div style="margin-bottom:10px;">
									<p style="font-size:1.0rem;font-weight:bold;margin-bottom:4px;color:#555;"><?php echo ($_lastGapIdx2>=0)?'주문 내역 (환불대상 블록 식별)':'주문 내역'; ?></p>
									<table class="table table-condensed" style="margin-bottom:0;font-size:0.95rem;table-layout:fixed;width:100%;">
										<colgroup><col style="width:16%"><col style="width:10%"><col style="width:10%"><col style="width:25%"><col style="width:25%"><col style="width:14%"></colgroup><thead><tr><th style="text-align:left">구분</th><th style="text-align:right">금액</th><th style="text-align:center">기간</th><th style="text-align:left">시작</th><th style="text-align:left">종료</th><th style="text-align:center">상태</th></tr></thead>
										<tbody>
										<?php foreach($_orders_bd2 as $_bde2){ ?>
										<tr <?php echo $_bde2['refundable']?'':'style="color:#aaa;"'; ?>>
											<td><?php echo $_bde2['type']; ?></td>
											<td style="text-align:right"><?php echo number_format($_bde2['amount']); ?></td>
											<td style="text-align:center"><?php echo $_bde2["period_label"]; ?></td>
											<td><?php echo strlen($_bde2['od_time'])>=16?substr($_bde2['od_time'],0,16):$_bde2['od_time']; ?></td>
											<td><?php echo strlen($_bde2['end_time'])>=16?substr($_bde2['end_time'],0,16):($_bde2['end_time']?$_bde2['end_time']:'-'); ?></td>
											<td style="text-align:center"><?php if($_bde2["refundable"]){?><span class="label label-success">환불대상</span><?php }else{?><span class="label label-default">만료됨</span><?php } ?></td>
										</tr>
										<?php } ?>
										</tbody>
									</table>
								</div>
								<?php } ?>
								<div>
									<table class="table" style="margin-bottom:0px; font-size:1.1rem;">
										<tr>
											<th><?php echo ($_lastGapIdx2>=0)?'환불계산시작':'계약시작'; ?></th>
											<td class="text-center" id="contract_start_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>"><?php echo $start_time->format('Y-m-d H:i:s'); ?></td>
											<th>계약종료</th>
											<td class="text-center" id="contract_end_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>"><?php echo $item[$i]['it_spec_to_datetime']; ?></td>
										</tr>
										<tr>
											<th><?php echo ($_lastGapIdx2>=0)?'환불대상기간':'계약기간'; ?></th>
											<td class="text-center" id="contract_period_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>" colspan="3"><?php echo $contract_period_text; ?></td>
										</tr>
										<tr>
											<th>계약상태</th>
											<td class="text-center" colspan="3">
												<span id="contract_status_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>" class="contract-status-badge <?php echo $contract_status_class; ?>"><?php echo $contract_status_text; ?></span>
											</td>
										</tr>
										<tr>
											<th>사용한요금</th>
											<td class="text-right refund-point-cell" id="elapsed_cost_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>"><?php echo $elapsed_cost_disp; ?></td>
											<th>사용한시간</th>
											<td class="text-center" id="elapsed_time_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>"><?php echo "{$elapsed_days}일 {$elapsed_hours}시간 {$elapsed_remaining_minutes}분"?></td>
										</tr>
										<tr>
											<th>미사용요금</th>
											<td class="text-right refund-point-cell" id="remaining_cost_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>"><?php echo $remaining_cost_disp; ?></td>
											<th>미사용시간</th>
											<td class="text-center" id="remaining_time_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>"><?php echo "{$remaining_days}일 {$remaining_hours}시간 {$remaining_remaining_minutes}분"?></td>
										</tr>
										<tr>
											<th>
												<span class="refund-fee-head">
													<span>해지수수료</span>
													<button type="button" class="refund-calc-toggle" id="refund_calc_toggle_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>" onclick="openRefundCalcGuideModal('<?php echo $od_id . "_" . $item[$i]['it_id']; ?>')" aria-expanded="false" title="해지수수료 계산식 안내 보기" aria-label="해지수수료 계산식 안내 보기">
														<i class="fa fa-info-circle" aria-hidden="true"></i>
													</button>
												</span>
											</th>
											<td class="text-right refund-point-cell" id="penalty_amount_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>"><?php echo $penalty_amount_disp; ?></td>
											<th class="red">환불금액</th>
											<th class="text-right red refund-point-cell" id="refund_amount_after_penalty_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>"><?php echo $refund_amount_after_penalty_disp; ?></th>
										</tr>
									</table>
									<p class="refund-amount-note">※ 표시된 금액은 현재 시점 기준 예정액입니다. 실제 환불액은 접수 처리 시각에 따라 재계산되므로 소폭 차이가 발생할 수 있습니다.</p>
									<div class="refund-calc-guide" id="refund_calc_guide_<?php echo $od_id . "_" . $item[$i]['it_id']; ?>">
										<?php $_fee_rate_pct = (int)round($_fee_rate * 100); ?>
										<strong>해지수수료 계산식</strong>
										<table class="refund-calc-table">
											<tr><td class="rct-label">전체 결제금액</td><td class="rct-value"><?php echo $_total_paid_all_disp; ?></td></tr>
											<?php if ($_ct_install_price > 0) { ?>
											<tr><td class="rct-label">− 개통비/설치비</td><td class="rct-value"><?php echo $_install_price_disp; ?></td></tr>
											<?php } ?>
											<tr><td class="rct-label">= 이용요금 합계</td><td class="rct-value"><?php echo $_subscription_fee_disp; ?></td></tr>
											<tr class="rct-ratio-row"><td colspan="2" class="rct-ratio-cell"><?php
												$_rt_rd=floor($remaining_time/86400);
												$_rt_rh=floor(($remaining_time%86400)/3600);
												$_rt_rm=floor(($remaining_time%3600)/60);
												$_rt_rs=$remaining_time%60;
												$_rt_td=$total_usage_days;
												$_rt_th=$total_usage_hours;
												$_rt_tm=$total_usage_remaining_minutes;
												echo '× 미사용비율 ('.$_rt_rd.'일 '.sprintf('%02d',$_rt_rh).'시간 '.sprintf('%02d',$_rt_rm).'분 '.sprintf('%02d',$_rt_rs).'초 / '.$_rt_td.'일 '.$_rt_th.'시간 '.$_rt_tm.'분)';
											?></td></tr>
											<tr><td class="rct-label">= 미사용요금</td><td class="rct-value"><?php echo $penalty_formula_base_disp; ?></td></tr>
											<tr><td class="rct-label">× 해지수수료율</td><td class="rct-value"><?php echo $_fee_rate_pct; ?>%</td></tr>
											<tr><td class="rct-label">= 해지수수료</td><td class="rct-value"><?php echo $penalty_amount_disp; ?></td></tr>
											<tr class="rct-result-row"><td class="rct-label">환불금액</td><td class="rct-value"><?php echo $refund_amount_after_penalty_disp; ?> Point</td></tr>
										</table>
									</div>
								</div>

							</div>
							</div>
							<div class="extend-popup-resizer"></div>
						</div>

						<script>
							document.addEventListener("DOMContentLoaded", function() {
								updateRefund('<?php echo $od_id . "_" . $item[$i]['it_id']; ?>' , '<?php echo $start_time->getTimestamp(); ?>', '<?php echo $end_time->getTimestamp(); ?>', '<?php echo $current_time->getTimestamp(); ?>', '<?php echo $paid_total_amount; ?>', '0', '0');								initRefundPopup('<?php echo $od_id . "_" . $item[$i]['it_id']; ?>');
							});
						</script>

					<?php } else { ?>
						<div class="text-center">환불완료 <?php echo apms_display_point_plain($item[$i]['real_refund_amount'])?><br><?php echo $item[$i]['real_refund_datetime']?></div>
					<?php } ?>
					</td>
					<!-- <td class="text-right"><?php echo number_format($item[$i]['opt'][$k]['point']); ?>포인트</td> -->
					<!-- <td class="text-center"><?php echo $item[$i]['opt'][$k]['ct_send_cost']; ?>포인트</td> -->
				</tr>

				<tr>
					<td colspan="11" style="padding:0px;">
						<style>
							#orderinquiryview table {
								width: 100%;
								border-collapse: collapse;
								margin-top: 0px;
								margin-bottom: 5px;
								box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
								font-size: 0.9em;
							}
							#orderinquiryview th, #orderinquiryview td {
								padding: 3px;
								text-align: left;
								border-top: 1px solid #ddd;
								border-bottom: 1px solid #ddd;
							}
							#orderinquiryview th {
								background-color: #f4f4f4;
								font-weight: bold;
								text-transform: uppercase;
							}
							#orderinquiryview tr:nth-child(even) {
								background-color: #f9f9f9;
							}
							#orderinquiryview tr:hover {
								background-color: #f1f1f1;
							}
							#orderinquiryview .center {
								text-align: center;
							}
							#orderinquiryview .right {
								text-align: right;
							}
							#orderinquiryview .nation_flag_img2 {
								width: 25px;
								height: 17px;
								margin-left: 0px;
								margin-right: 5px;
							}

							#orderinquiryview .input-with-icon {
								position: relative;
								display: inline-block;
								width: 150px; /* 원하는 너비로 설정 */
								margin-left: 10px;
								margin-bottom: 1px;
							}

							#orderinquiryview .input-with-icon input {
								width: 100%;
								padding-left: 30px; /* Adjust based on icon size and padding */
								box-sizing: border-box;
								height: 23px; /* 원하는 높이로 설정 */
								border-top: 1px solid transparent;
								border-left: 1px solid transparent;
								border-right: 1px solid transparent;
								border-bottom: 1px solid #ccc;
								font-size: 0.9em; /* 폰트 크기 */
							}

							#orderinquiryview .input-with-icon .fa {
								position: absolute;
								top: 50%;
								left: 10px; /* 아이콘 위치 조정 */
								transform: translateY(-50%);
								color: #aaa;
								font-size: 1.2em;
							}

							#orderinquiryview .input-with-icon4ip {
								position: relative;
								display: inline-block;
								width: 120px; /* 원하는 너비로 설정 */
								margin-left: 0px;
								margin-bottom: 1px;
								padding: 3px 0px 3px;
								font-size: 1.1em;
							}

							#orderinquiryview .input-with-icon4ip input {
								width: 100%;
								padding-left: 30px; /* Adjust based on icon size and padding */
								box-sizing: border-box;
								height: 23px; /* 원하는 높이로 설정 */
								border: 1px solid #ccc; /* 테두리 스타일 */
								font-size: 0.9em; /* 폰트 크기 */
							}

							#orderinquiryview .input-with-icon4ip .fa {
								position: absolute;
								top: 50%;
								left: 10px; /* 아이콘 위치 조정 */
								transform: translateY(-50%);
								color: #aaa;
								font-size: 1.2em;
							}

							#orderinquiryview label {
								display: inline-block;
								width: 150px;
								background: #000;
								color: #fff;
								text-align: center;
								padding: 3px 0 4px 0;
								margin-bottom: 1px;
								font-size: 0.9em;
							}

							#orderinquiryview label.connect-ip4ip {
								width: 120px;
								background: #6699ff;
								color: #fff;
								margin-top: 7px;
							}

							@keyframes blink {
								0% { color: #000; }
								50% { color: #ccc; }
								100% { color: #000; }
							}

							#orderinquiryview .blink-text {
								font-size: 1.1em;
								color: #E91B23;
								text-align: center;
								animation: blink 1.5s infinite;
							}
							#orderinquiryview .remote-ip-panel {
								padding: 7px 6px;
								border: 1px solid #cfd8e3;
								border-radius: 7px;
								background: #f8fbff;
							}
							#orderinquiryview .remote-ip-title {
								font-size: 11px;
								font-weight: 700;
								color: #1f2937;
								margin-bottom: 2px;
							}
							#orderinquiryview .remote-ip-value {
								font-size: 16px;
								font-weight: 800;
								letter-spacing: 0.1px;
								font-variant-numeric: tabular-nums;
								margin-bottom: 1px;
							}
							#orderinquiryview .remote-ip-help {
								font-size: 10px;
								color: #5b6472;
								line-height: 1.3;
							}
							#orderinquiryview .remote-access-mini-guide {
								margin-bottom: 5px;
								padding: 0;
								border: 1px solid #e2e8f0;
								background: #f8fafc;
								border-radius: 7px;
								font-size: 11px;
								line-height: 1.35;
								color: #334155;
							}
							#orderinquiryview .remote-access-mini-guide summary {
								cursor: pointer;
								list-style: none;
								padding: 5px 9px;
								font-weight: 700;
								user-select: none;
							}
							#orderinquiryview .remote-access-mini-guide summary::-webkit-details-marker {
								display: none;
							}
							#orderinquiryview .remote-access-mini-guide summary:before {
								content: '\25B8';
								display: inline-block;
								margin-right: 6px;
								color: #1f2937;
								transition: transform 0.15s ease;
							}
							#orderinquiryview .remote-access-mini-guide[open] summary:before {
								transform: rotate(90deg);
							}
							#orderinquiryview .remote-access-mini-guide .remote-access-guide-body {
								padding: 0 9px 6px;
								border-top: 1px dashed #d8e0ea;
							}
							#orderinquiryview .remote-access-mini-guide .remote-guide-step {
								margin-top: 6px;
								font-size: 11px;
								line-height: 1.4;
								color: #334155;
							}
							#orderinquiryview .remote-access-card {
								border: 1px solid #d7dce5;
								border-radius: 8px;
								padding: 6px 8px;
								background: #fff;
								margin-top: 4px;
							}
							#orderinquiryview .remote-access-card.expired-access {
								border-color: #f5c2c7;
								background: #fff8f8;
							}
							#orderinquiryview .remote-expired-notice {
								margin: 1px 0 6px;
								padding: 5px 8px;
								border: 1px solid #fecdd3;
								border-radius: 6px;
								background: #fff1f2;
								color: #9f1239;
								font-size: 11px;
								font-weight: 700;
								line-height: 1.35;
							}
							#orderinquiryview .remote-access-head {
								display: flex;
								justify-content: space-between;
								align-items: center;
								gap: 6px;
								margin-bottom: 4px;
							}
							#orderinquiryview .remote-program-title {
								font-size: 13px;
								font-weight: 800;
							}
							#orderinquiryview .remote-program-title-wrap {
								display: flex;
								align-items: baseline;
								flex-wrap: wrap;
								gap: 6px;
							}
							#orderinquiryview .remote-program-caption {
								font-size: 11px;
								font-weight: 600;
								color: #475569;
							}
							#orderinquiryview .remote-download-title {
								margin-top: 3px;
								font-size: 10px;
								font-weight: 700;
								color: #475569;
							}
							#orderinquiryview .remote-program-tools {
								display: inline-flex;
								align-items: center;
								gap: 5px;
							}
							#orderinquiryview .remote-site-btn {
								height: 24px;
								line-height: 22px;
								padding: 0 8px;
								border-radius: 999px;
								border: 1px solid #cbd5e1;
								background: #f8fafc;
								font-size: 10px;
								font-weight: 700;
								color: #1f2937;
								text-decoration: none;
							}
							#orderinquiryview .remote-download-wrap {
								display: flex;
								flex-wrap: wrap;
								gap: 4px;
								margin: 3px 0 2px;
							}
							#orderinquiryview .remote-manual-section {
								margin-top: 6px;
								padding: 7px;
								border: 1px solid #dbe4f0;
								border-radius: 8px;
								background: #ffffff;
							}
							#orderinquiryview .remote-manual-title {
								font-size: 11px;
								font-weight: 800;
								color: #1f2937;
								margin-bottom: 5px;
							}
							#orderinquiryview .remote-manual-tabs {
								display: flex;
								flex-wrap: wrap;
								gap: 0;
								margin-bottom: 0;
								border-bottom: 1px solid #cbd5e1;
							}
							#orderinquiryview .remote-manual-btn {
								height: 27px;
								line-height: 25px;
								padding: 0 10px;
								border-radius: 6px 6px 0 0;
								border: 1px solid #cbd5e1;
								border-bottom: 0;
								background: #f1f5f9;
								font-size: 10px;
								font-weight: 700;
								color: #334155;
								cursor: pointer;
								margin-right: 3px;
								position: relative;
								top: 1px;
							}
							#orderinquiryview .remote-manual-btn.is-active {
								background: #ffffff;
								border-color: #94a3b8;
								color: #1e3a8a;
								z-index: 1;
							}
							#orderinquiryview .remote-manual-btn .remote-os-badge {
								display: inline-block;
								margin-left: 5px;
								padding: 0 5px;
								height: 16px;
								line-height: 16px;
								border-radius: 999px;
								font-size: 9px;
								font-weight: 800;
								color: #0f766e;
								background: #ecfdf5;
								border: 1px solid #a7f3d0;
								vertical-align: middle;
							}
							#orderinquiryview .remote-manual-panel {
								display: none;
								border: 1px solid #cbd5e1;
								border-top: 0;
								border-radius: 0 0 7px 7px;
								padding: 8px;
								background: #fcfdff;
							}
							#orderinquiryview .remote-manual-panel.is-active {
								display: block;
							}
							#orderinquiryview .remote-manual-inner {
								display: grid;
								grid-template-columns: 170px 1fr;
								gap: 8px;
								align-items: start;
							}
							#orderinquiryview .remote-detail-card-cell .remote-manual-inner {
								grid-template-columns: 1fr;
							}
							#orderinquiryview .remote-detail-card-cell .remote-manual-image-wrap {
								margin-bottom: 6px;
							}
							#orderinquiryview .remote-manual-image-wrap {
								position: relative;
							}
							#orderinquiryview .remote-manual-image {
								width: 100%;
								height: auto;
								border: 1px solid #e2e8f0;
								border-radius: 6px;
								background: #fff;
							}
							#orderinquiryview .remote-manual-zoom-btn {
								position: absolute;
								right: 6px;
								top: 6px;
								height: 24px;
								line-height: 22px;
								padding: 0 7px;
								border: 1px solid #93c5fd;
								border-radius: 999px;
								background: rgba(255, 255, 255, 0.95);
								font-size: 12px;
								font-weight: 700;
								color: #1d4ed8;
								cursor: pointer;
							}
							#orderinquiryview .remote-manual-zoom-btn .fa {
								font-size: 12px;
								line-height: 1;
							}
							#orderinquiryview .remote-manual-zoom-btn:hover {
								background: #eff6ff;
							}
							.remote-manual-preview-backdrop {
								position: fixed;
								inset: 0;
								background: rgba(15, 23, 42, 0.55);
								z-index: 2200;
								opacity: 0;
								visibility: hidden;
								pointer-events: none;
								transition: opacity 0.24s cubic-bezier(0.22, 1, 0.36, 1), visibility 0s linear 0.24s;
							}
							.remote-manual-preview-backdrop.is-open {
								opacity: 1;
								visibility: visible;
								pointer-events: auto;
								transition-delay: 0s;
							}
							.remote-manual-preview-window {
								position: fixed;
								left: 50%;
								top: 50%;
								transform: translate(-50%, -50%) scale(0.86);
								width: 860px;
								height: 620px;
								max-width: 94vw;
								max-height: 90vh;
								min-width: 420px;
								min-height: 280px;
								background: #ffffff;
								border: 1px solid #cbd5e1;
								border-radius: 10px;
								box-shadow: 0 25px 60px rgba(2, 6, 23, 0.45);
								z-index: 2210;
								opacity: 0;
								visibility: hidden;
								pointer-events: none;
								transition: opacity 0.26s cubic-bezier(0.22, 1, 0.36, 1), transform 0.26s cubic-bezier(0.22, 1, 0.36, 1), left 0.26s cubic-bezier(0.22, 1, 0.36, 1), top 0.26s cubic-bezier(0.22, 1, 0.36, 1), visibility 0s linear 0.26s;
								overflow: hidden;
							}
							.remote-manual-preview-window.is-opening {
								visibility: visible;
								pointer-events: none;
								opacity: 0;
							}
							.remote-manual-preview-window.is-open {
								opacity: 1;
								visibility: visible;
								pointer-events: auto;
								transform: translate(-50%, -50%) scale(1);
								transition-delay: 0s;
							}
							.remote-manual-preview-window.is-closing {
								opacity: 0;
								visibility: visible;
								pointer-events: none;
								transform: translate(-50%, -50%) scale(0.94);
							}
							.remote-manual-preview-window.is-detached {
								transform: none !important;
								transition: opacity 0.18s ease, visibility 0s linear 0.18s;
							}
							.remote-manual-preview-window.is-detached.is-closing {
								transform: scale(0.96) !important;
								transform-origin: center center;
							}
							.remote-manual-preview-header {
								display: flex;
								align-items: center;
								justify-content: space-between;
								padding: 9px 12px;
								background: #0f172a;
								color: #f8fafc;
								cursor: move;
								user-select: none;
							}
							.remote-manual-preview-title {
								font-size: 13px;
								font-weight: 700;
							}
							.remote-manual-preview-close {
								width: 28px;
								height: 28px;
								border: 0;
								border-radius: 6px;
								background: rgba(255, 255, 255, 0.14);
								color: #ffffff;
								font-size: 18px;
								line-height: 28px;
							}
							.remote-manual-preview-body {
								height: calc(100% - 46px);
								overflow: auto;
								padding: 10px;
								background: #f8fafc;
							}
							.remote-manual-preview-image {
								width: 100%;
								height: auto;
								border: 1px solid #cbd5e1;
								border-radius: 8px;
								background: #ffffff;
							}
							.remote-manual-preview-resizer {
								position: absolute;
								right: 5px;
								bottom: 5px;
								width: 16px;
								height: 16px;
								cursor: nwse-resize;
								background: linear-gradient(135deg, transparent 0%, transparent 45%, #94a3b8 46%, #94a3b8 54%, transparent 55%, transparent 100%);
							}
							#orderinquiryview .remote-manual-steps {
								margin: 0;
								padding-left: 16px;
								font-size: 11px;
								line-height: 1.5;
								color: #334155;
							}
							#orderinquiryview .remote-manual-steps li {
								margin-bottom: 3px;
							}
							#orderinquiryview .remote-manual-tip {
								margin-top: 6px;
								padding: 5px 7px;
								border-radius: 6px;
								background: #eef6ff;
								border: 1px solid #bfdbfe;
								font-size: 10px;
								font-weight: 700;
								color: #1e3a8a;
							}
							#orderinquiryview .remote-cert-download {
								margin-bottom: 6px;
								padding: 6px 7px;
								border-radius: 7px;
								border: 1px solid #dbeafe;
								background: #f8fbff;
							}
							#orderinquiryview .remote-cert-title {
								font-size: 10px;
								font-weight: 800;
								color: #1e3a8a;
								margin-bottom: 5px;
							}
							#orderinquiryview .remote-cert-btns {
								display: flex;
								flex-wrap: wrap;
								gap: 4px;
							}
							#orderinquiryview .remote-cert-btn {
								display: inline-block;
								height: 22px;
								line-height: 20px;
								padding: 0 8px;
								border-radius: 999px;
								border: 1px solid #93c5fd;
								background: #ffffff;
								font-size: 10px;
								font-weight: 700;
								color: #1d4ed8;
								text-decoration: none;
							}
							#orderinquiryview .remote-cert-btn:hover {
								background: #eff6ff;
								text-decoration: none;
							}
							#orderinquiryview .remote-manual-download-inline {
								margin-bottom: 6px;
							}
							#orderinquiryview .remote-manual-download-empty {
								display: inline-block;
								padding: 2px 4px;
								font-size: 10px;
								font-weight: 700;
								color: #64748b;
							}
							#orderinquiryview .remote-download-btn {
								height: 22px;
								line-height: 20px;
								padding: 0 7px;
								border-radius: 999px;
								border: 1px solid #d6deea;
								background: #ffffff;
								font-size: 10px;
								font-weight: 700;
								color: #334155;
								text-decoration: none;
							}
							#orderinquiryview .remote-download-btn:hover {
								background: #f1f5f9;
								text-decoration: none;
							}
							#orderinquiryview .remote-site-btn:hover {
								background: #eef2f7;
								text-decoration: none;
							}
							#orderinquiryview .remote-status {
								font-size: 10px;
								font-weight: 700;
								padding: 2px 7px;
								border-radius: 999px;
							}
							#orderinquiryview .remote-status.active {
								color: #065f46;
								background: #ecfdf5;
								border: 1px solid #a7f3d0;
							}
							#orderinquiryview .remote-status.expired {
								color: #9f1239;
								background: #fff1f2;
								border: 1px solid #fecdd3;
							}
							#orderinquiryview .remote-credential-strip {
								display: grid;
								grid-template-columns: repeat(3, minmax(0, 1fr));
								gap: 6px;
								margin-top: 5px;
							}
							#orderinquiryview .remote-credential-item {
								border: 1px solid #dbe4f0;
								border-radius: 8px;
								background: #fbfdff;
								padding: 6px 8px;
								display: flex;
								align-items: center;
								justify-content: space-between;
								gap: 6px;
							}
							#orderinquiryview .remote-credential-main {
								display: flex;
								align-items: baseline;
								gap: 7px;
								min-width: 0;
							}
							#orderinquiryview .remote-credential-label {
								font-size: 10px;
								font-weight: 700;
								color: #475569;
								white-space: nowrap;
							}
							#orderinquiryview .remote-credential-value {
								font-size: 15px;
								font-weight: 700;
								letter-spacing: 0;
								line-height: 1.25;
								color: #0f172a;
								font-variant-numeric: tabular-nums;
								word-break: break-all;
								min-width: 0;
							}
							#orderinquiryview .remote-credential-item.is-password .remote-credential-value {
								font-size: 15px;
								letter-spacing: 0.2px;
							}
							#orderinquiryview .remote-password-scratch {
								position: relative;
								display: inline-flex;
								align-items: center;
								justify-content: center;
								min-height: 24px;
								min-width: 132px;
								padding: 2px 8px;
								border-radius: 5px;
								cursor: grab;
								overflow: hidden;
							}
							#orderinquiryview .remote-password-text {
								position: relative;
								z-index: 1;
								text-align: center;
								width: 100%;
							}
							#orderinquiryview .remote-password-canvas {
								position: absolute;
								inset: 0;
								width: 100%;
								height: 100%;
								border-radius: 4px;
								z-index: 2;
								cursor: grab;
							}
							#orderinquiryview .remote-password-scratch.is-scratching,
							#orderinquiryview .remote-password-scratch.is-scratching .remote-password-canvas {
								cursor: grabbing;
							}
							#orderinquiryview .remote-password-scratch:hover:after {
								content: attr(data-tooltip);
								position: absolute;
								left: 0;
								top: calc(100% + 5px);
								padding: 4px 7px;
								border-radius: 6px;
								background: #0f172a;
								color: #f8fafc;
								font-size: 10px;
								font-weight: 700;
								white-space: nowrap;
								z-index: 30;
								pointer-events: none;
							}
							#orderinquiryview .remote-credential-action {
								display: flex;
								justify-content: flex-end;
								flex: 0 0 auto;
							}
							#orderinquiryview .remote-field-row {
								display: grid;
								grid-template-columns: 92px 1fr;
								gap: 6px;
								align-items: start;
								padding: 7px 0 3px;
								border-top: 1px dashed #e6ebf2;
							}
							#orderinquiryview .remote-field-row:first-of-type {
								border-top: 0;
							}
							#orderinquiryview .remote-field-label {
								font-size: 11px;
								font-weight: 700;
								color: #334155;
							}
							#orderinquiryview .remote-field-value {
								font-size: 12px;
								color: #111827;
								font-variant-numeric: tabular-nums;
								word-break: break-all;
							}
							#orderinquiryview .remote-copy-btn {
								height: 22px;
								padding: 0 8px;
								border: 1px solid #cbd5e1;
								border-radius: 999px;
								background: #f8fafc;
								font-size: 10px;
								font-weight: 700;
								color: #1f2937;
								cursor: pointer;
							}
							#orderinquiryview .remote-copy-btn.copied {
								border-color: #10b981;
								background: #ecfdf5;
								color: #065f46;
							}
							#orderinquiryview .remote-copy-btn:hover {
								background: #eef2f7;
							}
							#orderinquiryview .remote-field-row.period .remote-field-value {
								font-size: 12px;
								line-height: 1.35;
								overflow-wrap: anywhere;
								word-break: break-word;
								white-space: normal;
							}
							#orderinquiryview .remote-field-row.period {
								grid-template-columns: 72px 1fr;
							}
							#orderinquiryview .remote-detail-card-cell {
								width: 350px;
								min-width: 320px;
								max-width: 350px;
							}
							#orderinquiryview .remote-detail-card-cell .remote-credential-strip {
								grid-template-columns: 1fr;
							}
							#orderinquiryview .remote-detail-card-cell .remote-credential-item {
								align-items: center;
							}
							#orderinquiryview .remote-detail-card-cell .remote-credential-main {
								width: 100%;
								justify-content: space-between;
							}
							#orderinquiryview .remote-detail-card-cell .remote-credential-value {
								word-break: normal;
								overflow-wrap: anywhere;
							}
							#orderinquiryview .remote-detail-card-cell .remote-password-scratch {
								min-width: 118px;
								max-width: 100%;
							}
							#orderinquiryview .remote-detail-history-cell {
								width: auto;
								min-width: 420px;
							}
							#orderinquiryview .remote-period-range,
							#orderinquiryview .remote-period-remain {
								display: block;
								max-width: 100%;
								overflow-wrap: anywhere;
								word-break: break-word;
							}
							@media (max-width: 900px) {
								#orderinquiryview .remote-password-scratch:hover:after {
									display: none;
								}
							}
							@media (max-width: 1200px) {
								#orderinquiryview .remote-credential-strip {
									grid-template-columns: repeat(2, minmax(0, 1fr));
								}
							}
							@media (max-width: 700px) {
								#orderinquiryview .remote-access-card {
									max-width: 350px;
									margin-left: 0;
									margin-right: 0;
								}
								#orderinquiryview .remote-detail-card-cell {
									width: 350px;
									min-width: 320px;
									max-width: 350px;
								}
								#orderinquiryview .remote-field-row.period {
									grid-template-columns: 62px 1fr;
								}
								#orderinquiryview .remote-credential-strip {
									grid-template-columns: 1fr;
								}
								#orderinquiryview .remote-credential-item {
									align-items: flex-start;
								}
								#orderinquiryview .remote-credential-main {
									width: 100%;
									justify-content: space-between;
								}
								#orderinquiryview .remote-manual-inner {
									grid-template-columns: 1fr;
								}
							}
							@media (orientation: landscape) and (hover: none) and (pointer: coarse) {
								#orderinquiryview .remote-detail-row > td {
									display: table-cell !important;
									vertical-align: top;
								}
								#orderinquiryview .remote-detail-card-cell {
									width: 350px !important;
									min-width: 320px !important;
									max-width: 350px !important;
								}
								#orderinquiryview .remote-detail-history-cell {
									width: auto !important;
									min-width: 420px !important;
									padding-top: 10px !important;
								}
								#orderinquiryview .remote-detail-card-cell .remote-access-card {
									max-width: 350px;
								}
							}
							#orderinquiryview .vpn-service-summary {
								font-size: 12px;
								line-height: 1.45;
								text-align: left;
								padding: 4px 8px;
							}
							#orderinquiryview .vpn-service-summary strong {
								color: #1f2937;
							}
							[data-site-theme="dark"] #orderinquiryview .vpn-service-summary {
								color: #c4c4cc !important;
							}
							[data-site-theme="dark"] #orderinquiryview .vpn-service-summary strong {
								color: #e4e4e7 !important;
							}
							#orderinquiryview .vpn-device-badges {
								display: inline-flex;
								flex-wrap: wrap;
								gap: 4px;
								vertical-align: middle;
							}
							#orderinquiryview .vpn-device-badge {
								display: inline-block;
								padding: 1px 7px;
								border-radius: 999px;
								border: 1px solid #d4dce7;
								background: #f8fafc;
								font-size: 10px;
								font-weight: 700;
								color: #334155;
								line-height: 1.5;
							}

							@media screen and (max-width: 600px) {
								#orderinquiryview .flags-icons img {
									max-height: 30px;
									margin-right: 3px;
								}
								#orderinquiryview .nation_flag_img2 {
									width: 25px;
									height: 17px;
									margin-left: 0px;
									margin-right: 5px;
								}
							}
							/* ── 다크모드 ── */
							[data-site-theme="dark"] #orderinquiryview,
							[data-site-theme="dark"] #orderinquiryview table {
								background-color: #18181e !important;
								border-color: #454552;
							}
							[data-site-theme="dark"] #orderinquiryview tr {
								background-color: #18181e !important;
							}
							[data-site-theme="dark"] #orderinquiryview th,
							[data-site-theme="dark"] #orderinquiryview td {
								border-top-color: #454552 !important;
								border-bottom-color: #454552 !important;
								background-color: #18181e !important;
								color: #e4e4e7 !important;
							}
							[data-site-theme="dark"] #orderinquiryview th {
								background-color: #252528 !important;
								color: #e4e4e7 !important;
							}
							[data-site-theme="dark"] #orderinquiryview tr:nth-child(even) td {
								background-color: #1d1d24 !important;
							}
							[data-site-theme="dark"] #orderinquiryview tr:hover td,
							[data-site-theme="dark"] #orderinquiryview tr:hover th {
								background-color: #252530 !important;
							}
							[data-site-theme="dark"] #orderinquiryview label {
								background: #1a1a1f !important;
								border-color: #3a3a42 !important;
							}
							[data-site-theme="dark"] #orderinquiryview .remote-ip-panel {
								background: #0f1929 !important;
								border-color: #2d3d52 !important;
							}
							[data-site-theme="dark"] #orderinquiryview .remote-ip-title { color: #c4c4cc !important; }
							[data-site-theme="dark"] #orderinquiryview .remote-ip-help { color: #9ca3af !important; }
							[data-site-theme="dark"] #orderinquiryview .remote-access-mini-guide {
								background: #1a1a20 !important;
								border-color: #3a3a42 !important;
								color: #c4c4cc !important;
							}
							[data-site-theme="dark"] #orderinquiryview .remote-access-mini-guide summary { color: #c4c4cc !important; }
							[data-site-theme="dark"] #orderinquiryview .remote-access-guide-body { border-top-color: #3a3a42 !important; }
							[data-site-theme="dark"] #orderinquiryview .remote-access-card {
								background: #18181e !important;
								border-color: #3a3a42 !important;
							}
							[data-site-theme="dark"] #orderinquiryview .remote-access-card.expired-access {
								background: #1e1216 !important;
								border-color: #4a2530 !important;
							}
							[data-site-theme="dark"] #orderinquiryview .remote-expired-notice {
								background: #2d0f14 !important;
								border-color: #7f1d1d !important;
								color: #fca5a5 !important;
							}
							[data-site-theme="dark"] #orderinquiryview .remote-program-title { color: #e4e4e7 !important; }
							[data-site-theme="dark"] #orderinquiryview .remote-access-head { color: #e4e4e7 !important; }
							[data-site-theme="dark"] #orderinquiryview .remote-manual-section {
								background: #18181e !important;
								border-color: #3a3a42 !important;
							}
							[data-site-theme="dark"] #orderinquiryview .remote-manual-btn {
								background: #252528 !important;
								border-color: #4a4a52 !important;
								color: #c4c4cc !important;
							}
							[data-site-theme="dark"] #orderinquiryview .remote-manual-btn:hover {
								background: #2e2e36 !important;
								color: #e4e4e7 !important;
							}
							[data-site-theme="dark"] #orderinquiryview .remote-manual-btn.is-active {
								background: #1e2535 !important;
								border-color: #3d5a80 !important;
								color: #93c5fd !important;
							}
							[data-site-theme="dark"] #orderinquiryview .remote-manual-badge {
								background: #0d2d1e !important;
								border-color: #1a5c38 !important;
								color: #6ee7b7 !important;
							}
							[data-site-theme="dark"] #orderinquiryview .remote-manual-panel {
								background: #161620 !important;
								border-color: #3a3a42 !important;
							}
							[data-site-theme="dark"] #orderinquiryview .remote-manual-image {
								background: #1e1e24 !important;
								border-color: #3a3a42 !important;
							}
							[data-site-theme="dark"] #orderinquiryview .remote-manual-zoom-btn {
								background: rgba(15,25,40,0.92) !important;
								border-color: #3a5a80 !important;
								color: #93c5fd !important;
							}
							[data-site-theme="dark"] #orderinquiryview .remote-manual-steps { color: #c4c4cc !important; }
							[data-site-theme="dark"] #orderinquiryview .remote-manual-tip {
								background: #1a2035 !important;
								border-color: #2d4270 !important;
								color: #93c5fd !important;
							}
							[data-site-theme="dark"] #orderinquiryview .remote-cert-download {
								background: #0f1929 !important;
								border-color: #2d4270 !important;
							}
							[data-site-theme="dark"] #orderinquiryview .remote-cert-title { color: #93c5fd !important; }
							[data-site-theme="dark"] #orderinquiryview .remote-cert-btn {
								background: #1e1e24 !important;
								border-color: #3a5a80 !important;
								color: #93c5fd !important;
							}
							[data-site-theme="dark"] #orderinquiryview .remote-cert-btn:hover { background: #1a2435 !important; }
							[data-site-theme="dark"] #orderinquiryview .remote-download-btn {
								background: #252528 !important;
								border-color: #4a4a52 !important;
								color: #c4c4cc !important;
							}
							[data-site-theme="dark"] #orderinquiryview .remote-download-btn:hover { background: #363640 !important; }
							[data-site-theme="dark"] #orderinquiryview .remote-site-btn {
								border-color: #4a4a52 !important;
								background: #252528 !important;
								color: #c4c4cc !important;
							}
							[data-site-theme="dark"] #orderinquiryview .remote-site-btn:hover { background: #363640 !important; }
							[data-site-theme="dark"] #orderinquiryview .remote-credential-item {
								background: #18181e !important;
								border-color: #3a3a42 !important;
							}
							[data-site-theme="dark"] #orderinquiryview .remote-credential-label { color: #9ca3af !important; }
							[data-site-theme="dark"] #orderinquiryview .remote-credential-value { color: #e4e4e7 !important; }
							[data-site-theme="dark"] #orderinquiryview .remote-field-row { border-top-color: #3a3a42 !important; }
							[data-site-theme="dark"] #orderinquiryview .remote-field-label { color: #9ca3af !important; }
							[data-site-theme="dark"] #orderinquiryview .remote-field-value { color: #e4e4e7 !important; }
							[data-site-theme="dark"] #orderinquiryview .remote-copy-btn {
								background: #252528 !important;
								border-color: #4a4a52 !important;
								color: #c4c4cc !important;
							}
							[data-site-theme="dark"] #orderinquiryview .remote-copy-btn.copied {
								background: #0d2d1e !important;
								border-color: #1a5c38 !important;
								color: #6ee7b7 !important;
							}
							[data-site-theme="dark"] #orderinquiryview .remote-download-title { color: #9ca3af !important; }
							[data-site-theme="dark"] #orderinquiryview .remote-program-caption { color: #9ca3af !important; }
						</style>

						<div id="orderinquiryview">
							<?php
								$item_name_upper_for_spec = strtoupper(trim((string)$item[$i]['it_name'] . ' ' . (string)$item[$i]['pt_it']));
								$is_vpn_spec_view = (strpos($item_name_upper_for_spec, 'VPN') !== false && strpos($item_name_upper_for_spec, 'RPC') === false);
							?>
							<table id="table">
								<tr>
									<!-- <th>PC No.</th>
									<th>DAILY FEE</th>
									<th>DAILY EXT. FEE</th> -->
									<th class='center' style='width:140px; max-width:140px !important;'>IP할당국가</th>
									<?php if ($is_vpn_spec_view) { ?>
										<th class='center' colspan='5'>VPN 서비스 정보</th>
									<?php } else { ?>
										<th class='center'>CPU</th>
										<th class='center'>GPU</th>
										<th class='center'>RAM</th>
										<th class='center'>SSD</th>
										<th class='center'>HDD</th>
									<?php } ?>
								</tr>
								<?php
									$spec_rows = array();
									$result_api_data = sql_query("SELECT * FROM {$g5['g5_shop_item_table']} WHERE it_id='{$item[$i]['it_id']}'");
									while($it_data_row = sql_fetch_array($result_api_data)) {
										$spec_rows[] = $it_data_row;
									}

									// 1차 조회 실패 시 상품명 기반으로 1건 재조회 (주문 시점 it_id와 현재 상품 it_id 불일치 대응)
									if (count($spec_rows) === 0) {
										$item_name_for_like = trim((string)$item[$i]['it_name']);
										$pc_no = '';
										if (preg_match('/([0-9]{3,})/', $item_name_for_like, $m_pc)) {
											$pc_no = $m_pc[1];
										}
										if ($pc_no !== '') {
											$result_api_data_fallback = sql_query("SELECT * FROM {$g5['g5_shop_item_table']} WHERE it_name LIKE '%{$pc_no}%' ORDER BY it_id DESC LIMIT 1");
											if ($it_data_fallback = sql_fetch_array($result_api_data_fallback)) {
												$spec_rows[] = $it_data_fallback;
											}
										}
									}

									// 최종 fallback: 최소 1개 기본행 보장 (헤더만 보이는 현상 방지)
									if (count($spec_rows) === 0) {
										$_fb = array(
											'it_id' => $item[$i]['it_id'],
											'it_origin_mgr_from_api' => '',
											'pt_id' => '',
											'it_spec_remote_sw' => '[]',
											'it_spec_from_datetime' => '',
											'it_spec_to_datetime' => '',
											'it_spec_remote_ip_country_code' => '',
											'it_spec_cpu' => '', 'it_spec_mainboard' => '',
											'it_spec_ram_type' => '', 'it_spec_ram' => '',
											'it_spec_ssd_type' => '', 'it_spec_ssd' => '',
											'it_spec_hdd_type' => '', 'it_spec_hdd' => '',
											'it_spec_gpu' => '', 'it_spec_os' => '',
											'it_spec_keyboard' => '', 'it_spec_mouse' => ''
										);
										// VPN 상품이면 provision queue에서 서비스 정보 복원
										if (strpos(strtoupper((string)$item[$i]['it_name']), 'VPN') !== false) {
											$_pq_fb = sql_fetch("SELECT protocol, server_ip, created_at, last_response FROM app_ikev2_provision_queue WHERE it_id='{$item[$i]['it_id']}' AND od_id='$od_id' ORDER BY queue_id DESC LIMIT 1", false);
											if ($_pq_fb) {
												$_pq_resp_fb = json_decode((string)$_pq_fb['last_response'], true);
												$_pq_expire_fb = (!empty($_pq_resp_fb['data']['expire'])) ? $_pq_resp_fb['data']['expire'] : '';
												$_pq_sw = array(array(
													'Program__0' => $_pq_fb['protocol'],
													'RemoteIP__0' => $_pq_fb['server_ip'],
												));
												// 서버 IP → 국가코드 매핑 (vpnid_list.server_name)
												$_iso3_map = array('KOR'=>'KR','USA'=>'US','JPN'=>'JP','CHN'=>'CN','GBR'=>'GB','DEU'=>'DE','FRA'=>'FR','NLD'=>'NL','SGP'=>'SG','HKG'=>'HK','AUS'=>'AU','CAN'=>'CA','IND'=>'IN','TWN'=>'TW','THA'=>'TH','VNM'=>'VN','BRA'=>'BR','MEX'=>'MX','RUS'=>'RU','ITA'=>'IT','ESP'=>'ES','POL'=>'PL','SWE'=>'SE','NOR'=>'NO','IDN'=>'ID','MYS'=>'MY','PHL'=>'PH','TUR'=>'TR','UKR'=>'UA');
												$_vl_row = sql_fetch("SELECT country_name_short, country_name FROM vpnid_list WHERE server_name='" . sql_escape_string($_pq_fb['server_ip']) . "' AND country_name_short != '' LIMIT 1", false);
												if (!empty($_vl_row['country_name_short'])) {
													$_iso3 = strtoupper(trim($_vl_row['country_name_short']));
													$_iso2 = isset($_iso3_map[$_iso3]) ? $_iso3_map[$_iso3] : (strlen($_iso3) === 2 ? $_iso3 : '');
													if ($_iso2 !== '') {
														$_pq_sw[0]['RemoteIP_CountryCode__0'] = $_iso2;
														$_pq_sw[0]['RemoteIP_CountryName__0'] = trim((string)$_vl_row['country_name']);
														$_fb['it_spec_remote_ip_country_code'] = $_iso2;
													}
												}
												$_fb['it_spec_remote_sw'] = json_encode($_pq_sw, JSON_UNESCAPED_UNICODE);
												$_fb['it_spec_from_datetime'] = (string)$_pq_fb['created_at'];
												$_fb['it_spec_to_datetime'] = $_pq_expire_fb;
											}
										}
										$spec_rows[] = $_fb;
									}

									foreach($spec_rows as $it_data){
										$it_id = $it_data['it_id'];
										if ($it_data['it_origin_mgr_from_api']) {
											// comviewers.comŽRnDŽRnD서버실
											$M_store_arr = explode("Ž", $it_data['it_origin_mgr_from_api']);
											$M_storeid = $M_store_arr[0] . " ". $M_store_arr[1];
											$M_storename = $M_store_arr[2];
										} else {
											$M_storeid = "";
											$M_storename = "";
										}

										$pt_id = $it_data['pt_id']; // partner id

										$it_spec_from_datetime = $it_data['it_spec_from_datetime'];
										$it_spec_to_datetime = $it_data['it_spec_to_datetime'];
										$current_datetime = G5_TIME_YMDHIS;
										$remain_seconds = strtotime($it_spec_to_datetime) - strtotime($current_datetime);
										// 남은 시간이 0보다 작은 경우 0으로 설정
										if ($remain_seconds < 0) {
											$remain_seconds = 0;
										}
										$is_access_expired = ($remain_seconds <= 0);
										?>

										<?php
											// 원격접속정보 JSON 데이터 수집
											$jsonData_it_spec_remote_sw = $it_data['it_spec_remote_sw'];

											// JSON 데이터를 배열로 디코드 (비정상 JSON 대응)
											$dataArray_it_spec_remote_sw = json_decode($jsonData_it_spec_remote_sw, true);
											if (!is_array($dataArray_it_spec_remote_sw)) {
												$dataArray_it_spec_remote_sw = array();
											}

											$remote_ip = "";
											$remote_ip_country_code = "";
											$remote_ip_country_name = "-";
											$remote_ip_city_name = "";
											$remote_ip_country_flag = "";
											if (isset($dataArray_it_spec_remote_sw[0]) && is_array($dataArray_it_spec_remote_sw[0])) {
												$remote_ip = isset($dataArray_it_spec_remote_sw[0]['RemoteIP__0']) ? $dataArray_it_spec_remote_sw[0]['RemoteIP__0'] : "";
												$remote_ip_country_code = isset($dataArray_it_spec_remote_sw[0]['RemoteIP_CountryCode__0']) ? strtolower((string)$dataArray_it_spec_remote_sw[0]['RemoteIP_CountryCode__0']) : "";
												$remote_ip_country_name = isset($dataArray_it_spec_remote_sw[0]['RemoteIP_CountryName__0']) && trim((string)$dataArray_it_spec_remote_sw[0]['RemoteIP_CountryName__0']) !== "" ? $dataArray_it_spec_remote_sw[0]['RemoteIP_CountryName__0'] : "-";
												$remote_ip_city_name = isset($dataArray_it_spec_remote_sw[0]['RemoteIP_City__0']) ? $dataArray_it_spec_remote_sw[0]['RemoteIP_City__0'] : "";
												if ($remote_ip_country_code !== "") {
													$remote_ip_country_flag = "<img src='" . G5_DATA_URL . "/item/img_nation_flag/svg/{$remote_ip_country_code}.svg' class='nation_flag_img2'>";
												}
											}
											// 폴백 1: it_spec_remote_ip_country_code 컬럼 (JSON에 없는 경우)
											if ($remote_ip_country_code === "" && !empty($it_data['it_spec_remote_ip_country_code'])) {
												$remote_ip_country_code = strtolower((string)$it_data['it_spec_remote_ip_country_code']);
												$remote_ip_country_flag = "<img src='" . G5_DATA_URL . "/item/img_nation_flag/svg/{$remote_ip_country_code}.svg' class='nation_flag_img2'>";
												if ($remote_ip_country_name === '-') {
													$remote_ip_country_name = strtoupper($remote_ip_country_code);
												}
											}
											$vpn_program_names = array();
											for ($r_program=0; $r_program < count($dataArray_it_spec_remote_sw); $r_program++) {
												$program_name = isset($dataArray_it_spec_remote_sw[$r_program]['Program__'.$r_program]) ? trim((string)$dataArray_it_spec_remote_sw[$r_program]['Program__'.$r_program]) : '';
												if ($program_name !== '') {
													$vpn_program_names[] = $program_name;
												}
											}
											$vpn_program_names = array_values(array_unique($vpn_program_names));
											$vpn_program_text = (count($vpn_program_names) > 0) ? implode(', ', $vpn_program_names) : '-';
											$item_name_upper_label = strtoupper((string)$item[$i]['it_name']);
											$connect_ip_label = isset($order_connect_ip_label_default) ? $order_connect_ip_label_default : 'IP Address';
											if (strpos($item_name_upper_label, 'VPN') !== false && strpos($item_name_upper_label, 'RPC') === false) {
												$connect_ip_label = 'VPN IP Address';
											} else if (strpos($item_name_upper_label, 'RPC') !== false || strpos($item_name_upper_label, 'REMOTE') !== false) {
												$connect_ip_label = 'Service IP Address';
											}

											$is_masked_access = ($is_refunded || $is_access_expired);
											$remote_ip_for_panel = trim((string)$remote_ip);
											if ($is_masked_access) {
												$remote_ip_for_panel = ($remote_ip_for_panel !== '') ? '***.***.***.***' : '-';
											}

											$remote_ip_panel_title = htmlspecialchars($connect_ip_label, ENT_QUOTES);
											$remote_ip_panel_value = htmlspecialchars($remote_ip_for_panel !== '' ? $remote_ip_for_panel : '-', ENT_QUOTES);
											$remote_ip_panel_help = $is_refunded
												? '중도해지된 주문은 접속정보가 자동으로 숨김 처리됩니다.'
												: '원격제어 프로그램의 서버/IP 입력란에 위 주소를 입력해 주세요.';
											$remote_ip_panel_help = htmlspecialchars($remote_ip_panel_help, ENT_QUOTES);
											$remote_access_panel_html = "
												<div class='remote-ip-panel'>
													<div class='remote-ip-title'>{$remote_ip_panel_title}</div>
													<div class='remote-ip-value'>{$remote_ip_panel_value}</div>
													<div class='remote-ip-help'>{$remote_ip_panel_help}</div>
												</div>";

											$remote_access_cards_html_arr = array();
											for ($r=0; $r < count($dataArray_it_spec_remote_sw); $r++) {
												$remote_program = isset($dataArray_it_spec_remote_sw[$r]['Program__'.$r]) ? trim((string)$dataArray_it_spec_remote_sw[$r]['Program__'.$r]) : '';
												$remote_program_id = isset($dataArray_it_spec_remote_sw[$r][$remote_program.'_ID__'.$r]) ? trim((string)$dataArray_it_spec_remote_sw[$r][$remote_program.'_ID__'.$r]) : '';
												$remote_program_pwd = isset($dataArray_it_spec_remote_sw[$r][$remote_program.'_PWD__'.$r]) ? trim((string)$dataArray_it_spec_remote_sw[$r][$remote_program.'_PWD__'.$r]) : '';

												if (!$is_refunded && ($remote_program_id === '' || $remote_program_pwd === '')) {
													continue;
												}

												$program_disp = ($remote_program !== '') ? $remote_program : '원격제어 프로그램';
												$id_disp = $is_masked_access ? '********' : (($remote_program_id !== '') ? $remote_program_id : '-');
												$pwd_disp = $is_masked_access ? '********' : (($remote_program_pwd !== '') ? $remote_program_pwd : '-');
												$ip_disp = ($remote_ip_for_panel !== '') ? $remote_ip_for_panel : '-';
												$status_class = (!$is_refunded && $remain_seconds > 0) ? 'active' : 'expired';
												$status_text = $is_refunded ? '중도해지 환불' : (($remain_seconds > 0) ? '이용 가능' : '계약기간 만료');
												$period_from_disp = htmlspecialchars($it_data['it_spec_from_datetime'], ENT_QUOTES);
												$period_to_disp = htmlspecialchars($it_data['it_spec_to_datetime'], ENT_QUOTES);
												$remain_expired_label = $is_refunded ? '중도해지되어 접속이 종료되었습니다' : '계약기간이 종료되었습니다';
												$vpn_service_summary_html = "<strong>VPN종류:</strong> " . htmlspecialchars($vpn_program_text, ENT_QUOTES) . " &nbsp;|&nbsp; <strong>이용 가능 기간:</strong> {$period_from_disp} ~ {$period_to_disp} &nbsp;|&nbsp; <strong>남은 시간:</strong> <span class='remote-remain-time' data-remaining='{$remain_seconds}' data-expired-label='{$remain_expired_label}'></span>";

												$program_esc = htmlspecialchars($program_disp, ENT_QUOTES);
												$ip_esc = htmlspecialchars($ip_disp, ENT_QUOTES);
												$id_esc = htmlspecialchars($id_disp, ENT_QUOTES);
												$pwd_esc = htmlspecialchars($pwd_disp, ENT_QUOTES);
												$program_catalog_type = $is_vpn_spec_view ? 'vpn' : 'remote';
												$program_site_url = apms_remote_program_official_url($program_disp, $program_catalog_type);
												$program_download_urls = apms_remote_program_download_urls($program_disp, $program_catalog_type);
												$program_site_btn = '';
												if ($program_site_url !== '') {
													$program_site_esc = htmlspecialchars($program_site_url, ENT_QUOTES);
													$program_site_btn = "<a href='{$program_site_esc}' target='_blank' rel='noopener noreferrer' class='remote-site-btn'>공식 사이트</a>";
												}

												$download_label_map = array(
													'windows' => 'Windows',
													'macos' => 'macOS',
													'linux' => 'Linux',
													'android' => 'Android',
													'ios' => 'iOS'
												);
												$download_order = defined('G5_IS_MOBILE') && G5_IS_MOBILE
													? array('android', 'ios', 'windows', 'macos', 'linux')
													: array('windows', 'macos', 'linux', 'android', 'ios');
												$download_btns_arr = array();
												foreach ($download_order as $download_os_key) {
													$download_url = isset($program_download_urls[$download_os_key]) ? trim((string)$program_download_urls[$download_os_key]) : '';
													if ($download_url === '') {
														continue;
													}
													$download_url_esc = htmlspecialchars($download_url, ENT_QUOTES);
													$download_os_label = isset($download_label_map[$download_os_key]) ? $download_label_map[$download_os_key] : strtoupper($download_os_key);
													$download_os_label_esc = htmlspecialchars($download_os_label, ENT_QUOTES);
													$download_btns_arr[] = "<a href='{$download_url_esc}' target='_blank' rel='noopener noreferrer' class='remote-download-btn'>{$download_os_label_esc}</a>";
												}
												$program_download_btns = '';
												$download_url_map = array();
												if (!empty($download_btns_arr)) {
													$program_download_buttons_html = "<div class='remote-download-wrap'>".implode('', $download_btns_arr)."</div>";
													if (!$is_vpn_spec_view) {
														$program_download_btns = "<div class='remote-download-title'>운영체제별 프로그램</div>{$program_download_buttons_html}";
													}
												}
												foreach ($download_label_map as $download_os_key => $download_os_label) {
													$download_url_raw = isset($program_download_urls[$download_os_key]) ? trim((string)$program_download_urls[$download_os_key]) : '';
													if ($download_url_raw !== '') {
														$download_url_esc_map = htmlspecialchars($download_url_raw, ENT_QUOTES);
														$download_label_esc_map = htmlspecialchars($download_os_label, ENT_QUOTES);
														$download_url_map[$download_os_key] = "<a href='{$download_url_esc_map}' target='_blank' rel='noopener noreferrer' class='remote-download-btn'>{$download_label_esc_map} 다운로드</a>";
													} else {
														$download_url_map[$download_os_key] = "<span class='remote-manual-download-empty'>{$download_os_label} 다운로드 준비중</span>";
													}
												}

												$manual_section_html = '';
												if ($is_vpn_spec_view) {
													$manual_base = htmlspecialchars($skin_url, ENT_QUOTES) . '/manual';
													$cert_pem_url = $manual_base . '/certs/ikev2-ca.pem';
													$cert_download_common_html = "<div class='remote-cert-download'><div class='remote-cert-title'>VPNLink IKEv2 VPN 사용을 위해 인증서를 설치하세요 (기기당 1회만 필요)</div><div class='remote-cert-btns'><a href='{$cert_pem_url}' class='remote-cert-btn' download>VPNLink 인증서 다운로드</a></div></div>";
													$manual_download_windows = isset($download_url_map['windows']) ? $download_url_map['windows'] : "<span class='remote-manual-download-empty'>Windows 다운로드 준비중</span>";
													$manual_download_macos = isset($download_url_map['macos']) ? $download_url_map['macos'] : "<span class='remote-manual-download-empty'>macOS 다운로드 준비중</span>";
													$manual_download_linux = isset($download_url_map['linux']) ? $download_url_map['linux'] : "<span class='remote-manual-download-empty'>Linux 다운로드 준비중</span>";
													$manual_download_android = isset($download_url_map['android']) ? $download_url_map['android'] : "<span class='remote-manual-download-empty'>Android 다운로드 준비중</span>";
													$manual_download_ios = isset($download_url_map['ios']) ? $download_url_map['ios'] : "<span class='remote-manual-download-empty'>iOS 다운로드 준비중</span>";
													$manual_section_html = "
														<div class='remote-manual-section'>
															<div class='remote-manual-tabs'>
																<button type='button' class='remote-manual-btn is-active' data-manual-os='windows'>Windows</button>
																<button type='button' class='remote-manual-btn' data-manual-os='macos'>macOS</button>
																<button type='button' class='remote-manual-btn' data-manual-os='linux'>Linux</button>
																<button type='button' class='remote-manual-btn' data-manual-os='android'>Android</button>
																<button type='button' class='remote-manual-btn' data-manual-os='ios'>iOS</button>
															</div>
															<div class='remote-manual-panel is-active' data-manual-os='windows'>
																<div class='remote-manual-inner'>
																	<div class='remote-manual-image-wrap'><img src='{$manual_base}/ikev2-windows.svg' alt='Windows IKEv2 설정 매뉴얼' class='remote-manual-image'><button type='button' class='remote-manual-zoom-btn' data-manual-image='{$manual_base}/ikev2-windows.svg' data-manual-title='Windows IKEv2 설정 매뉴얼' title='이미지 확대' aria-label='이미지 확대'><i class='fa fa-search-plus' aria-hidden='true'></i></button></div>
																	<div>
																		<div class='remote-manual-download-inline'>{$manual_download_windows}</div>
																		{$cert_download_common_html}
																		<ol class='remote-manual-steps'>
																			<li>인증서 파일을 다운로드하고 더블클릭하여 신뢰할 수 있는 루트 인증기관에 설치합니다.</li>
																			<li>다운로드한 IKEv2-Client를 실행 후 설치를 완료합니다.</li>
																			<li>프로그램에서 신규 연결 추가를 선택합니다.</li>
																			<li>서버(접속 IP), ID, 비밀번호를 각각 입력합니다.</li>
																			<li>프로토콜은 IKEv2를 선택하고 저장 후 연결합니다.</li>
																			<li>연결 후 공인 IP가 변경되었는지 확인합니다.</li>
																		</ol>
																		<div class='remote-manual-tip'>팁: 연결 실패 시 방화벽/보안프로그램 예외 설정 후 재시도하세요.</div>
																	</div>
																</div>
															</div>
															<div class='remote-manual-panel' data-manual-os='macos'>
																<div class='remote-manual-inner'>
																	<div class='remote-manual-image-wrap'><img src='{$manual_base}/ikev2-macos.svg' alt='macOS IKEv2 설정 매뉴얼' class='remote-manual-image'><button type='button' class='remote-manual-zoom-btn' data-manual-image='{$manual_base}/ikev2-macos.svg' data-manual-title='macOS IKEv2 설정 매뉴얼' title='이미지 확대' aria-label='이미지 확대'><i class='fa fa-search-plus' aria-hidden='true'></i></button></div>
																	<div>
																		<div class='remote-manual-download-inline'>{$manual_download_macos}</div>
																		{$cert_download_common_html}
																		<ol class='remote-manual-steps'>
																			<li>인증서 파일을 다운로드하고 키체인 접근 앱에 추가한 뒤 신뢰를 항상으로 설정합니다.</li>
																			<li>시스템 설정에서 VPN 추가 또는 설치한 클라이언트를 실행합니다.</li>
																			<li>VPN 종류를 IKEv2로 설정합니다.</li>
																			<li>서버 주소, 원격 ID, 계정(ID/PW)을 입력합니다.</li>
																			<li>적용 후 연결 버튼을 눌러 연결 상태를 확인합니다.</li>
																			<li>메뉴바 VPN 아이콘에서 연결 유지 여부를 점검합니다.</li>
																		</ol>
																		<div class='remote-manual-tip'>팁: 인증서 경고가 뜨면 서버 주소 오타 여부를 먼저 확인하세요.</div>
																	</div>
																</div>
															</div>
															<div class='remote-manual-panel' data-manual-os='linux'>
																<div class='remote-manual-inner'>
																	<div class='remote-manual-image-wrap'><img src='{$manual_base}/ikev2-linux.svg' alt='Linux IKEv2 설정 매뉴얼' class='remote-manual-image'><button type='button' class='remote-manual-zoom-btn' data-manual-image='{$manual_base}/ikev2-linux.svg' data-manual-title='Linux IKEv2 설정 매뉴얼' title='이미지 확대' aria-label='이미지 확대'><i class='fa fa-search-plus' aria-hidden='true'></i></button></div>
																	<div>
																		<div class='remote-manual-download-inline'>{$manual_download_linux}</div>
																		{$cert_download_common_html}
																		<ol class='remote-manual-steps'>
																			<li>인증서 파일을 다운로드해 /usr/local/share/ca-certificates 또는 배포판 권장 경로에 등록합니다.</li>
																			<li>네트워크 관리자 또는 strongSwan 기반 클라이언트를 준비합니다.</li>
																			<li>IKEv2 프로필 생성 후 서버 IP와 계정 정보를 입력합니다.</li>
																			<li>필요 시 인증서(또는 PSK) 설정을 추가합니다.</li>
																			<li>연결 실행 후 터미널/로그에서 상태를 확인합니다.</li>
																			<li>DNS 누수 방지 옵션을 활성화하면 안정성이 좋아집니다.</li>
																		</ol>
																		<div class='remote-manual-tip'>팁: 배포판별 설정 경로가 다를 수 있으니 공식 문서 링크를 함께 확인하세요.</div>
																	</div>
																</div>
															</div>
															<div class='remote-manual-panel' data-manual-os='android'>
																<div class='remote-manual-inner'>
																	<div class='remote-manual-image-wrap'><img src='{$manual_base}/ikev2-android.svg' alt='Android IKEv2 설정 매뉴얼' class='remote-manual-image'><button type='button' class='remote-manual-zoom-btn' data-manual-image='{$manual_base}/ikev2-android.svg' data-manual-title='Android IKEv2 설정 매뉴얼' title='이미지 확대' aria-label='이미지 확대'><i class='fa fa-search-plus' aria-hidden='true'></i></button></div>
																	<div>
																		<div class='remote-manual-download-inline'>{$manual_download_android}</div>
																		{$cert_download_common_html}
																		<ol class='remote-manual-steps'>
																			<li>인증서 파일을 다운로드 후 설정 &gt; 보안에서 인증서 설치를 진행합니다.</li>
																			<li>설정 &gt; 네트워크 및 인터넷에서 VPN 추가를 선택합니다.</li>
																			<li>VPN 유형을 IKEv2/IPSec MSCHAPv2로 선택합니다.</li>
																			<li>서버 주소, 사용자 이름, 비밀번호를 입력합니다.</li>
																			<li>저장 후 해당 프로필을 탭하여 연결합니다.</li>
																			<li>상단 상태바 VPN 아이콘이 표시되면 정상 연결입니다.</li>
																		</ol>
																		<div class='remote-manual-tip'>팁: 데이터 절약 모드가 켜져 있으면 VPN 유지가 불안정할 수 있습니다.</div>
																	</div>
																</div>
															</div>
															<div class='remote-manual-panel' data-manual-os='ios'>
																<div class='remote-manual-inner'>
																	<div class='remote-manual-image-wrap'><img src='{$manual_base}/ikev2-ios.svg' alt='iOS IKEv2 설정 매뉴얼' class='remote-manual-image'><button type='button' class='remote-manual-zoom-btn' data-manual-image='{$manual_base}/ikev2-ios.svg' data-manual-title='iOS IKEv2 설정 매뉴얼' title='이미지 확대' aria-label='이미지 확대'><i class='fa fa-search-plus' aria-hidden='true'></i></button></div>
																	<div>
																		<div class='remote-manual-download-inline'>{$manual_download_ios}</div>
																		{$cert_download_common_html}
																		<ol class='remote-manual-steps'>
																			<li>인증서 파일을 다운로드하면 설정 앱에 프로파일이 표시되며 설치 후 신뢰 설정을 완료합니다.</li>
																			<li>설정 &gt; 일반 &gt; VPN 및 기기 관리에서 VPN 추가를 선택합니다.</li>
																			<li>유형을 IKEv2로 선택합니다.</li>
																			<li>서버, 원격 ID, 사용자 인증 정보(ID/PW)를 입력합니다.</li>
																			<li>완료 후 VPN 스위치를 켜서 연결 상태를 확인합니다.</li>
																			<li>Safari에서 접속 IP 확인 페이지로 정상 연결 여부를 점검합니다.</li>
																		</ol>
																		<div class='remote-manual-tip'>팁: iOS는 절전 상태에서 VPN이 재연결될 수 있으니 알림을 확인하세요.</div>
																	</div>
																</div>
															</div>
														</div>";
												}

												$pwd_display_html = $pwd_esc;
												if (!$is_masked_access && $pwd_disp !== '-') {
													$pwd_attr_esc = htmlspecialchars($pwd_disp, ENT_QUOTES);
													$pwd_display_html = "<span class='remote-password-scratch' data-password='{$pwd_attr_esc}' data-reveal-seconds='10' data-tooltip='마우스로 클릭 후 긁으면 10초간 표시됩니다.'><span class='remote-password-text'>********</span><canvas class='remote-password-canvas'></canvas></span>";
												}
												$copy_ip_btn = (!$is_masked_access && $ip_disp !== '-') ? "<button type='button' class='remote-copy-btn' data-copy='{$ip_esc}'>복사</button>" : '';
												$copy_id_btn = (!$is_masked_access && $id_disp !== '-') ? "<button type='button' class='remote-copy-btn' data-copy='{$id_esc}'>복사</button>" : '';
												$copy_pwd_btn = (!$is_masked_access && $pwd_disp !== '-') ? "<button type='button' class='remote-copy-btn' data-copy='{$pwd_esc}'>복사</button>" : '';
												$is_expired_access_view = (!$is_refunded && $is_access_expired);
												$access_card_class = $is_expired_access_view ? 'remote-access-card expired-access' : 'remote-access-card';
												$expired_notice_html = $is_expired_access_view ? "<div class='remote-expired-notice'>이용 기간 경과로 접속 정보가 마스킹 처리되었습니다.</div>" : '';
												$guide_summary_text = $is_expired_access_view ? '운영체제별 프로그램 다운로드 및 설정 매뉴얼' : '운영체제별 프로그램 다운로드 및 설정 매뉴얼';
												$guide_summary_esc = htmlspecialchars($guide_summary_text, ENT_QUOTES);
												$program_caption = $is_vpn_spec_view ? 'IKEv2-VPN 연결에 필요한 공식 프로그램' : '서비스 이용에 필요한 공식 프로그램';
												$program_caption_esc = htmlspecialchars($program_caption, ENT_QUOTES);
												$remote_access_head_html = "<div class='remote-access-head'><div class='remote-program-title-wrap'><div class='remote-program-title'>{$program_esc}</div><div class='remote-program-caption'>{$program_caption_esc}</div></div><div class='remote-program-tools'>{$program_site_btn}<span class='remote-status {$status_class}'>{$status_text}</span></div></div>";
												if ($is_vpn_spec_view) {
													$remote_access_head_html = '';
												}
												$period_row_html = '';
												if (!$is_vpn_spec_view) {
													$period_row_html = "<div class='remote-field-row period'><div class='remote-field-label'>이용기간</div><div class='remote-field-value'><span class='remote-period-range'>시작 일시: {$period_from_disp}<br>종료 일시: {$period_to_disp}</span><span class='remote-period-remain'>남은 시간: <span class='remote-remain-time' data-remaining='{$remain_seconds}' data-expired-label='{$remain_expired_label}'></span></span></div></div>";
												}

												$remote_access_cards_html_arr[] = "
													<div class='{$access_card_class}'>
														{$expired_notice_html}
																<details class='remote-access-mini-guide'>
																	<summary>{$guide_summary_esc}</summary>
																	<div class='remote-access-guide-body'>
																		{$remote_access_head_html}
																		{$program_download_btns}
																		{$manual_section_html}
																	</div>
																</details>
															<div class='remote-credential-strip'>
																<div class='remote-credential-item'>
																	<div class='remote-credential-main'>
																		<div class='remote-credential-label'>접속 IP</div>
																		<div class='remote-credential-value'>{$ip_esc}</div>
																	</div>
																	<div class='remote-credential-action'>{$copy_ip_btn}</div>
																</div>
																<div class='remote-credential-item'>
																	<div class='remote-credential-main'>
																		<div class='remote-credential-label'>ID</div>
																		<div class='remote-credential-value'>{$id_esc}</div>
																	</div>
																	<div class='remote-credential-action'>{$copy_id_btn}</div>
																</div>
																<div class='remote-credential-item is-password'>
																	<div class='remote-credential-main'>
																		<div class='remote-credential-label'>PW</div>
																		<div class='remote-credential-value'>{$pwd_display_html}</div>
																	</div>
																	<div class='remote-credential-action'>{$copy_pwd_btn}</div>
																</div>
															</div>
														{$period_row_html}
													</div>";
											}

											$remote_access_cards_html = implode('', $remote_access_cards_html_arr);


										//$it_spec_cpu_arr = explode("Ž", trim(str_ireplace(array("(R)", "(TM)", "Intel", "AMD", "with Radeon Graphics", "with Radeon Vega Graphics", "CPU", "Core ", " Cores", "Eight-Processor"), array("", "", "", "", "", "", "", "", "C", ""), $it_data['it_spec_cpu'])));
										$it_spec_cpu = "-";
										$it_spec_cpu_arr = explode("Ž", trim(str_ireplace(array("(R)", "(TM)", "with Radeon Graphics", "with Radeon Vega Graphics", "CPU", "Core ", "Eight-Processor"), array("", "", "", "", "", "", ""), $it_data['it_spec_cpu'])));
										if (count($it_spec_cpu_arr) == 1) {
											$it_spec_cpu = $it_spec_cpu_arr[0];
										} else if (count($it_spec_cpu_arr) == 2) {
											$it_spec_cpu = "[Dual] " . $it_spec_cpu_arr[0];
										} else if (count($it_spec_cpu_arr) == 3) {
											$it_spec_cpu = "[Triple] " . $it_spec_cpu_arr[0];
										} else if (count($it_spec_cpu_arr) == 4) {
											$it_spec_cpu = "[Quad] " . $it_spec_cpu_arr[0];
										}
										if (stripos($it_spec_cpu, 'intel') !== false) {
											$logo_cpu = "<img src='" . G5_DATA_URL . "/item/img_logo/logo_intel.png' class='cpu_logo_img2'>";
										} else if (stripos($it_spec_cpu, 'amd') !== false) {
											$logo_cpu = "<img src='" . G5_DATA_URL . "/item/img_logo/logo_amd.png' class='cpu_logo_img2'>";
										} else {
											$logo_cpu = "";
										}

										// CPU 데이터
										$cpu_data = $it_data['it_spec_cpu'];

										// 정규식을 사용하여 괄호 속에 "Cores"라는 단어가 포함된 숫자를 추출
										if (preg_match('/\((\d+) Cores\)/', $cpu_data, $matches)) {
											// 추출된 숫자를 $cpu_core 변수에 저장
											$cpu_core = $matches[1];
										} else {
											// "Cores"가 포함된 문자열이 없는 경우
											$cpu_core = null;
										}
										$it_spec_mainboard = $it_data['it_spec_mainboard'];
										$it_spec_ram = trim($it_data['it_spec_ram_type'] . " " . $it_data['it_spec_ram']);
										if ($it_spec_ram === "") {
											$it_spec_ram = "-";
										}
										//$SSDinfo = $it_data['SSDinfo'];
										$it_spec_ssd =  $it_data['it_spec_ssd'] == "0" ? "<div style='width:100%; min-width:40px; text-align:left;'>Not installed</div>" : trim($it_data['it_spec_ssd_type'] . " " . $it_data['it_spec_ssd']);
										if ($it_spec_ssd === "") {
											$it_spec_ssd = "-";
										}
										//$SSD = $it_data['SSD'];
										//$HDDinfo = $it_data['HDDinfo'];
										$it_spec_hdd = $it_data['it_spec_hdd'] == "0" ? "<div style='width:100%; min-width:40px; text-align:left;'>Not installed</div>" : trim($it_data['it_spec_hdd_type'] . " " . $it_data['it_spec_hdd']);
										if ($it_spec_hdd === "") {
											$it_spec_hdd = "-";
										}
										//$HDD = $it_data['HDD'];
										$it_spec_gpu = "-";
										$it_spec_gpu_arr = explode("Ž", trim(str_ireplace(array("(R)", "(TM)"), array("", ""), $it_data['it_spec_gpu'])));
										if (count($it_spec_gpu_arr) == 1) {
											$it_spec_gpu = $it_spec_gpu_arr[0];
										} else if (count($it_spec_gpu_arr) > 1) {
											if ((strpos($it_spec_gpu_arr[0], "NVIDIA") !== false) || (strpos($it_spec_gpu_arr[0], "AMD") !== false)) {
												$it_spec_gpu = $it_spec_gpu_arr[0];
											} else if ((strpos($it_spec_gpu_arr[1], "NVIDIA") !== false) || (strpos($it_spec_gpu_arr[1], "AMD") !== false)) {
												$it_spec_gpu = $it_spec_gpu_arr[1];
											} else {
												$it_spec_gpu = $it_spec_gpu_arr[0] . "<br>" . $it_spec_gpu_arr[1];
											}
										}
										if (stripos($it_spec_gpu, 'nvidia') !== false) {
											$logo_gpu = "<img src='" . G5_DATA_URL . "/item/img_logo/logo_nvidia.png' class='gpu_logo_img2'>";
										}
										if (stripos($it_spec_gpu, 'quadro') !== false) {
											$logo_gpu = "<img src='" . G5_DATA_URL . "/item/img_logo/logo_nvidia_quadro.png' class='gpu_logo_img2'>";
										} else if (stripos($it_spec_gpu, 'geforce') !== false) {
											$logo_gpu = "<img src='" . G5_DATA_URL . "/item/img_logo/logo_nvidia_geforce.png' class='gpu_logo_img2'>";
										}

										if (stripos($it_spec_gpu, 'radeon') !== false) {
											$logo_gpu = "<img src='" . G5_DATA_URL . "/item/img_logo/logo_amd_radeon.png' class='gpu_logo_img2'>";
										} else {
											$logo_gpu = "";
										}

										//$gpu_ram = $it_data['gpu_ram'];

										//$it_spec_os = trim(str_ireplace(array("Microsoft", "Windows", "(64Bit)"), array("", "Win", ""), $it_data['it_spec_os']));
										$it_spec_os = trim($it_data['it_spec_os']);
										if (stripos($it_spec_os, 'Windows 11') !== false || stripos($it_spec_os, 'Windows11') !== false) {
											$it_spec_os = (stripos($it_spec_os, 'Microsoft') !== false) ? $it_spec_os : "Microsoft " . $it_spec_os;
											$OS_flag = "<img src='" . G5_DATA_URL . "/item/img_os/Windows11.png' class='os_img2'>";
										} else if (stripos($it_spec_os, 'Windows 10') !== false || stripos($it_spec_os, 'Windows10') !== false) {
											$it_spec_os = (stripos($it_spec_os, 'Microsoft') !== false) ? $it_spec_os : "Microsoft " . $it_spec_os;
											$OS_flag = "<img src='" . G5_DATA_URL . "/item/img_os/Windows10.png' class='os_img2'>";
										} else if (stripos($it_spec_os, 'Windows 8') !== false || stripos($it_spec_os, 'Windows8') !== false) {
											$it_spec_os = (stripos($it_spec_os, 'Microsoft') !== false) ? $it_spec_os : "Microsoft " . $it_spec_os;
											$OS_flag = "<img src='" . G5_DATA_URL . "/item/img_os/Windows8.png' class='os_img2'>";
										} else if (stripos($it_spec_os, 'Windows 7') !== false || stripos($it_spec_os, 'Windows7') !== false) {
											$it_spec_os = (stripos($it_spec_os, 'Microsoft') !== false) ? $it_spec_os : "Microsoft " . $it_spec_os;
											$OS_flag = "<img src='" . G5_DATA_URL . "/item/img_os/Windows7.png' class='os_img2'>";
										} else if (stripos($it_spec_os, 'Windows Server 2016') !== false) {
											$it_spec_os = (stripos($it_spec_os, 'Microsoft') !== false) ? $it_spec_os : "Microsoft " . $it_spec_os;
											$OS_flag = "<img src='" . G5_DATA_URL . "/item/img_os/WindowsServer2016.png' class='os_img2'>";
										} else {
											$OS_flag = "";
										}

										// $rantal_fee_type = $it_data['rantal_fee_type'];
										// $rental_fee = $it_data['rental_fee'];
										// $rental_setting_fee = $it_data['rental_setting_fee'];
										// $rental_fee_first_daily = round(($rental_fee + $rental_setting_fee) / 30);
										// $rental_fee_ext_daily = round(($rental_fee) / 30);
										// $rental_stat = $it_data['rental_stat'];
										// $client_number = $it_data['client_number'];
										// $cpu_clock = $it_data['cpu_clock'];
										// $AppVer = $it_data['AppVer'];

										$it_spec_keyboard = !empty(trim($it_data['it_spec_keyboard'])) ? "KEYBOARD(O)" : "KEYBOARD(X)";
										$it_spec_mouse = !empty(trim($it_data['it_spec_mouse'])) ? "MOUSE(O)" : "MOUSE(X)";

										// Initialize the array
										$it_spec_device_arr = [];

										// Check if $it_spec_keyboard is not empty and add to array
										if (!empty(trim($it_spec_keyboard))) {
											$it_spec_device_arr[] = $it_spec_keyboard;
										}

										// Check if $it_spec_mouse is not empty and add to array
										if (!empty(trim($it_spec_mouse))) {
											$it_spec_device_arr[] = $it_spec_mouse;
										}

										// Join array elements with a comma if there are multiple elements
										$it_spec_devices = (count($it_spec_device_arr) > 0) ? implode(', ', $it_spec_device_arr) : "KEYBOARD(X) MOUSE(X)";


										echo "<tr>";
										// echo "<td class='center'>".$no."</td>";
										// echo "<td class='center'>".number_format($rental_fee_first_daily)." Point"."</td>";
										// echo "<td class='center'>".number_format($rental_fee_ext_daily)." Point"."</td>";
										echo "<td class='center'>".$remote_ip_country_flag.$remote_ip_country_name."</td>";
										if ($is_vpn_spec_view) {
											echo "<td class='vpn-service-summary' colspan='5'>{$vpn_service_summary_html}</td>";
										} else {
											echo "<td class='center'>".$it_spec_cpu."</td>";
											echo "<td class='center'>".$it_spec_gpu."</td>";
											echo "<td class='center'>".$it_spec_ram."</td>";
											echo "<td class='center'>".$it_spec_ssd."</td>";
											echo "<td class='center'>".$it_spec_hdd."</td>";
										}
										echo "</tr>";

										echo "<tr class='remote-detail-row' style='vertical-align: top;'>";
										$remote_access_colspan = 2;
										if (trim($remote_access_cards_html) === '' && !$is_refunded) {
											echo "<td class='remote-detail-card-cell' colspan='{$remote_access_colspan}' style='vertical-align:middle; font-size:1.05rem; color:#b91c1c; text-align:left; line-height:1.5; padding:10px;'><strong>원격접속 정보가 아직 준비되지 않았습니다.</strong><br>잠시 후 새로고침해 주세요. 계속 표시되면 고객센터로 문의해 주세요.</td>";
										} else if (trim($remote_access_cards_html) === '' && $is_refunded) {
											echo "<td class='remote-detail-card-cell' colspan='{$remote_access_colspan}' style='vertical-align:middle; font-size:1.0rem; color:#475569; text-align:left; line-height:1.5; padding:10px;'><strong>중도해지 환불 처리된 주문입니다.</strong><br>접속정보는 보안상 마스킹 처리됩니다.</td>";
										} else {
											echo "<td class='remote-detail-card-cell' colspan='{$remote_access_colspan}' style='font-size:0.98rem; padding:6px 8px;'>{$remote_access_cards_html}</td>";
										}

										$extension_history_raw = isset($item[$i]['extension_of_period_date']) ? trim((string)$item[$i]['extension_of_period_date']) : '';
										$refund_history_datetime = isset($item[$i]['real_refund_datetime']) ? trim((string)$item[$i]['real_refund_datetime']) : '';
										$refund_history_amount = isset($item[$i]['real_refund_amount']) ? (float)$item[$i]['real_refund_amount'] : 0;
										$has_extension_history = ($extension_history_raw !== '');
										$has_refund_history = ($refund_history_datetime !== '' && $refund_history_datetime !== '0000-00-00 00:00:00');

										if (!$has_extension_history && !$has_refund_history) {
											echo "<td class='remote-detail-history-cell' colspan='4' style='vertical-align:middle; font-size:1.1em; padding:10px; width:100%;'>계약연장 기록이 없습니다.</td>";
										} else {
											echo "<td class='remote-detail-history-cell' colspan='4' style='font-size:1.1em; padding:10px; width:100%;'>";

											$extension_of_period_date_arr = $has_extension_history ? explode("\n", (string)$item[$i]['extension_of_period_date']) : array();
											$extension_of_period_to_datetime_arr = $has_extension_history ? explode("\n", (string)$item[$i]['extension_of_period_to_datetime']) : array();
											$extension_of_period_days_arr = $has_extension_history ? explode("\n", (string)$item[$i]['extension_of_period_days']) : array();
											$extension_of_period_hours_arr = $has_extension_history ? explode("\n", (string)$item[$i]['extension_of_period_hours']) : array();
											$extension_of_period_price_arr = $has_extension_history ? explode("\n", (string)$item[$i]['extension_of_period_price']) : array();
											echo "<table style='width:100%;'>";
											echo "<tr>";
											echo "<th style='width:auto; text-align:center;'>구분</th>";
											echo "<th style='width:auto; text-align:center;'>결제일시</th>";
											echo "<th style='width:auto; text-align:center;'>종료일시</th>";
											echo "<th style='width:auto; text-align:center;'>계약일수</th>";
											echo "<th style='width:auto; text-align:center;'>처리금액</th>";
											echo "</tr>";

											for ($h=0; $h<count($extension_of_period_date_arr); $h++) {
												if (trim($extension_of_period_date_arr[$h]) == "") {
													continue;
												}
												echo "<tr>";
												if ($h == 0) {
													echo "<td style='width:auto; text-align:center;'>신규</td>";
												} else {
													echo "<td style='width:auto; text-align:center;'>연장</td>";
												}
												echo "<td style='width:auto; text-align:center;'>{$extension_of_period_date_arr[$h]}</td>";
												echo "<td style='width:auto; text-align:center;'>{$extension_of_period_to_datetime_arr[$h]}</td>";
												$ext_period_hours = apms_contract_hours_from_day_hour((int)$extension_of_period_days_arr[$h], (int)$extension_of_period_hours_arr[$h]);
												echo "<td style='width:auto; text-align:center;'>".apms_contract_hours_text($ext_period_hours)."</td>";
												echo "<td style='width:auto; text-align:right;'>".number_format($extension_of_period_price_arr[$h])."</td>";
												echo "</tr>";
											}

											if ($has_refund_history) {
												echo "<tr>";
												echo "<td style='width:auto; text-align:center;'>해지</td>";
												echo "<td style='width:auto; text-align:center;'>{$refund_history_datetime}</td>";
												echo "<td style='width:auto; text-align:center;'>{$refund_history_datetime}</td>";
												echo "<td style='width:auto; text-align:center;'>-</td>";
												echo "<td style='width:auto; text-align:right;'>" . number_format($refund_history_amount) . "</td>";
												echo "</tr>";
											}
											echo "</table>";
											echo "</td>";
										}

										echo "</tr>";

									}
								?>
							</table>
						</div>
					</td>
				</tr>
			<?php } ?>
		<?php } ?>
	<?php } ?>
	</tbody>
	</table>
</div>

<div class="well">
	<div class="row">
		<div class="col-xs-6">주문총액 (신규)</div>
		<div class="col-xs-6 text-right">
			<strong><?php echo number_format($od['od_cart_price']); ?></strong>
		</div>

		<?php if($od['od_receipt_point_for_extension_of_period'] > 0) { ?>
			<div class="col-xs-6">주문총액 (연장주문)</div>
			<div class="col-xs-6 text-right">
				<strong><?php echo number_format($od['od_receipt_point_for_extension_of_period']); ?></strong>
			</div>
		<?php } ?>

		<?php if($od['od_cart_coupon'] > 0) { ?>
			<div class="col-xs-6 blue">개별상품 쿠폰할인</div>
			<div class="col-xs-6 text-right blue">
				<strong>-<?php echo number_format($od['od_cart_coupon']); ?></strong>
			</div>
		<?php } ?>
		<?php if($od['od_coupon'] > 0) { ?>
			<div class="col-xs-6 blue">주문금액 쿠폰할인</div>
			<div class="col-xs-6 text-right blue">
				<strong>-<?php echo number_format($od['od_coupon']); ?></strong>
			</div>
		<?php } ?>

		<?php if ($od['od_send_cost'] > 0) { ?>
			<div class="col-xs-6">배송비</div>
			<div class="col-xs-6 text-right">
				<strong><?php echo number_format($od['od_send_cost']); ?></strong>
			</div>
		<?php } ?>

		<?php if($od['od_send_coupon'] > 0) { ?>
			<div class="col-xs-6 blue">배송비 쿠폰할인</div>
			<div class="col-xs-6 text-right blue">
				<strong>-<?php echo number_format($od['od_send_coupon']); ?></strong>
			</div>
		<?php } ?>

		<?php if ($od['od_send_cost2'] > 0) { ?>
			<div class="col-xs-6">추가배송비</div>
			<div class="col-xs-6 text-right">
				<strong><?php echo number_format($od['od_send_cost2']); ?></strong>
			</div>
		<?php } ?>

		<?php if ($od['od_cancel_price'] > 0) { ?>
			<div class="col-xs-6 blue">취소금액</div>
			<div class="col-xs-6 text-right blue">
				<strong>-<?php echo number_format($od['od_cancel_price']); ?></strong>
			</div>
		<?php } ?>

		<div class="col-xs-6 red"> <b>합계금액</b></div>
		<div class="col-xs-6 text-right red">
			<strong><?php echo number_format($tot_price); ?></strong>
		</div>

		<!-- <div class="col-xs-6"> 포인트</div>
		<div class="col-xs-6 text-right">
			<strong><?php echo number_format($tot_point); ?> 점</strong>
		</div> -->
	</div>
</div>

<div class="panel panel-success">
	<div class="panel-heading"><strong><i class="fa fa-star fa-lg"></i> 결제정보</strong></div>
	<div class="table-responsive">
		<table class="div-table table bsk-tbl bg-white">
		<col width="120">
		<tbody>
		<tr>
			<th scope="row">주문번호</th>
			<td><?php echo $od_id; ?></td>
		</tr>
		<tr>
			<th scope="row">주문일시</th>
			<td><?php echo $od['od_time']; ?> KST</td>
		</tr>
		<tr>
			<th scope="row">결제방식</th>
			<td><?php echo ($easy_pay_name ? $easy_pay_name.'('.$od['od_settle_case'].')' : check_pay_name_replace($od['od_settle_case']) ); ?></td>
		</tr>
		<!-- <tr class="active">
			<th scope="row">결제금액</th>
			<td><?php echo $od_receipt_price; ?></td>
		</tr> -->
		<?php if($od['od_receipt_price'] > 0) {	?>
			<tr>
				<th scope="row">결제일시</th>
				<td><?php echo $od['od_receipt_time']; ?></td>
			</tr>
		<?php } ?>
		<?php if($app_no_subj) { // 승인번호, 휴대폰번호, 거래번호 ?>
			<tr>
				<th scope="row"><?php echo $app_no_subj; ?></th>
				<td><?php echo $app_no; ?></td>
			</tr>
		<?php } ?>
		<?php if($disp_bank) { // 계좌정보 ?>
			<!-- <tr>
				<th scope="row">입금자명</th>
				<td><?php echo get_text($od['od_deposit_name']); ?></td>
			</tr>
			<tr>
				<th scope="row">입금계좌</th>
				<td><?php echo get_text($od['od_bank_account']); ?></td>
			</tr> -->
		<?php } ?>
		<?php if($disp_receipt_href) { ?>
			<tr>
				<th scope="row">영수증</th>
				<td><a <?php echo $disp_receipt_href;?>>영수증 출력</a></td>
			</tr>
		<?php } ?>
		<?php if ($od['od_receipt_point'] > 0) { ?>
			<tr>
				<th scope="row">포인트사용</th>
				<td>최초주문 <?php echo apms_display_point_plain($od['od_receipt_point']); ?> + 연장주문 <?php echo apms_display_point_plain($od['od_receipt_point_for_extension_of_period']); ?> </td>
			</tr>
		<?php } ?>
		<?php if ($od['od_refund_price'] > 0) { ?>
			<tr>
				<th scope="row" class="red">환불금액</th>
				<td class="red"><strong><?php echo apms_display_point_plain($od['od_refund_price']); ?></strong></td>
			</tr>
		<?php } ?>
		<?php if($taxsave_href) { ?>
			<tr>
				<th scope="row">현금영수증</th>
				<td>
					<a <?php echo $taxsave_href;?> class="btn btn-black btn-xs">
						<?php echo ($taxsave_confirm) ? '현금영수증 확인하기' : '현금영수증을 발급하시려면 클릭하십시오.';?>
					</a>
				</td>
			</tr>
		<?php } ?>
		</tbody>
		</table>
	</div>
</div>

<?php if($is_orderform) { ?>
	<div class="panel panel-default">
		<div class="panel-heading"><strong><i class="fa fa-user fa-lg"></i> 주문하신 분</strong></div>
		<div class="table-responsive">
			<table class="div-table table bsk-tbl bg-white">
			<col width="120">
			<tbody>
			<tr>
				<th scope="row">이 름</th>
				<td><?php echo get_text($od['od_name']); ?></td>
			</tr>
			<tr>
				<th scope="row">전화번호</th>
				<td><?php echo get_text($od['od_tel']); ?></td>
			</tr>
			<tr style="display:none;">
				<th scope="row">휴대폰</th>
				<td><?php echo get_text($od['od_hp']); ?></td>
			</tr>
			<tr style="display:none;">
				<th scope="row">주 소</th>
				<td><?php echo get_text(sprintf("(%s%s)", $od['od_zip1'], $od['od_zip2']).' '.print_address($od['od_addr1'], $od['od_addr2'], $od['od_addr3'], $od['od_addr_jibeon'])); ?></td>
			</tr>
			<tr>
				<th scope="row">E-mail</th>
				<td><?php echo get_text($od['od_email']); ?></td>
			</tr>
			<tr>
				<th scope="row">메신저</th>
				<td><?php echo "[종류] " . get_text($od['od_sns_name']) . " [ID] " . get_text($od['od_sns_id']); ?></td>
			</tr>
			</tbody>
			</table>
		</div>
	</div>

	<div class="panel panel-default" style="display:none;">
		<div class="panel-heading"><strong><i class="fa fa-gift fa-lg"></i> 받으시는 분</strong></div>
		<div class="table-responsive">
			<table class="div-table table bsk-tbl bg-white">
			<col width="120">
			<tbody>
			<tr>
				<th scope="row">이 름</th>
				<td><?php echo get_text($od['od_b_name']); ?></td>
			</tr>
			<tr>
				<th scope="row">전화번호</th>
				<td><?php echo get_text($od['od_b_tel']); ?></td>
			</tr>
			<tr>
				<th scope="row">휴대폰</th>
				<td><?php echo get_text($od['od_b_hp']); ?></td>
			</tr>
			<tr>
				<th scope="row">주 소</th>
				<td><?php echo get_text(sprintf("(%s%s)", $od['od_b_zip1'], $od['od_b_zip2']).' '.print_address($od['od_b_addr1'], $od['od_b_addr2'], $od['od_b_addr3'], $od['od_b_addr_jibeon'])); ?></td>
			</tr>
			<?php if ($default['de_hope_date_use']) { // 희망배송일을 사용한다면 ?>
				<tr>
					<th scope="row">희망배송일</th>
					<td><?php echo substr($od['od_hope_date'],0,10).' ('.get_yoil($od['od_hope_date']).')' ;?></td>
				</tr>
			<?php } ?>

			<?php if ($od['od_memo']) { ?>
				<tr>
					<th scope="row">전하실 말씀</th>
					<td><?php echo conv_content($od['od_memo'], 0); ?></td>
				</tr>
			<?php } ?>
			</tbody>
			</table>
		</div>
	</div>

	<div class="panel panel-default" style="display:none;">
		<div class="panel-heading"><strong><i class="fa fa-truck fa-lg"></i> 배송정보</strong></div>
		<div class="table-responsive">
			<table class="div-table table bsk-tbl bg-white">
			<col width="120">
			<tbody>
			<?php if ($od['od_invoice'] && $od['od_delivery_company']) {?>
				<tr>
					<th scope="row">배송회사</th>
					<td><?php echo $od['od_delivery_company']; ?> <?php echo get_delivery_inquiry($od['od_delivery_company'], $od['od_invoice'], 'dvr_link'); ?></td>
				</tr>
				<tr>
					<th scope="row">운송장번호</th>
					<td><?php echo $od['od_invoice']; ?></td>
				</tr>
				<tr>
					<th scope="row">배송일시</th>
					<td><?php echo $od['od_invoice_time']; ?></td>
				</tr>
			<?php }	else { ?>
				<tr>
					<td>아직 배송하지 않았거나 배송정보를 입력하지 못하였습니다.</td>
				</tr>
			<?php }	?>
			</tbody>
			</table>
		</div>
	</div>
<?php } ?>

<div class="panel panel-primary">
	<div class="panel-heading"><strong><i class="fa fa-money fa-lg"></i> 결제합계</strong></div>
	<div class="table-responsive">
		<table class="div-table table bsk-tbl bg-white">
		<col width="120">
		<tbody>
		<tr>
			<th scope="row">총구매액</th>
			<td class="text-right"><strong><?php echo apms_display_point_plain($tot_price); ?></strong></td>
		</tr>
		<?php if ($misu_price > 0) { ?>
			<tr class="active">
				<th scope="row">미결제액</th>
				<td class="text-right"><strong><?php echo apms_display_point_plain($misu_price);?></strong></td>
			</tr>
		<?php } ?>
		<tr>
			<th scope="row" id="alrdy">결제금액</th>
			<td class="text-right"><strong><?php echo $wanbul; ?></strong></td>
		</tr>
		</tbody>
		</table>
	</div>
</div>

<?php if ($cancel_price == 0) { // 취소한 내역이 없다면 ?>
	<?php if ($custom_cancel) { ?>
		<div class="print-hide text-center">
			<button type="button" data-toggle="collapse" href="#sod_fin_cancelfrm" aria-expanded="false" aria-controls="sod_fin_cancelfrm" class="btn btn-black btn-sm">주문 취소하기</button>
		</div>

		<div class="h15"></div>

		<div id="sod_fin_cancelfrm" class="collapse">
			<div class="well">
				<form class="form" role="form" method="post" action="./orderinquirycancel.php" onsubmit="return fcancel_check(this);">
				<input type="hidden" name="od_id"  value="<?php echo $od['od_id']; ?>">
				<input type="hidden" name="token"  value="<?php echo $token; ?>">
					<div class="input-group input-group-sm">
						<span class="input-group-addon">사유</span>
						<input type="text" name="cancel_memo" id="cancel_memo" required class="form-control input-sm" size="40" maxlength="100">
						<span class="input-group-btn">
							<button type="submit" class="btn btn-black btn-sm">확인</button>
						</span>
					</div>
				</form>
			</div>
		</div>
	<?php } ?>
<?php } else { ?>
	<div class="well text-center">주문 취소, 반품, 품절된 내역이 있습니다.</div>
<?php } ?>

<?php if ($is_account_test) { ?>
	<div class="alert alert-danger">
		관리자가 가상계좌 테스트를 한 경우에만 보입니다.
	</div>

	<form class="form" role="form" method="post" action="http://devadmin.kcp.co.kr/Modules/Noti/TEST_Vcnt_Noti_Proc.jsp" target="_blank">
		<div class="panel panel-default">
			<div class="panel-heading"><strong><i class="fa fa-cog fa-lg"></i> 모의입금처리</strong></div>
			<div class="table-responsive">
				<table class="div-table table bsk-tbl bg-white">
				<col width="120">
				<tbody>
				<tr>
					<th scope="col"><label for="e_trade_no">KCP 거래번호</label></th>
					<td><input type="text" name="e_trade_no" value="<?php echo $od['od_tno']; ?>" class="form-control input-sm"></td>
				</tr>
				<tr>
					<th scope="col"><label for="deposit_no">입금계좌</label></th>
					<td><input type="text" name="deposit_no" value="<?php echo $deposit_no; ?>" class="form-control input-sm"></td>
				</tr>
				<tr>
					<th scope="col"><label for="req_name">입금자명</label></th>
					<td><input type="text" name="req_name" value="<?php echo $od['od_deposit_name']; ?>" class="form-control input-sm"></td>
				</tr>
				<tr>
					<th scope="col"><label for="noti_url">입금통보 URL</label></th>
					<td><input type="text" name="noti_url" value="<?php echo G5_SHOP_URL; ?>/settle_kcp_common.php" class="form-control input-sm"></td>
				</tr>
				</tbody>
				</table>
			</div>
		</div>
		<div id="sod_fin_test" class="text-center">
			<input type="submit" value="입금통보 테스트" class="btn btn-color btn-sm">
		</div>
	</form>
<?php } ?>

<p class="print-hide text-center oi-fixed-actionbar">
	<a class="btn btn-color btn-sm" href="<?php echo isset($order_inquiry_back_href) ? $order_inquiry_back_href : './orderinquiry.php'; ?>"><i class="fa fa-bars"></i> 목록으로</a>
	<button type="button" onclick="apms_print();" class="btn btn-black btn-sm"><i class="fa fa-print"></i> 프린트</button>
	<?php if($setup_href) { ?>
		<a class="btn btn-color btn-sm win_memo" href="<?php echo $setup_href;?>">
			<i class="fa fa-cogs"></i> 스킨설정
		</a>
	<?php } ?>
</p>

<div id="remoteManualPreviewBackdrop" class="remote-manual-preview-backdrop" onclick="closeRemoteManualPreview()"></div>
<div id="remoteManualPreviewWindow" class="remote-manual-preview-window" role="dialog" aria-modal="true" aria-labelledby="remoteManualPreviewTitle">
	<div id="remoteManualPreviewHeader" class="remote-manual-preview-header">
		<div id="remoteManualPreviewTitle" class="remote-manual-preview-title">매뉴얼 이미지 미리보기</div>
		<button type="button" class="remote-manual-preview-close" onclick="closeRemoteManualPreview()">×</button>
	</div>
	<div class="remote-manual-preview-body">
		<img id="remoteManualPreviewImage" src="" alt="" class="remote-manual-preview-image">
	</div>
	<div id="remoteManualPreviewResizer" class="remote-manual-preview-resizer"></div>
</div>

<style>
.oi-fixed-actionbar {
	display: flex;
	justify-content: center;
	align-items: center;
	gap: 6px;
	max-width: 1170px;
	margin: 12px auto 0;
	padding: 0 8px;
}
.oi-fixed-actionbar .btn {
	height: 38px;
	min-width: 104px;
	padding: 0 12px;
	line-height: 36px;
	font-size: 13px;
	font-weight: 700;
	border-radius: 0;
}
@media (max-width: 991px) {
	.oi-fixed-actionbar {
		justify-content: center;
		flex-wrap: wrap;
	}
	.oi-fixed-actionbar .btn {
		min-width: 92px;
		height: 34px;
		line-height: 32px;
		font-size: 12px;
	}
}
</style>

<script>
var extendPopupZIndex = 1060;
var extendPopupInitMap = {};
var refundPopupInitMap = {};
var extendConfirmContext = null;
var refundConfirmContext = null;
var refundCalcGuideContext = null;

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

function openExtendConfirmModal(payload, onConfirm) {
	var backdrop = document.getElementById('extendConfirmBackdrop');
	var modal = document.getElementById('extendConfirmModal');
	var headText = document.getElementById('extendConfirmHeadText');
	if (!backdrop || !modal) {
		return;
	}
	if (headText) {
		headText.textContent = (payload.itemName ? String(payload.itemName) + ' 계약연장 확인' : '계약연장 확인');
	}

	document.getElementById('extendConfirmItem').innerHTML = '계약연장 상품명 : ' + escapeHtml(payload.itemName || '-');
	document.getElementById('extendConfirmPeriod').innerHTML = '계약연장기간 : ' + escapeHtml(payload.periodText || '-');
	document.getElementById('extendConfirmAmount').innerHTML = '결제(포인트 차감)금액 : ' + escapeHtml(payload.amountText || '-');
	document.getElementById('extendConfirmEnd').innerHTML = '계약연장후 종료일시 : ' + escapeHtml(payload.endText || '-');
	var okBtn = document.getElementById('extendConfirmOk');
	if (okBtn) {
		okBtn.textContent = payload.payButtonText ? String(payload.payButtonText) : '결제하기';
	}

	extendConfirmContext = {
		onConfirm: (typeof onConfirm === 'function') ? onConfirm : null
	};

	backdrop.style.display = 'block';
	modal.style.display = 'block';
	if (okBtn) {
		okBtn.focus();
	}
}

function closeExtendConfirmModal() {
	var backdrop = document.getElementById('extendConfirmBackdrop');
	var modal = document.getElementById('extendConfirmModal');
	if (backdrop) backdrop.style.display = 'none';
	if (modal) modal.style.display = 'none';
	extendConfirmContext = null;
}

function buildRefundConfirmPayload(form) {
	if (!form) {
		return {
			itemName: '-',
			amountText: '- (현재 시간 기준)',
			memoText: '-',
			submitText: '해지신청',
			isExpired: false
		};
	}

	var itId = form.it_id ? String(form.it_id.value || '') : '';
	var itemName = form.it_name ? String(form.it_name.value || '') : '';
	if (itemName.replace(/^\s+|\s+$/g, '') === '') {
		itemName = 'VPN-' + itId;
	}

	var memo = form.refund_memo ? String(form.refund_memo.value || '') : '';
	var odId = form.od_id ? String(form.od_id.value || '') : '';
	var amountKey = odId + '_' + itId;
	var amountEl = document.getElementById('refund_amount_after_penalty_' + amountKey);
	var amountText = '- (현재 시간 기준)';
	if (amountEl) {
		var amountRawText = String(amountEl.textContent || amountEl.innerText || '').replace(/\s+/g, ' ').trim();
		if (amountRawText !== '') {
			amountText = amountRawText + ' (현재 시간 기준)';
		}
	}
	var isExpired = (form.contract_is_expired && String(form.contract_is_expired.value) === '1');

	return {
		itemName: itemName,
		amountText: amountText,
		memoText: memo,
		submitText: isExpired ? '해지불가(계약만료)' : '해지신청',
		isExpired: isExpired
	};
}

function renderRefundConfirmModal(payload) {
	document.getElementById('refundConfirmItem').innerHTML = '계약해지 상품명 : ' + escapeHtml(payload.itemName || '-');
	document.getElementById('refundConfirmAmount').innerHTML = '환불예정금액 : ' + escapeHtml(payload.amountText || '-');
	document.getElementById('refundConfirmMemo').innerHTML = '해지사유 : ' + escapeHtml(payload.memoText || '-');

	var okBtn = document.getElementById('refundConfirmOk');
	if (okBtn) {
		okBtn.textContent = payload.submitText ? String(payload.submitText) : '해지신청';
		okBtn.disabled = !!payload.isExpired;
	}

	var modal = document.getElementById('refundConfirmModal');
	if (modal) {
		var subNode = modal.querySelector('.extend-confirm-sub');
		if (subNode) {
			subNode.textContent = payload.isExpired
				? '현재 계약상태가 만료로 변경되어 해지신청이 불가합니다.'
				: '이 작업은 취소할 수 없습니다.';
		}
	}
}

function openRefundConfirmModal(payload, onConfirm) {
	var backdrop = document.getElementById('refundConfirmBackdrop');
	var modal = document.getElementById('refundConfirmModal');
	var headText = document.getElementById('refundConfirmHeadText');
	if (!backdrop || !modal) {
		return;
	}
	if (headText) {
		headText.textContent = '계약해지 확인';
	}

	refundConfirmContext = {
		onConfirm: (typeof onConfirm === 'function') ? onConfirm : null,
		form: payload && payload.form ? payload.form : null,
		syncTimer: null
	};

	renderRefundConfirmModal(payload || {});

	backdrop.style.display = 'block';
	modal.style.display = 'block';

	if (refundConfirmContext.form) {
		refundConfirmContext.syncTimer = setInterval(function() {
			if (!refundConfirmContext || !refundConfirmContext.form) {
				return;
			}
			var livePayload = buildRefundConfirmPayload(refundConfirmContext.form);
			renderRefundConfirmModal(livePayload);
		}, 1000);
	}

	var okBtn = document.getElementById('refundConfirmOk');
	if (okBtn) {
		okBtn.focus();
	}
}

function closeRefundConfirmModal() {
	var backdrop = document.getElementById('refundConfirmBackdrop');
	var modal = document.getElementById('refundConfirmModal');
	if (refundConfirmContext && refundConfirmContext.syncTimer) {
		clearInterval(refundConfirmContext.syncTimer);
	}
	if (backdrop) backdrop.style.display = 'none';
	if (modal) modal.style.display = 'none';
	refundConfirmContext = null;
}

function openRefundCalcGuideModal(odiditid) {
	var sourceEl = document.getElementById('refund_calc_guide_' + odiditid);
	var backdrop = document.getElementById('refundCalcGuideBackdrop');
	var modal = document.getElementById('refundCalcGuideModal');
	var body = document.getElementById('refundCalcGuideBody');
	if (!sourceEl || !backdrop || !modal || !body) {
		return;
	}

	body.innerHTML = '<div class="refund-calc-guide">' + sourceEl.innerHTML + '</div>';
	backdrop.style.display = 'block';
	modal.style.display = 'block';

	refundCalcGuideContext = {
		odiditid: odiditid
	};

	var activeToggleBtn = document.getElementById('refund_calc_toggle_' + odiditid);
	if (activeToggleBtn) {
		activeToggleBtn.setAttribute('aria-expanded', 'true');
		activeToggleBtn.setAttribute('title', '해지수수료 계산식 안내 닫기');
		activeToggleBtn.setAttribute('aria-label', '해지수수료 계산식 안내 닫기');
	}

	var closeBtn = document.getElementById('refundCalcGuideCloseBtn');
	if (closeBtn) {
		closeBtn.focus();
	}
}

function closeRefundCalcGuideModal() {
	var backdrop = document.getElementById('refundCalcGuideBackdrop');
	var modal = document.getElementById('refundCalcGuideModal');
	if (backdrop) backdrop.style.display = 'none';
	if (modal) modal.style.display = 'none';

	if (refundCalcGuideContext && refundCalcGuideContext.odiditid) {
		var toggleBtn = document.getElementById('refund_calc_toggle_' + refundCalcGuideContext.odiditid);
		if (toggleBtn) {
			toggleBtn.setAttribute('aria-expanded', 'false');
			toggleBtn.setAttribute('title', '해지수수료 계산식 안내 보기');
			toggleBtn.setAttribute('aria-label', '해지수수료 계산식 안내 보기');
		}
	}

	refundCalcGuideContext = null;
}

document.addEventListener('DOMContentLoaded', function() {
	var okBtn = document.getElementById('extendConfirmOk');
	if (okBtn) {
		okBtn.addEventListener('click', function() {
			if (extendConfirmContext && typeof extendConfirmContext.onConfirm === 'function') {
				var run = extendConfirmContext.onConfirm;
				closeExtendConfirmModal();
				run();
			} else {
				closeExtendConfirmModal();
			}
		});
	}

	var refundOkBtn = document.getElementById('refundConfirmOk');
	if (refundOkBtn) {
		refundOkBtn.addEventListener('click', function() {
			if (refundConfirmContext && refundConfirmContext.form) {
				var latestPayload = buildRefundConfirmPayload(refundConfirmContext.form);
				renderRefundConfirmModal(latestPayload);
				if (latestPayload.isExpired) {
					return;
				}
			}

			if (refundConfirmContext && typeof refundConfirmContext.onConfirm === 'function') {
				var run = refundConfirmContext.onConfirm;
				closeRefundConfirmModal();
				run();
			} else {
				closeRefundConfirmModal();
			}
		});
	}
});

function openExtendPopup(odiditid) {
	var popup = document.getElementById('sod_fin_ExtendPeriodfrm_' + odiditid);
	var backdrop = document.getElementById('sod_fin_ExtendPeriodBackdrop_' + odiditid);
	if (!popup || !backdrop) {
		return;
	}

	extendPopupZIndex += 2;
	backdrop.style.zIndex = String(extendPopupZIndex - 1);
	popup.style.zIndex = String(extendPopupZIndex);
	backdrop.style.display = 'block';
	popup.style.display = 'block';

	popup.style.left = '50%';
	popup.style.top = '50%';
	popup.style.transform = 'translate(-50%, -50%)';

	initExtendPopup(odiditid);
}

function closeExtendPopup(odiditid) {
	var popup = document.getElementById('sod_fin_ExtendPeriodfrm_' + odiditid);
	var backdrop = document.getElementById('sod_fin_ExtendPeriodBackdrop_' + odiditid);
	if (popup) popup.style.display = 'none';
	if (backdrop) backdrop.style.display = 'none';
}

function initExtendPopup(odiditid) {
	if (extendPopupInitMap[odiditid]) {
		return;
	}

	var popup = document.getElementById('sod_fin_ExtendPeriodfrm_' + odiditid);
	if (!popup) {
		return;
	}

	var header = popup.querySelector('.extend-popup-header');
	var resizer = popup.querySelector('.extend-popup-resizer');
	if (!header || !resizer) {
		return;
	}

	var dragState = null;
	var resizeState = null;

	function bringToFront() {
		extendPopupZIndex += 2;
		var backdrop = document.getElementById('sod_fin_ExtendPeriodBackdrop_' + odiditid);
		if (backdrop) backdrop.style.zIndex = String(extendPopupZIndex - 1);
		popup.style.zIndex = String(extendPopupZIndex);
	}

	header.addEventListener('mousedown', function(e) {
		if (e.target && e.target.classList && e.target.classList.contains('extend-popup-close')) {
			return;
		}
		bringToFront();
		var rect = popup.getBoundingClientRect();
		popup.style.transform = 'none';
		popup.style.left = rect.left + 'px';
		popup.style.top = rect.top + 'px';

		dragState = {
			startX: e.clientX,
			startY: e.clientY,
			left: rect.left,
			top: rect.top
		};
		e.preventDefault();
	});

	resizer.addEventListener('mousedown', function(e) {
		bringToFront();
		var rect = popup.getBoundingClientRect();
		resizeState = {
			startX: e.clientX,
			startY: e.clientY,
			width: rect.width,
			height: rect.height
		};
		e.preventDefault();
		e.stopPropagation();
	});

	document.addEventListener('mousemove', function(e) {
		if (dragState) {
			var nextLeft = dragState.left + (e.clientX - dragState.startX);
			var nextTop = dragState.top + (e.clientY - dragState.startY);
			var vw = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
			var vh = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
			var rect = popup.getBoundingClientRect();
			nextLeft = Math.max(6, Math.min(nextLeft, vw - rect.width - 6));
			nextTop = Math.max(6, Math.min(nextTop, vh - rect.height - 6));
			popup.style.left = nextLeft + 'px';
			popup.style.top = nextTop + 'px';
			popup.style.transform = 'none';
		}

		if (resizeState) {
			var width = resizeState.width + (e.clientX - resizeState.startX);
			var height = resizeState.height + (e.clientY - resizeState.startY);
			var minW = Math.max(300, Math.min(420, window.innerWidth - 24));
			var minH = Math.max(240, Math.min(300, window.innerHeight - 24));
			var maxW = Math.max(minW, window.innerWidth - 16);
			var maxH = Math.max(minH, window.innerHeight - 16);
			width = Math.max(minW, Math.min(width, maxW));
			height = Math.max(minH, Math.min(height, maxH));
			popup.style.width = width + 'px';
			popup.style.height = height + 'px';
		}
	});

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

	popup.addEventListener('mousedown', function() {
		bringToFront();
	});

	extendPopupInitMap[odiditid] = true;
}

function openRefundPopup(odiditid) {
	var popup = document.getElementById('sod_fin_refundfrm_' + odiditid);
	var backdrop = document.getElementById('sod_fin_refundBackdrop_' + odiditid);
	if (!popup || !backdrop) {
		return;
	}

	extendPopupZIndex += 2;
	backdrop.style.zIndex = String(extendPopupZIndex - 1);
	popup.style.zIndex = String(extendPopupZIndex);
	backdrop.style.display = 'block';
	popup.style.display = 'block';

	popup.style.left = '50%';
	popup.style.top = '50%';
	popup.style.transform = 'translate(-50%, -50%)';

	initRefundPopup(odiditid);
}

function closeRefundPopup(odiditid) {
	var popup = document.getElementById('sod_fin_refundfrm_' + odiditid);
	var backdrop = document.getElementById('sod_fin_refundBackdrop_' + odiditid);
	if (popup) popup.style.display = 'none';
	if (backdrop) backdrop.style.display = 'none';
}

function initRefundPopup(odiditid) {
	if (refundPopupInitMap[odiditid]) {
		return;
	}

	var popup = document.getElementById('sod_fin_refundfrm_' + odiditid);
	if (!popup) {
		return;
	}

	var header = popup.querySelector('.extend-popup-header');
	var resizer = popup.querySelector('.extend-popup-resizer');
	if (!header || !resizer) {
		return;
	}

	var dragState = null;
	var resizeState = null;

	function bringToFront() {
		extendPopupZIndex += 2;
		var backdrop = document.getElementById('sod_fin_refundBackdrop_' + odiditid);
		if (backdrop) backdrop.style.zIndex = String(extendPopupZIndex - 1);
		popup.style.zIndex = String(extendPopupZIndex);
	}

	header.addEventListener('mousedown', function(e) {
		if (e.target && e.target.classList && e.target.classList.contains('extend-popup-close')) {
			return;
		}
		bringToFront();
		var rect = popup.getBoundingClientRect();
		popup.style.transform = 'none';
		popup.style.left = rect.left + 'px';
		popup.style.top = rect.top + 'px';

		dragState = {
			startX: e.clientX,
			startY: e.clientY,
			left: rect.left,
			top: rect.top
		};
		e.preventDefault();
	});

	resizer.addEventListener('mousedown', function(e) {
		bringToFront();
		var rect = popup.getBoundingClientRect();
		resizeState = {
			startX: e.clientX,
			startY: e.clientY,
			width: rect.width,
			height: rect.height
		};
		e.preventDefault();
		e.stopPropagation();
	});

	document.addEventListener('mousemove', function(e) {
		if (dragState) {
			var nextLeft = dragState.left + (e.clientX - dragState.startX);
			var nextTop = dragState.top + (e.clientY - dragState.startY);
			var vw = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
			var vh = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
			var rect = popup.getBoundingClientRect();
			nextLeft = Math.max(6, Math.min(nextLeft, vw - rect.width - 6));
			nextTop = Math.max(6, Math.min(nextTop, vh - rect.height - 6));
			popup.style.left = nextLeft + 'px';
			popup.style.top = nextTop + 'px';
			popup.style.transform = 'none';
		}

		if (resizeState) {
			var width = resizeState.width + (e.clientX - resizeState.startX);
			var height = resizeState.height + (e.clientY - resizeState.startY);
			var minW = Math.max(300, Math.min(420, window.innerWidth - 24));
			var minH = Math.max(240, Math.min(320, window.innerHeight - 24));
			var maxW = Math.max(minW, window.innerWidth - 16);
			var maxH = Math.max(minH, window.innerHeight - 16);
			width = Math.max(minW, Math.min(width, maxW));
			height = Math.max(minH, Math.min(height, maxH));
			popup.style.width = width + 'px';
			popup.style.height = height + 'px';
		}
	});

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

	popup.addEventListener('mousedown', function() {
		bringToFront();
	});

	refundPopupInitMap[odiditid] = true;
}

document.addEventListener('keydown', function(e) {
	if (e.key === 'Escape') {
		closeExtendConfirmModal();
		closeRefundConfirmModal();
		closeRefundCalcGuideModal();
		closeRemoteManualPreview();
	}

	if (e.key !== 'Escape') {
		return;
	}
	var openPopups = document.querySelectorAll('.extend-popup-window');
	for (var i = 0; i < openPopups.length; i++) {
		if (openPopups[i].style.display === 'block') {
			var popupId = openPopups[i].getAttribute('data-popup-id');
			if (popupId) {
				closeExtendPopup(popupId);
			}
			var refundPopupId = openPopups[i].getAttribute('data-refund-popup-id');
			if (refundPopupId) {
				closeRefundPopup(refundPopupId);
			}
		}
	}
});

function contractHoursText(totalHours) {
	var hours = parseInt(totalHours, 10) || 0;

	if (hours <= 0) {
		return "0시간";
	}

	if (hours < 24) {
		return number_format(String(hours)) + "시간";
	}

	var days = Math.floor(hours / 24);
	var remainHours = hours % 24;

	if (remainHours > 0) {
		return number_format(String(days)) + "일 " + number_format(String(remainHours)) + "시간";
	}

	return number_format(String(days)) + "일";
}

function fExtendPeriod_check(f) {
	if (f.getAttribute('data-extend-confirmed') === '1') {
		f.setAttribute('data-extend-confirmed', '0');
		return true;
	}

	var it_id = f.it_id.value;
	var item_name = f.it_name ? f.it_name.value : ('VPN-' + it_id);
	var ExtendPeriod_amount = f.ExtendPeriod_amount.value;
	var ExtendPeriod_days = f.ExtendPeriod_days.value;
	var ExtendPeriod_hours = f.ExtendPeriod_hours.value;
	var ExtendPeriod_datetime = f.ExtendPeriod_datetime.value;
	var selectedDays = parseInt(ExtendPeriod_days, 10) || 0;
	var selectedHours = parseInt(ExtendPeriod_hours, 10) || 0;
	var selectedTotalHours = (selectedDays * 24) + selectedHours;

	openExtendConfirmModal({
		itemName: item_name,
		periodText: contractHoursText(selectedTotalHours),
		amountText: number_format(ExtendPeriod_amount),
		endText: ExtendPeriod_datetime,
		payButtonText: number_format(ExtendPeriod_amount) + ' 결제하기'
	}, function() {
		f.setAttribute('data-extend-confirmed', '1');
		f.submit();
	});

	return false;
}

function frefund_check(f) {
	if (f.getAttribute('data-refund-confirmed') === '1') {
		f.setAttribute('data-refund-confirmed', '0');
		return true;
	}

	var isExpired = (f.contract_is_expired && String(f.contract_is_expired.value) === '1');
	if (isExpired) {
		alert("계약기간이 만료되어 환불신청이 불가합니다.");
		return false;
	}

	var memo = f.refund_memo ? String(f.refund_memo.value || '') : '';
	if (memo.replace(/^\s+|\s+$/g, '') === '') {
		alert("계약해지(환불신청) 사유를 입력해 주십시오.");
		if (f.refund_memo && typeof f.refund_memo.focus === 'function') {
			f.refund_memo.focus();
		}
		return false;
	}

	var it_id = f.it_id.value;
	var payload = buildRefundConfirmPayload(f);
	payload.form = f;
	openRefundConfirmModal(payload, function() {
		if (f.contract_is_expired && String(f.contract_is_expired.value) === '1') {
			alert("계약기간이 만료되어 환불신청이 불가합니다.");
			return;
		}
		f.setAttribute('data-refund-confirmed', '1');
		f.submit();
	});

	return false;
}

function fcancel_check(f) {
    if(!confirm("주문을 정말 취소하시겠습니까?"))
        return false;

    var memo = f.cancel_memo.value;
    if(memo == "") {
        alert("취소사유를 입력해 주십시오.");
        return false;
    }

    return true;
}

$(function(){
	$(".delivery-confirm").click(function(){
		if(confirm("상품을 수령하셨습니까?\n\n확인시 배송완료 처리가됩니다.")) {
			return true;
		}
		return false;
	});
});
</script>

<script>
    function updateRemainingTime() {
		const remainTimeElements = document.querySelectorAll('.remote-remain-time');

        function formatTime(seconds) {
            if (seconds <= 0) {
				return '';
            } else if (seconds < 60) {
                return `${seconds}초 남음`;
            } else if (seconds < 3600) {
                const minutes = Math.floor(seconds / 60);
                seconds = seconds % 60;
                return `${minutes}분 ${seconds}초 남음`;
            } else if (seconds < 86400) {
                const hours = Math.floor(seconds / 3600);
                const minutes = Math.floor((seconds % 3600) / 60);
				seconds = seconds % 60;
                return `${hours}시간 ${minutes}분 ${seconds}초 남음`;
            } else {
                const days = Math.floor(seconds / 86400);
                const hours = Math.floor((seconds % 86400) / 3600);
				const minutes = Math.floor((seconds % 3600) / 60);
				seconds = seconds % 60;
                return `${days}일 ${hours}시간 ${minutes}분 ${seconds}초 남음`;
            }
        }

        function updateElement(remainTimeElement) {
            let remainingSeconds = parseInt(remainTimeElement.getAttribute('data-remaining'), 10);

            if (isNaN(remainingSeconds)) {
                console.error('Remaining seconds is NaN');
                return;
            }

            function update() {
                if (remainingSeconds >= 0) {
                    var display = formatTime(remainingSeconds);
                    if (display === '') {
                        display = remainTimeElement.getAttribute('data-expired-label') || '계약기간이 종료되었습니다';
                    }
                    remainTimeElement.textContent = display;

                    // 남은 시간을 1초 감소
                    remainingSeconds -= 1;

                    // 실시간 업데이트를 위해 1초마다 호출
                    setTimeout(update, 1000);
                } else {
					remainTimeElement.textContent = remainTimeElement.getAttribute('data-expired-label') || '계약기간이 종료되었습니다';
                }
            }

            update();
        }

        remainTimeElements.forEach(updateElement);
    }

	function setCopyButtonCopied(btn) {
		if (!btn) return;
		if (!btn.dataset.originalLabel) {
			btn.dataset.originalLabel = btn.textContent || '복사';
		}
		if (btn.dataset.timerId) {
			clearTimeout(parseInt(btn.dataset.timerId, 10));
		}
		btn.textContent = '복사됨';
		btn.classList.add('copied');
		var timerId = setTimeout(function() {
			btn.textContent = btn.dataset.originalLabel || '복사';
			btn.classList.remove('copied');
			btn.dataset.timerId = '';
		}, 1400);
		btn.dataset.timerId = String(timerId);
	}

	function copyTextToClipboard(text, btn) {
		if (!text) return;
		if (navigator.clipboard && navigator.clipboard.writeText) {
			navigator.clipboard.writeText(text).then(function() {
				setCopyButtonCopied(btn);
			}).catch(function() {
				fallbackCopy(text, btn);
			});
		} else {
			fallbackCopy(text, btn);
		}
	}

	function fallbackCopy(text, btn) {
		var temp = document.createElement('textarea');
		temp.value = text;
		temp.setAttribute('readonly', 'readonly');
		temp.style.position = 'absolute';
		temp.style.left = '-9999px';
		document.body.appendChild(temp);
		temp.select();
		document.execCommand('copy');
		document.body.removeChild(temp);
		setCopyButtonCopied(btn);
	}

	function setupRemoteCopyButtons() {
		document.querySelectorAll('.remote-copy-btn').forEach(function(btn) {
			btn.addEventListener('click', function() {
				var value = btn.getAttribute('data-copy') || '';
				copyTextToClipboard(value, btn);
			});
		});
	}

	function detectClientOsForManual() {
		var ua = (navigator.userAgent || '').toLowerCase();
		var platform = (navigator.platform || '').toLowerCase();

		if (ua.indexOf('android') !== -1) {
			return 'android';
		}
		if (ua.indexOf('iphone') !== -1 || ua.indexOf('ipad') !== -1 || ua.indexOf('ipod') !== -1) {
			return 'ios';
		}
		if (platform === 'macintel' && navigator.maxTouchPoints && navigator.maxTouchPoints > 1) {
			return 'ios';
		}
		if (platform.indexOf('win') !== -1 || ua.indexOf('windows') !== -1) {
			return 'windows';
		}
		if (platform.indexOf('mac') !== -1 || ua.indexOf('mac os x') !== -1) {
			return 'macos';
		}
		if (platform.indexOf('linux') !== -1 || platform.indexOf('x11') !== -1 || ua.indexOf('linux') !== -1) {
			return 'linux';
		}

		return 'windows';
	}

	function setupRemoteManualTabs() {
		var detectedOs = detectClientOsForManual();
		var osLabelMap = {
			windows: 'Windows',
			macos: 'macOS',
			linux: 'Linux',
			android: 'Android',
			ios: 'iOS'
		};
		document.querySelectorAll('.remote-manual-section').forEach(function(section) {
			var buttons = section.querySelectorAll('.remote-manual-btn');
			var panels = section.querySelectorAll('.remote-manual-panel');

			function activateManualTab(targetOs) {
				if (!targetOs) {
					return;
				}
				buttons.forEach(function(b) {
					if (b.getAttribute('data-manual-os') === targetOs) {
						b.classList.add('is-active');
					} else {
						b.classList.remove('is-active');
					}
				});
				panels.forEach(function(panel) {
					if (panel.getAttribute('data-manual-os') === targetOs) {
						panel.classList.add('is-active');
					} else {
						panel.classList.remove('is-active');
					}
				});
			}

			buttons.forEach(function(btn) {
				btn.addEventListener('click', function() {
					var targetOs = btn.getAttribute('data-manual-os') || '';
					activateManualTab(targetOs);
				});
			});

			var hasDetectedTab = false;
			buttons.forEach(function(btn) {
				if (btn.getAttribute('data-manual-os') === detectedOs) {
					hasDetectedTab = true;
					if (!btn.querySelector('.remote-os-badge')) {
						var osBadge = document.createElement('span');
						osBadge.className = 'remote-os-badge';
						osBadge.textContent = '현재 OS';
						btn.appendChild(osBadge);
					}
					btn.setAttribute('title', '현재 사용 중인 OS: ' + (osLabelMap[detectedOs] || detectedOs));
				}
			});
			if (hasDetectedTab) {
				activateManualTab(detectedOs);
			} else if (buttons.length > 0) {
				activateManualTab(buttons[0].getAttribute('data-manual-os') || '');
			}
		});
	}

	var remoteManualPreviewState = {
		drag: null,
		resize: null,
		closeTimer: null
	};

	function openRemoteManualPreview(src, title, triggerEl) {
		var backdrop = document.getElementById('remoteManualPreviewBackdrop');
		var win = document.getElementById('remoteManualPreviewWindow');
		var img = document.getElementById('remoteManualPreviewImage');
		var titleEl = document.getElementById('remoteManualPreviewTitle');
		if (!backdrop || !win || !img) {
			return;
		}
		if (remoteManualPreviewState.closeTimer) {
			clearTimeout(remoteManualPreviewState.closeTimer);
			remoteManualPreviewState.closeTimer = null;
		}
		img.src = src || '';
		img.alt = title || '매뉴얼 이미지';
		if (titleEl) {
			titleEl.textContent = title || '매뉴얼 이미지 미리보기';
		}
		remoteManualPreviewState.drag = null;
		remoteManualPreviewState.resize = null;
		win.classList.remove('is-detached');
		win.style.width = '';
		win.style.height = '';

		var startLeft = '50%';
		var startTop = '50%';
		if (triggerEl && typeof triggerEl.getBoundingClientRect === 'function') {
			var btnRect = triggerEl.getBoundingClientRect();
			startLeft = (btnRect.left + (btnRect.width / 2)) + 'px';
			startTop = (btnRect.top + (btnRect.height / 2)) + 'px';
		}

		win.style.left = startLeft;
		win.style.top = startTop;
		win.style.width = '';
		win.style.height = '';
		backdrop.classList.add('is-open');
		win.classList.remove('is-closing');
		win.classList.add('is-opening');
		win.classList.remove('is-open');
		window.requestAnimationFrame(function() {
			win.style.left = '50%';
			win.style.top = '50%';
			win.classList.remove('is-opening');
			win.classList.add('is-open');
		});
	}

	function closeRemoteManualPreview() {
		var backdrop = document.getElementById('remoteManualPreviewBackdrop');
		var win = document.getElementById('remoteManualPreviewWindow');
		if (backdrop) backdrop.classList.remove('is-open');
		if (win) {
			win.classList.remove('is-opening');
			win.classList.remove('is-open');
			win.classList.add('is-closing');
			if (remoteManualPreviewState.closeTimer) {
				clearTimeout(remoteManualPreviewState.closeTimer);
			}
			remoteManualPreviewState.closeTimer = setTimeout(function() {
				win.classList.remove('is-closing');
				win.classList.remove('is-detached');
				remoteManualPreviewState.closeTimer = null;
			}, 270);
		}
		remoteManualPreviewState.drag = null;
		remoteManualPreviewState.resize = null;
	}

	function setupRemoteManualImagePreview() {
		document.querySelectorAll('.remote-manual-zoom-btn').forEach(function(btn) {
			btn.addEventListener('click', function(e) {
				e.preventDefault();
				e.stopPropagation();
				openRemoteManualPreview(btn.getAttribute('data-manual-image') || '', btn.getAttribute('data-manual-title') || '매뉴얼 이미지', btn);
			});
		});

		var win = document.getElementById('remoteManualPreviewWindow');
		var header = document.getElementById('remoteManualPreviewHeader');
		var resizer = document.getElementById('remoteManualPreviewResizer');
		if (!win || !header || !resizer) {
			return;
		}

		header.addEventListener('mousedown', function(e) {
			if (e.target && e.target.classList && e.target.classList.contains('remote-manual-preview-close')) {
				return;
			}
			var rect = win.getBoundingClientRect();
			win.style.width = rect.width + 'px';
			win.style.height = rect.height + 'px';
			win.style.left = rect.left + 'px';
			win.style.top = rect.top + 'px';
			win.classList.add('is-detached');
			remoteManualPreviewState.drag = {
				startX: e.clientX,
				startY: e.clientY,
				left: rect.left,
				top: rect.top
			};
			e.preventDefault();
		});

		resizer.addEventListener('mousedown', function(e) {
			var rect = win.getBoundingClientRect();
			remoteManualPreviewState.resize = {
				startX: e.clientX,
				startY: e.clientY,
				width: rect.width,
				height: rect.height
			};
			e.preventDefault();
			e.stopPropagation();
		});

		document.addEventListener('mousemove', function(e) {
			if (remoteManualPreviewState.drag) {
				var d = remoteManualPreviewState.drag;
				var left = d.left + (e.clientX - d.startX);
				var top = d.top + (e.clientY - d.startY);
				var vw = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
				var vh = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
				var rectNow = win.getBoundingClientRect();
				left = Math.max(8, Math.min(left, vw - rectNow.width - 8));
				top = Math.max(8, Math.min(top, vh - rectNow.height - 8));
				win.style.left = left + 'px';
				win.style.top = top + 'px';
			}

			if (remoteManualPreviewState.resize) {
				var r = remoteManualPreviewState.resize;
				var width = r.width + (e.clientX - r.startX);
				var height = r.height + (e.clientY - r.startY);
				var minW = Math.max(420, Math.min(520, window.innerWidth - 24));
				var minH = Math.max(280, Math.min(360, window.innerHeight - 24));
				var maxW = Math.max(minW, window.innerWidth - 16);
				var maxH = Math.max(minH, window.innerHeight - 16);
				width = Math.max(minW, Math.min(width, maxW));
				height = Math.max(minH, Math.min(height, maxH));
				win.style.width = width + 'px';
				win.style.height = height + 'px';
			}
		});

		document.addEventListener('mouseup', function() {
			remoteManualPreviewState.drag = null;
			remoteManualPreviewState.resize = null;
		});
	}

	function setupRemotePasswordScratch() {
		document.querySelectorAll('.remote-password-scratch').forEach(function(box) {
			var pwdText = box.querySelector('.remote-password-text');
			var canvas = box.querySelector('.remote-password-canvas');
			if (!pwdText || !canvas) {
				return;
			}

			var ctx = canvas.getContext('2d');
			if (!ctx) {
				return;
			}

			var revealMs = (parseInt(box.getAttribute('data-reveal-seconds'), 10) || 10) * 1000;
			var password = box.getAttribute('data-password') || '';
			var isDrawing = false;
			var hideTimer = null;

			function clearHideTimer() {
				if (hideTimer) {
					clearTimeout(hideTimer);
					hideTimer = null;
				}
			}

			function drawCover() {
				var ratio = window.devicePixelRatio || 1;
				var w = Math.max(1, Math.round(box.clientWidth));
				var h = Math.max(1, Math.round(box.clientHeight));
				canvas.width = Math.round(w * ratio);
				canvas.height = Math.round(h * ratio);
				canvas.style.width = w + 'px';
				canvas.style.height = h + 'px';
				ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
				ctx.globalCompositeOperation = 'source-over';
				ctx.clearRect(0, 0, w, h);
				var scratchDark = (document.documentElement.getAttribute('data-site-theme') === 'dark');
				ctx.fillStyle = scratchDark ? '#3a3a45' : '#e2e8f0';
				ctx.fillRect(0, 0, w, h);
				ctx.fillStyle = scratchDark ? '#c4c4cc' : '#475569';
				ctx.font = '700 10px sans-serif';
				ctx.textBaseline = 'middle';
				ctx.textAlign = 'center';
				ctx.fillText('CLICK + SCRATCH', Math.floor(w / 2), Math.floor(h / 2));
			}

			function hidePassword() {
				clearHideTimer();
				pwdText.textContent = '********';
				drawCover();
			}

			function showPasswordWithTimeout() {
				if (!password || password === '-') {
					return;
				}
				pwdText.textContent = password;
				clearHideTimer();
				hideTimer = setTimeout(function() {
					hidePassword();
				}, revealMs);
			}

			function scratchAt(clientX, clientY) {
				var rect = canvas.getBoundingClientRect();
				var x = clientX - rect.left;
				var y = clientY - rect.top;
				ctx.globalCompositeOperation = 'destination-out';
				ctx.beginPath();
				ctx.arc(x, y, 12, 0, Math.PI * 2);
				ctx.fill();
				showPasswordWithTimeout();
			}

			canvas.addEventListener('mousedown', function(e) {
				isDrawing = true;
				box.classList.add('is-scratching');
				scratchAt(e.clientX, e.clientY);
				e.preventDefault();
			});

			canvas.addEventListener('mousemove', function(e) {
				if (!isDrawing) {
					return;
				}
				scratchAt(e.clientX, e.clientY);
				e.preventDefault();
			});

			window.addEventListener('mouseup', function() {
				isDrawing = false;
				box.classList.remove('is-scratching');
			});

			canvas.addEventListener('touchstart', function(e) {
				isDrawing = true;
				box.classList.add('is-scratching');
				if (e.touches && e.touches[0]) {
					scratchAt(e.touches[0].clientX, e.touches[0].clientY);
				}
				e.preventDefault();
			}, { passive: false });

			canvas.addEventListener('touchmove', function(e) {
				if (!isDrawing) {
					return;
				}
				if (e.touches && e.touches[0]) {
					scratchAt(e.touches[0].clientX, e.touches[0].clientY);
				}
				e.preventDefault();
			}, { passive: false });

			window.addEventListener('touchend', function() {
				isDrawing = false;
				box.classList.remove('is-scratching');
			});

			window.addEventListener('resize', function() {
				hidePassword();
			});

			hidePassword();
		});
	}

    // 페이지가 로드되면 남은 시간 업데이트를 시작
    document.addEventListener('DOMContentLoaded', function() {
		updateRemainingTime();
		setupRemoteCopyButtons();
		setupRemoteManualTabs();
		setupRemotePasswordScratch();
		setupRemoteManualImagePreview();
	});
</script>

<script>
	// 1초마다 환불 금액을 실시간 업데이트
	function formatIntlNumber(value, decimals) {
		var num = Number(value);
		if (!isFinite(num)) {
			num = 0;
		}
		return new Intl.NumberFormat('en-US', {
			minimumFractionDigits: decimals,
			maximumFractionDigits: decimals
		}).format(num);
	}

	function formatIntlPoint(value, decimals) {
		return formatIntlNumber(value, decimals);
	}

	function updateRefund(odiditid, startTime, endTime, currentTime, sell_price, install_fee, gap_sec) {
		gap_sec = parseInt(gap_sec, 10) || 0;
		startTime = parseInt(startTime, 10) || 0;
		endTime = parseInt(endTime, 10) || 0;
		currentTime = parseInt(currentTime, 10) || 0;
		sell_price = parseFloat(sell_price) || 0;
		install_fee = parseFloat(install_fee) || 0;
		var _installFeeAll = sell_price + install_fee;

		const totalUsageTime = Math.max(0, endTime - startTime); // 총 사용 시간 (초 단위)
		const effTotalUsageTime = Math.max(1, totalUsageTime - gap_sec); // 갭 제외 유효 기간
		const totalUsageMinutes = effTotalUsageTime / 60;

		// 분당 요금 (0분 분모 방지)
		const minuteRate = totalUsageMinutes > 0 ? (sell_price / totalUsageMinutes) : 0;

		function formatDuration(seconds) {
			seconds = Math.max(0, Math.floor(seconds));
			const days = Math.floor(seconds / 86400);
			const hours = Math.floor((seconds % 86400) / 3600);
			const minutes = Math.floor((seconds % 3600) / 60);
			const secs = Math.floor(seconds % 60);
			return days + "일 " + String(hours).padStart(2, '0') + "시간 " + String(minutes).padStart(2, '0') + "분 " + String(secs).padStart(2, '0') + "초";
		}

		// 1초마다 현재 시간 계산
		setInterval(function() {
			currentTime = parseInt(currentTime, 10) + 1; // 현재 시간 (초 단위)
			let elapsedTimeRaw = currentTime - startTime; // 전체 경과 시간
			let elapsedTime = Math.min(Math.max(elapsedTimeRaw - gap_sec, 0), effTotalUsageTime);

			// 남은 시간 계산 (초 단위, 갭 제외 유효 기간 기준)
			let remainingTime = Math.max(0, effTotalUsageTime - elapsedTime);

			// 환불금액 계산
			let remainingMinutes = remainingTime / 60;
			let refundAmount = Math.max(0, remainingMinutes * minuteRate);
			var _cancFeeRate = <?php echo defined('VPNLINK_CANCELLATION_FEE_RATE') ? VPNLINK_CANCELLATION_FEE_RATE : 0.15; ?>;
			var _cancFeeRatePct = <?php echo (int)round((defined('VPNLINK_CANCELLATION_FEE_RATE') ? VPNLINK_CANCELLATION_FEE_RATE : 0.15) * 100); ?>;
			var _cancFeeRateCompPct = 100 - _cancFeeRatePct;
			let penaltyAmountRaw = refundAmount * _cancFeeRate;
			let refundAmountAfterPenaltyRaw = Math.max(0, refundAmount - penaltyAmountRaw);
			let penaltyAmount = Math.round(penaltyAmountRaw);
			let refundAmountAfterPenalty = Math.round(refundAmountAfterPenaltyRaw);

			// 경과된 시간
			let elapsedMinutes = elapsedTime / 60;
			let elapsedCost = Math.max(0, elapsedMinutes * minuteRate);

			// UI 업데이트 (HTML 요소의 내용을 업데이트)
			document.getElementById('elapsed_cost_' + odiditid).innerText = formatIntlPoint(elapsedCost, 2);
			document.getElementById('remaining_cost_' + odiditid).innerText = formatIntlPoint(refundAmount, 2);
			document.getElementById('penalty_amount_' + odiditid).innerText = formatIntlPoint(penaltyAmount, 0);
			document.getElementById('refund_amount_after_penalty_' + odiditid).innerText = formatIntlPoint(refundAmountAfterPenalty, 0);

			var calcGuideEl = document.getElementById('refund_calc_guide_' + odiditid);
			if (calcGuideEl) {
				var _installRow = '';
				if (install_fee > 0) {
					_installRow = '<tr><td class="rct-label">− 개통비/설치비</td><td class="rct-value">' + formatIntlNumber(install_fee, 0) + '</td></tr>';
				}
				calcGuideEl.innerHTML = '<strong>해지수수료 계산식</strong>'
					+ '<table class="refund-calc-table">'
					+ '<tr><td class="rct-label">전체 결제금액</td><td class="rct-value">' + formatIntlNumber(_installFeeAll, 0) + '</td></tr>'
					+ _installRow
					+ '<tr><td class="rct-label">= 이용요금 합계</td><td class="rct-value">' + formatIntlNumber(sell_price, 0) + '</td></tr>'
					+ '<tr class="rct-ratio-row"><td colspan="2" class="rct-ratio-cell">× 미사용비율 (' + formatDuration(remainingTime) + ' / ' + formatDuration(effTotalUsageTime) + ')</td></tr>'
					+ '<tr><td class="rct-label">= 미사용요금</td><td class="rct-value">' + formatIntlNumber(refundAmount, 2) + '</td></tr>'
					+ '<tr><td class="rct-label">× 해지수수료율</td><td class="rct-value">' + _cancFeeRatePct + '%</td></tr>'
					+ '<tr><td class="rct-label">= 해지수수료</td><td class="rct-value">' + formatIntlNumber(penaltyAmount, 0) + '</td></tr>'
					+ '<tr class="rct-result-row"><td class="rct-label">환불금액</td><td class="rct-value">' + formatIntlNumber(refundAmountAfterPenalty, 0) + ' Point</td></tr>'
					+ '</table>';

				if (refundCalcGuideContext && refundCalcGuideContext.odiditid === odiditid) {
					var modalBody = document.getElementById('refundCalcGuideBody');
					if (modalBody) {
						modalBody.innerHTML = '<div class="refund-calc-guide">' + calcGuideEl.innerHTML + '</div>';
					}
				}
			}

			// 시간 정보 업데이트 (음수 방지)
			document.getElementById('remaining_time_' + odiditid).innerText = formatDuration(remainingTime);
			document.getElementById('elapsed_time_' + odiditid).innerText = formatDuration(elapsedTime);

			// 계약상태 배지 업데이트
			var contractStatusEl = document.getElementById('contract_status_' + odiditid);
			var contractExpiredEl = document.getElementById('contract_is_expired_' + odiditid);
			var refundSubmitBtnEl = document.getElementById('refund_submit_btn_' + odiditid);
			if (contractStatusEl) {
				if (remainingTime <= 0) {
					contractStatusEl.classList.remove('active');
					contractStatusEl.classList.add('expired');
					contractStatusEl.textContent = '계약기간 만료';
					if (contractExpiredEl) contractExpiredEl.value = '1';
					if (refundSubmitBtnEl) {
						refundSubmitBtnEl.disabled = true;
						refundSubmitBtnEl.textContent = '환불불가(계약만료)';
					}
				} else {
					contractStatusEl.classList.remove('expired');
					contractStatusEl.classList.add('active');
					contractStatusEl.textContent = '계약 유지중';
					if (contractExpiredEl) contractExpiredEl.value = '0';
					if (refundSubmitBtnEl) {
						refundSubmitBtnEl.disabled = false;
						refundSubmitBtnEl.textContent = '환불받기';
					}
				}
			}

		}, 1000); // 1초마다 업데이트

	}
</script>

<script>
	function updatePaymentButton(odiditid, itid) {
		const unitElement = document.getElementById('ExtendPeriod_pricing_unit_' + odiditid);
		const countElement = document.getElementById('ExtendPeriod_pricing_count_' + odiditid);
		const daysHidden = document.getElementById('ExtendPeriod_days_' + odiditid);
		const hoursHidden = document.getElementById('ExtendPeriod_hours_' + odiditid);
		const suffixElement = document.getElementById('ExtendPeriod_pricing_suffix_' + odiditid);
		const feeGuideElement = document.getElementById('ExtendPeriod_fee_guide_' + odiditid);
		const humanHintElement = document.getElementById('ExtendPeriod_human_hint_' + odiditid);
		const autoNoticeElement = document.getElementById('ExtendPeriod_auto_notice_' + odiditid);
		const totalDisplayElement = document.getElementById('ExtendPeriod_total_disp_' + odiditid);

		if (!unitElement || !countElement || !daysHidden || !hoursHidden) {
			console.error('Extension pricing elements not found');
			return;
		}

		const unit = String(unitElement.value || 'hour');
		let count = parseInt(countElement.value, 10);
		if (isNaN(count) || count < 1) {
			count = 1;
			countElement.value = '1';
		}

		function unitHours(u) {
			if (u === 'day') return 24;
			if (u === 'month') return 24 * 30;
			if (u === 'year') return 24 * 365;
			return 1;
		}

		function unitDiscount(u) {
			if (u === 'day') return parseFloat(unitElement.dataset.discountDay || '1') || 1;
			if (u === 'month') return parseFloat(unitElement.dataset.discountMonth || '1') || 1;
			if (u === 'year') return parseFloat(unitElement.dataset.discountYear || '1') || 1;
			return parseFloat(unitElement.dataset.discountHour || '1') || 1;
		}

		function isAllowedUnit(u) {
			if (u === 'day') return String(unitElement.dataset.allowDay || '0') === '1';
			if (u === 'month') return String(unitElement.dataset.allowMonth || '0') === '1';
			if (u === 'year') return String(unitElement.dataset.allowYear || '0') === '1';
			return String(unitElement.dataset.allowHour || '0') === '1';
		}

		function bestAllowedUnit(totalHours, fallbackUnit) {
			const units = ['hour', 'day', 'month', 'year'];
			let bestUnit = '';
			let bestTotal = null;

			for (let i = 0; i < units.length; i++) {
				const u = units[i];
				if (!isAllowedUnit(u)) continue;
				const unitH = unitHours(u);
				const packagePrice = Math.round(hourlyPrice * unitDiscount(u) * unitH);
				const lineTotal = Math.max(1, Math.ceil(totalHours / unitH)) * packagePrice;
				if (bestTotal === null || lineTotal < bestTotal) {
					bestTotal = lineTotal;
					bestUnit = u;
				}
			}

			if (!bestUnit && fallbackUnit && isAllowedUnit(fallbackUnit)) {
				bestUnit = fallbackUnit;
			}
			if (!bestUnit) {
				bestUnit = 'hour';
			}

			return bestUnit;
		}

		function unitSuffix(u) {
			if (u === 'day') return '일';
			if (u === 'month') return '개월';
			if (u === 'year') return '년';
			return '시간';
		}

		function unitLabel(u) {
			if (u === 'day') return '1일 이용권';
			if (u === 'month') return '1개월(30일) 이용권';
			if (u === 'year') return '1년(365일) 이용권';
			return '1시간 이용권';
		}

		const hourlyPrice = parseFloat(unitElement.dataset.hourlyPrice || '0') || 0;
		const packageHours = unitHours(unit);
		const totalHours = Math.max(1, count * packageHours);

		const autoUnit = bestAllowedUnit(totalHours, unit);
		const autoUnitHours = unitHours(autoUnit);
		const autoPackagePrice = Math.round(hourlyPrice * unitDiscount(autoUnit) * autoUnitHours);
		const autoCount = Math.max(1, Math.ceil(totalHours / autoUnitHours));
		const totalAmount = Math.round(autoCount * autoPackagePrice);

		const selected_days = Math.floor(totalHours / 24);
		const selected_hours = totalHours % 24;

		daysHidden.value = String(selected_days);
		hoursHidden.value = String(selected_hours);
		if (suffixElement) {
			suffixElement.textContent = unitSuffix(unit);
		}

		if (feeGuideElement) {
			const key = 'fee' + unit.charAt(0).toUpperCase() + unit.slice(1);
			const feeText = unitElement.dataset[key] || '-';
			feeGuideElement.textContent = feeText;
		}

		if (humanHintElement) {
			humanHintElement.textContent = '선택기간: ' + contractHoursText(totalHours);
		}

		if (autoNoticeElement) {
			if (autoUnit !== unit || autoCount !== count) {
				autoNoticeElement.style.display = 'block';
				autoNoticeElement.textContent = '자동최저가 적용됨';
			} else {
				autoNoticeElement.style.display = 'none';
				autoNoticeElement.textContent = '';
			}
		}

		if (totalDisplayElement) {
			totalDisplayElement.textContent = number_format(String(totalAmount));
		}

        // Update the total amount in the corresponding input element
        $('#ExtendPeriod_amount_' + odiditid).val(totalAmount);

        const paymentButton = document.getElementById('paymentButton_' + odiditid);
        if (paymentButton) {
            // Prepare the check code in PHP
            <?php $check_code = md5(md5(md5(md5(md5($member['mb_id'] . "Ž" . $member['mb_today_login']))))); ?>

            const xhr = new XMLHttpRequest();
            xhr.open('POST', '/mylib/ajax_get_check_points.php', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

            xhr.onreadystatechange = function() {
                if (xhr.readyState === XMLHttpRequest.DONE) {
                    if (xhr.status === 200) {
                        const response = JSON.parse(xhr.responseText);
                        if (response.success) {
                            paymentButton.disabled = false;
                            $("#paymentButton_msg_" + odiditid).hide();
                            $("#ExtendPeriod_datetime_" + odiditid).val(response.ExtendPeriod_datetime);
                        } else if (response.fail) {
                            paymentButton.disabled = true;
                            $("#paymentButton_msg_" + odiditid).show();
                            $("#paymentButton_msg_" + odiditid).html(response.message);
                            $("#ExtendPeriod_datetime_" + odiditid).val(response.ExtendPeriod_datetime);
                        }
                    } else {
                        console.error('AJAX request failed:', xhr.statusText);
                    }
                }
            };

            xhr.send('totalAmount=' + encodeURIComponent(totalAmount)
                + '&mbid=' + encodeURIComponent('<?php echo $member['mb_id']?>')
                + '&itid=' + encodeURIComponent(itid)
                + '&selected_days=' + encodeURIComponent(selected_days)
                + '&selected_hours=' + encodeURIComponent(selected_hours)
                + '&q=' + encodeURIComponent('<?php echo $check_code?>'));
        } else {
            console.error('Payment button not found');
        }
    }
</script>

