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

require_once(G5_PATH.'/mylib/rpc_grade.lib.php');

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>';
    }
}

if (!function_exists('apms_item_is_vpn_like')) {
	function apms_item_is_vpn_like($it) {
		$item_name_upper = strtoupper(trim((string)(isset($it['it_name']) ? $it['it_name'] : '').' '.(string)(isset($it['pt_it']) ? $it['pt_it'] : '')));
		return (strpos($item_name_upper, 'VPN') !== false && strpos($item_name_upper, 'RPC') === false);
	}
}

$orderform_vpn_item_count = 0;
$orderform_rpc_item_count = 0;
for ($oi = 0; $oi < count($item); $oi++) {
	$orderform_item_name_upper = strtoupper(trim((string)$item[$oi]['it_name'].' '.(string)$item[$oi]['pt_it']));
	if (apms_item_is_vpn_like($item[$oi])) {
		$orderform_vpn_item_count++;
	}
	if (strpos($orderform_item_name_upper, 'RPC') !== false || strpos($orderform_item_name_upper, 'REMOTE') !== false) {
		$orderform_rpc_item_count++;
	}
}
$orderform_is_mixed_types = ($orderform_vpn_item_count > 0 && $orderform_rpc_item_count > 0);

if ($orderform_is_mixed_types) {
	usort($item, function($a, $b) {
		$a_vpn = apms_item_is_vpn_like($a) ? 1 : 0;
		$b_vpn = apms_item_is_vpn_like($b) ? 1 : 0;
		if ($a_vpn === $b_vpn) {
			return 0;
		}
		return ($a_vpn > $b_vpn) ? -1 : 1;
	});
}

$orderform_first_col_label = ($orderform_vpn_item_count > 0 && $orderform_rpc_item_count === 0) ? 'VPN종류' : '운영체제';
?>

<div class="well well-sm">
	<i class="fa fa-shopping-cart fa-lg"></i> 주문하실 상품을 확인해 주세요.
</div>

<style>
	.voucher-info-wrap {
		display: inline;
		margin-left: 3px;
	}
	.voucher-info-btn {
		display: inline-block;
		border: 0;
		background: transparent;
		padding: 0;
		line-height: 1;
		color: #4b79c9;
		cursor: pointer;
	}
	.voucher-info-btn:hover { color: #355ea1; }
	.voucher-info-btn .fa-info-circle { font-size: 15px; vertical-align: middle; }

	/* 툴팁 레이어 (hover 팝업) */
	.voucher-calc-layer {
		display: none;
		position: fixed;
		z-index: 9999;
		filter: drop-shadow(0 8px 24px rgba(0,0,0,0.22));
	}
	.voucher-calc-backdrop { display: none; }
	.voucher-calc-panel {
		position: relative;
		width: 340px;
		max-width: calc(100vw - 24px);
		background: #fff;
		border: 1px solid #e2e8f0;
		border-radius: 10px;
		overflow: hidden;
	}
	/* 말풍선 꼬리 */
	.voucher-calc-panel::before {
		content: '';
		position: absolute;
		top: -7px;
		left: var(--tail-left, 18px);
		width: 13px;
		height: 13px;
		background: #f6f8fc;
		border-left: 1px solid #e2e8f0;
		border-top: 1px solid #e2e8f0;
		transform: rotate(45deg);
		border-radius: 2px 0 0 0;
	}
	.voucher-calc-head {
		padding: 10px 12px;
		background: #f6f8fc;
		border-bottom: 1px solid #e5e9f2;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.voucher-calc-close {
		border: 0;
		background: transparent;
		font-size: 19px;
		line-height: 1;
		padding: 1px 2px;
		cursor: pointer;
		color: #555;
	}
	.voucher-calc-body {
		padding: 12px;
		font-size: 12px;
		line-height: 1.55;
		color: #2f2f2f;
	}
	.voucher-calc-body div { margin-bottom: 2px; }
	.voucher-calc-body div:last-child { margin-bottom: 0; }
	.voucher-calc-body .formula { font-weight: 600; color: #1f1f1f; }

	/* 다크모드 */
	[data-site-theme="dark"] .voucher-calc-panel {
		background: #1e1e24;
		border-color: #3a3a42;
	}
	[data-site-theme="dark"] .voucher-calc-panel::before {
		background: #252528;
		border-color: #3a3a42;
	}
	[data-site-theme="dark"] .voucher-calc-head {
		background: #252528;
		border-bottom-color: #3a3a42;
	}
	[data-site-theme="dark"] .voucher-calc-head strong { color: #e4e4e7; }
	[data-site-theme="dark"] .voucher-calc-close { color: #a1a1aa; }
	[data-site-theme="dark"] .voucher-calc-close:hover { color: #e4e4e7; }
	[data-site-theme="dark"] .voucher-calc-body { color: #c4c4cc; }
	[data-site-theme="dark"] .voucher-calc-body .formula { color: #e4e4e7; }
	[data-site-theme="dark"] .voucher-calc-body [style*="color:#666"],
	[data-site-theme="dark"] .voucher-calc-body [style*="color: #666"] { color: #9ca3af !important; }
	[data-site-theme="dark"] .voucher-calc-body [style*="color:#888"],
	[data-site-theme="dark"] .voucher-calc-body [style*="color: #888"] { color: #71717a !important; }
	[data-site-theme="dark"] .voucher-calc-body [style*="color:#4b79c9"],
	[data-site-theme="dark"] .voucher-calc-body [style*="color: #4b79c9"] { color: #60a5fa !important; }
</style>

<div class="table-responsive order-item">
	<table id="sod_list" class="div-table table bg-white bsk-tbl">
	<tbody>
	<?php if(!$orderform_is_mixed_types) { ?>
	<tr class="<?php echo $head_class;?>">
		<th scope="col"><span><?php echo $orderform_first_col_label; ?></span></th>
		<th scope="col"><span>상품명</span></th>
		<th scope="col"><span>판매자</span></th>
		<th scope="col"><span>주문기간</span></th>
		<th scope="col"><span>이용권 금액</span></th>
		<th scope="col"><span>개통비/설치비</span></th>
		<th scope="col"><span>쿠폰</span></th>
		<th scope="col"><span>소계</span></th>
		<!-- <th scope="col"><span>적립포인트</span></th> -->
		<!-- <th scope="col"><span class="last">배송비</span></th> -->
	</tr>
	<?php } ?>

	<?php
	$orderform_prev_group_type = '';
	for($i=0; $i < count($item); $i++) {
		$orderform_row_is_vpn = apms_item_is_vpn_like($item[$i]);
		$orderform_group_type = $orderform_row_is_vpn ? 'vpn' : 'rpc';
		if($orderform_is_mixed_types && $orderform_prev_group_type !== $orderform_group_type) {
			$orderform_section_label = $orderform_row_is_vpn ? 'VPN종류' : '운영체제';
			$orderform_section_title = $orderform_row_is_vpn ? 'VPN 상품' : 'RPC 상품';
	?>
		<tr>
			<td colspan="8" class="text-left" style="background:#f8fafc; font-weight:700; color:#334155; border-top:2px solid #dbe2ea;">
				<?php echo $orderform_section_title; ?>
			</td>
		</tr>
		<tr class="<?php echo $head_class;?>">
			<th scope="col"><span><?php echo $orderform_section_label; ?></span></th>
			<th scope="col"><span>상품명</span></th>
			<th scope="col"><span>판매자</span></th>
			<th scope="col"><span>주문기간</span></th>
			<th scope="col"><span>이용권 금액</span></th>
			<th scope="col"><span>개통비/설치비</span></th>
			<th scope="col"><span>쿠폰</span></th>
			<th scope="col"><span>소계</span></th>
		</tr>
	<?php
			$orderform_prev_group_type = $orderform_group_type;
		}
	?>
		<tr<?php echo ($i == 0) ? ' class="tr-line"' : '';?>>
			<td class="text-center">
				<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
							$row_os = sql_fetch("SELECT * FROM {$g5['g5_shop_item_table']} WHERE it_id='{$item[$i]['it_id']}'");
							$item_pt_it_raw = isset($item[$i]['pt_it']) ? trim((string)$item[$i]['pt_it']) : '';
							$item_name_raw = isset($item[$i]['it_name']) ? trim((string)$item[$i]['it_name']) : '';
							$row_pt_it_raw = isset($row_os['pt_it']) ? trim((string)$row_os['pt_it']) : '';
							$row_item_name_raw = isset($row_os['it_name']) ? trim((string)$row_os['it_name']) : '';
							$row_ca_id_raw = isset($row_os['ca_id']) ? (string)$row_os['ca_id'] : '';
							$is_vpn_product = (
								preg_match('/^VPN/i', $item_pt_it_raw)
								|| preg_match('/^VPN/i', $row_pt_it_raw)
								|| preg_match('/^VPN/i', $item_name_raw)
								|| preg_match('/^VPN/i', $row_item_name_raw)
								|| in_array(substr($row_ca_id_raw, 0, 2), ['30', '40'], true)
							);
							echo trim(str_ireplace(array("Microsoft", "Windows"), array("", "Win"), $row_os['it_spec_os']));
						?>
					</div>
				</div>
			</td>
			<td>
				<input type="hidden" name="it_id[<?php echo $i; ?>]"    value="<?php echo $item[$i]['hidden_it_id']; ?>">
				<input type="hidden" name="it_name[<?php echo $i; ?>]"  value="<?php echo $item[$i]['hidden_it_name']; ?>">
				<input type="hidden" name="it_price[<?php echo $i; ?>]" value="<?php echo $item[$i]['hidden_sell_price']; ?>">
				<input type="hidden" name="cp_id[<?php echo $i; ?>]" value="<?php echo $item[$i]['hidden_cp_id']; ?>">
				<input type="hidden" name="cp_price[<?php echo $i; ?>]" value="<?php echo $item[$i]['hidden_cp_price']; ?>">
				<?php if($default['de_tax_flag_use']) { ?>
					<input type="hidden" name="it_notax[<?php echo $i; ?>]" value="<?php echo $item[$i]['hidden_it_notax']; ?>">
				<?php } ?>
				[<?php echo $item[$i]['pt_it']; ?>] <?php if($is_vpn_product) { echo vpn_category_badge_html(isset($row_os['it_spec_os']) ? $row_os['it_spec_os'] : ''); } else { echo rpc_category_badge_html(isset($row_os['ca_id']) ? $row_os['ca_id'] : ''); } echo vpn_grade_badge_html(isset($row_os['it_spec_grade']) ? $row_os['it_spec_grade'] : ''); ?><b><?php echo $item[$i]['it_name']; ?></b>
				<?php if($item[$i]['it_options']) { ?>
					<!-- <div class="well well-sm"><?php echo $item[$i]['it_options'];?></div> -->
				<?php } ?>
				<div>
					<style>
						table {
							width: 100%;
							border-collapse: collapse;
							margin-top: 3px;
							margin-bottom: 5px;
							box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
							font-size: 0.9em;
						}
						th, td {
							padding: 3px;
							text-align: left;
							border: 1px solid #ddd;
						}
						th {
							background-color: #f4f4f4;
							font-weight: bold;
							text-transform: uppercase;
						}
						tr:nth-child(even) {
							background-color: #f9f9f9;
						}
						tr:hover {
							background-color: #f1f1f1;
						}
						.center {
							text-align: center;
						}
						.right {
							text-align: right;
						}
						#table1 .nation_flag_img2 {
							width: 25px;
							height: 17px;
							margin-left: 0px;
							margin-right: 5px;
						}
						@media screen and (max-width: 600px) {
							#table1 .flags-icons img {
								max-height: 30px;
								margin-right: 3px;
							}
							#table1 .nation_flag_img2 {
								width: 25px;
								height: 17px;
								margin-left: 0px;
								margin-right: 5px;
							}
						}
					</style>

					<table id="table1">
						<tr>
							<!-- <th>PC No.</th>
							<th>DAILY FEE</th>
							<th>DAILY EXT. FEE</th> -->
							<th>IP할당국가</th>
							<?php if ($is_vpn_product) { ?>
								<th>VPN종류</th>
								<th>연결가능OS</th>
							<?php } else { ?>
								<!-- <th>IP</th> -->
								<!-- <th>OS</th> -->
								<th>CPU</th>
								<th>GPU</th>
								<th>RAM</th>
								<th>SSD</th>
								<th>HDD</th>
							<?php } ?>
						</tr>
						<?php
							$result_api_data = sql_query("SELECT * FROM {$g5['g5_shop_item_table']} WHERE it_id='{$item[$i]['it_id']}'");
							while($api_data = sql_fetch_array($result_api_data)){
								$it_id = $api_data['it_id'];
								if ($api_data['it_origin_mgr_from_api']) {
									// comviewers.comŽRnDŽRnD서버실
									$M_store_arr = explode("Ž", $api_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 = $api_data['pt_id']; // partner id

								// JSON 데이터
								$jsonData_it_spec_remote_sw = $api_data['it_spec_remote_sw'];

								// JSON 데이터를 배열로 디코드
								$dataArray_it_spec_remote_sw = json_decode($jsonData_it_spec_remote_sw, true);

								// RemoteIP 값을 추출하여 $extIP 변수에 저장
								$extIP = isset($dataArray_it_spec_remote_sw[0]['RemoteIP__0']) ? $dataArray_it_spec_remote_sw[0]['RemoteIP__0'] : null;
								$remote_ip_org = explode(" ", $extIP)[0];
								$remote_ip_parts = explode(".", $remote_ip_org); // IP 주소를 점(.)으로 분리

								// 각 부분을 3자리로 맞추기 위해 앞에 0을 추가
								foreach ($remote_ip_parts as &$part) {
									$part = str_pad($part, 3, '0', STR_PAD_LEFT);
								}
								// 마스킹할 부분을 선택
								$remote_ip_parts[1] = '***';
								$remote_ip_parts[3] = '***';
								// 마스킹된 IP 주소를 다시 조합
								$masked_ip = implode(".", $remote_ip_parts);
								$remote_ip = $masked_ip; // 출력: 111.***.022.***

								$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']) ? $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'] : '';
								$remote_ip_country_flag = ($remote_ip_country_code !== '') ? "<img src='" . G5_DATA_URL . "/item/img_nation_flag/svg/{$remote_ip_country_code}.svg' class='nation_flag_img2'>" : '';

								$it_spec_remote_sw_arr = [];
								for ($i_sw = 0; $i_sw < count($dataArray_it_spec_remote_sw); $i_sw++) {
									$it_spec_remote_sw_arr[] = $dataArray_it_spec_remote_sw[$i_sw]['Program__' . $i_sw];
								}
								$it_spec_remote_sw_disp = implode(" , ", $it_spec_remote_sw_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", ""), $api_data['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("", "", "", "", "", "", ""), $api_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 = $api_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 = $api_data['it_spec_mainboard'];
								$it_spec_ram = trim($api_data['it_spec_ram_type'] . " " . $api_data['it_spec_ram']);
								//$SSDinfo = $api_data['SSDinfo'];
								$it_spec_ssd =  $api_data['it_spec_ssd'] === "0 GB" ? "<div style='width:100%; min-width:40px; text-align:left;'>Not installed</div>" : trim($api_data['it_spec_ssd_type'] . " " . $api_data['it_spec_ssd']);
								//$SSD = $api_data['SSD'];
								//$HDDinfo = $api_data['HDDinfo'];
								$it_spec_hdd = $api_data['it_spec_hdd'] === "0 GB" ? "<div style='width:100%; min-width:40px; text-align:left;'>Not installed</div>" : trim($api_data['it_spec_hdd_type'] . " " . $api_data['it_spec_hdd']);
								//$HDD = $api_data['HDD'];
								$it_spec_gpu_arr = explode("Ž", trim(str_ireplace(array("(R)", "(TM)"), array("", ""), $api_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 = $api_data['gpu_ram'];

								//$it_spec_os = trim(str_ireplace(array("Microsoft", "Windows", "(64Bit)"), array("", "Win", ""), $api_data['it_spec_os']));
								$it_spec_os = trim($api_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 = $api_data['rantal_fee_type'];
								// $rental_fee = $api_data['rental_fee'];
								// $rental_setting_fee = $api_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 = $api_data['rental_stat'];
								// $client_number = $api_data['client_number'];
								// $cpu_clock = $api_data['cpu_clock'];
								// $AppVer = $api_data['AppVer'];

								$it_spec_keyboard = !empty(trim($api_data['it_spec_keyboard'])) ? "KEYBOARD(O)" : "KEYBOARD(X)";
								$it_spec_mouse = !empty(trim($api_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_product) {
									echo "<td class='center'>IKEv2-VPN</td>";
									echo "<td class='center'>Windows, MacOS, Linux, Android, iOS</td>";
								} else {
									//echo "<td class='center'>".$ip."</td>";
									//echo "<td class='center'>".$OperatingSystem."</td>";
									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>";
							}
						?>
					</table>
				</div>
			</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 !== '') {
						$seller_mb = get_member($seller_pt_id, 'mb_nick');
						$seller_nick = isset($seller_mb['mb_nick']) ? trim((string)$seller_mb['mb_nick']) : '';
					}
					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>
			<?php
				$order_contract_hours = apms_contract_hours_from_day_hour((int)$item[$i]['ct_qty'], (int)$item[$i]['ct_qty_hour']);
				$order_unit = apms_pricing_unit_from_day_hour((int)$item[$i]['ct_qty'], (int)$item[$i]['ct_qty_hour']);
				$order_count = apms_pricing_count_from_day_hour((int)$item[$i]['ct_qty'], (int)$item[$i]['ct_qty_hour'], $order_unit);
				$order_license_price = isset($item[$i]['license_price']) ? (int)$item[$i]['license_price'] : (int)$item[$i]['ct_price'];
				$order_unit_price = (int)$item[$i]['ct_price'];
				$order_base_amount = (int)$order_unit_price * (int)$order_contract_hours;
				$order_extra_amount = $order_license_price - $order_base_amount;
			?>
			<td class="text-center">
				<?php echo apms_contract_hours_text($order_contract_hours); ?>
			</td>
			<td class="text-right">
				<?php echo number_format($order_license_price); ?> Point
				<div class="voucher-info-wrap">
					<button type="button" class="voucher-info-btn"
						data-license-price="<?php echo (int)$order_license_price; ?>"
						data-unit-price="<?php echo (int)$order_unit_price; ?>"
						data-contract-hours="<?php echo (int)$order_contract_hours; ?>"
						data-extra-price="<?php echo (int)$order_extra_amount; ?>">
						<i class="fa fa-info-circle" aria-hidden="true"></i>
					</button>
				</div>
			</td>
			<td class="text-right"><?php echo number_format($item[$i]['ct_install_price']); ?> Point</td>
			<td class="text-center">
				<?php if($item[$i]['is_coupon']) { ?>
					<div class="btn-group">
						<button type="button" class="cp_btn btn btn-black btn-xs">적용</button>
					</div>
				<?php } else { ?>
					-
				<?php } ?>
			</td>
			<td class="text-right"><b><?php echo number_format($item[$i]['total_price']); ?> Point</b></td>
			<!-- <td class="text-right">+<?php echo number_format($item[$i]['point']); ?>포인트</td> -->
			<!-- <td class="text-center"><?php echo number_format($item[$i]['ct_send_cost']); ?>포인트</td> -->
		</tr>
	<?php } ?>
	</tbody>
	</table>
</div>

<div id="voucherCalcLayer" class="voucher-calc-layer" aria-hidden="true">
	<div class="voucher-calc-backdrop"></div>
	<div class="voucher-calc-panel" role="dialog" aria-modal="true" aria-label="이용권 금액 계산식">
		<div class="voucher-calc-head">
			<strong>이용권 금액 계산식</strong>
			<button type="button" class="voucher-calc-close" aria-label="닫기">&times;</button>
		</div>
		<div class="voucher-calc-body" id="voucherCalcDetail"></div>
	</div>
</div>

<script>
	(function($) {
		function numberFormat(n) {
			var num = parseInt(n, 10);
			if (isNaN(num)) num = 0;
			return num.toLocaleString('ko-KR');
		}

		var $layer = $('#voucherCalcLayer');
		var hideTimer = null;

		function buildHtml($btn) {
			var licensePrice  = parseInt($btn.data('license-price'),   10) || 0;
			var unitPrice     = parseInt($btn.data('unit-price'),       10) || 0;
			var contractHours = parseInt($btn.data('contract-hours'),   10) || 0;
			var extraPrice    = parseInt($btn.data('extra-price'),      10) || 0;
			var extraText  = (extraPrice >= 0 ? '+ ' : '- ') + numberFormat(Math.abs(extraPrice));
			var extraGuide = extraPrice > 0
				? '옵션/추가금액이 반영되어 금액이 추가되었습니다.'
				: (extraPrice < 0
					? '할인/보정 항목이 반영되어 금액이 차감되었습니다.'
					: '');
			return ''
				+ '<div><strong>이용권 금액 계산 안내</strong></div>'
				+ '<div class="formula" style="margin-top:8px;">계산식: (시간단가 × 총 이용시간) + 옵션/추가금액</div>'
				+ '<div class="formula">= (' + numberFormat(unitPrice) + ' × ' + numberFormat(contractHours) + ') ' + extraText + ' = ' + numberFormat(licensePrice) + ' Point</div>'
				+ '<div style="margin-top:8px; color:#666;">• 시간단가: 1시간 기준 금액</div>'
				+ '<div style="color:#666;">• 총 이용시간: 주문기간을 시간으로 환산한 값</div>'
				+ '<div style="color:#666;">• 옵션/추가금액: 선택옵션/사용량 과금 등 부가 금액 합계</div>'
				+ (extraGuide ? '<div style="margin-top:8px; color:#4b79c9;">※ ' + extraGuide + '</div>' : '');
		}

		function positionAndShow($btn) {
			clearTimeout(hideTimer);
			var rect   = $btn[0].getBoundingClientRect();
			var panelW = 340;
			var left   = rect.left + rect.width / 2 - 22; /* 꼬리 위치 맞춤 */
			var top    = rect.bottom + 10;

			/* 오른쪽 화면 밖으로 나가지 않도록 */
			var maxLeft = window.innerWidth - panelW - 12;
			if (left > maxLeft) left = maxLeft;
			if (left < 8) left = 8;

			/* 꼬리 삼각형 left 위치 보정 */
			var tailLeft = (rect.left + rect.width / 2) - left - 6;
			tailLeft = Math.max(8, Math.min(tailLeft, panelW - 24));
			$layer.find('.voucher-calc-panel').css('--tail-left', tailLeft + 'px');

			$('#voucherCalcDetail').html(buildHtml($btn));
			$layer.css({ left: left, top: top }).fadeIn(80).attr('aria-hidden', 'false');
		}

		function scheduleHide() {
			hideTimer = setTimeout(function() {
				$layer.fadeOut(80).attr('aria-hidden', 'true');
			}, 160);
		}

		/* ── hover (마우스) ── */
		$(document).on('mouseenter', '.voucher-info-btn', function() {
			positionAndShow($(this));
		}).on('mouseleave', '.voucher-info-btn', function() {
			scheduleHide();
		});

		$layer.on('mouseenter', function() {
			clearTimeout(hideTimer);
		}).on('mouseleave', function() {
			scheduleHide();
		});

		/* ── 닫기 버튼 / ESC (터치·접근성 지원) ── */
		$(document).on('click', '.voucher-calc-close', function() {
			$layer.fadeOut(80).attr('aria-hidden', 'true');
		});
		$(document).on('keydown', function(e) {
			if (e.key === 'Escape') $layer.fadeOut(80).attr('aria-hidden', 'true');
		});

		/* ── 터치 디바이스: 버튼 탭으로 토글 ── */
		$(document).on('click', '.voucher-info-btn', function(e) {
			if (!window.matchMedia('(hover: hover)').matches) {
				if ($layer.is(':visible')) {
					$layer.fadeOut(80).attr('aria-hidden', 'true');
				} else {
					positionAndShow($(this));
				}
			}
		});
	})(jQuery);
</script>

<?php if ($goods_count) $goods .= ' 외 '.$goods_count.'건'; ?>

<!-- 주문상품 합계 시작 { -->
<div class="well">
	<div class="row">
		<!-- <div class="col-xs-6">주문합계</div>
		<div class="col-xs-6 text-right">
			<strong><?php echo number_format($tot_sell_price); ?> 포인트</strong>
		</div> -->
		<?php if($it_cp_count > 0) { ?>
			<div class="col-xs-6">쿠폰할인</div>
			<div class="col-xs-6 text-right">
				<strong id="ct_tot_coupon">0 Point</strong>
			</div>
		<?php } ?>
		<!-- <div class="col-xs-6">배송비</div>
		<div class="col-xs-6 text-right">
			<strong><?php echo number_format($send_cost); ?> 포인트</strong>
		</div> -->
	</div>

	<div class="row">
		<?php $tot_price = $tot_sell_price + $send_cost; // 총계 = 주문상품금액합계 + 배송비 ?>
		<div class="col-xs-6 red"> <b>주문합계</b></div>
		<div class="col-xs-6 text-right red">
			<strong id="ct_tot_price"><?php echo number_format($tot_price); ?> Point</strong>
		</div>
	</div>

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