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

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

// 목록헤드
if(isset($wset['chead']) && $wset['chead']) {
	add_stylesheet('<link rel="stylesheet" href="'.G5_CSS_URL.'/head/'.$wset['chead'].'.css" media="screen">', 0);
	$head_class = 'list-head';
} else {
	$head_class = (isset($wset['ccolor']) && $wset['ccolor']) ? 'tr-head border-'.$wset['ccolor'] : 'tr-head border-black';
}

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

?>

<?php
$cart_vpn_item_count = 0;
$cart_rpc_item_count = 0;

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

for ($ci = 0; $ci < count($item); $ci++) {
	$cart_item_name_upper = strtoupper(trim((string)$item[$ci]['it_name'].' '.(string)$item[$ci]['pt_it']));
	if (apms_item_is_vpn_like($item[$ci])) {
		$cart_vpn_item_count++;
	}
	if (strpos($cart_item_name_upper, 'RPC') !== false || strpos($cart_item_name_upper, 'REMOTE') !== false) {
		$cart_rpc_item_count++;
	}
}
$cart_is_mixed_types = ($cart_vpn_item_count > 0 && $cart_rpc_item_count > 0);

if ($cart_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;
	});
}

$cart_first_col_label = ($cart_vpn_item_count > 0 && $cart_rpc_item_count === 0) ? 'VPN종류' : '운영체제';
?>

<script src="<?php echo $skin_url;?>/shop.js"></script>

<style>
	.voucher-info-wrap {
		margin-top: 4px;
		position: relative;
		display: inline-block;
	}
	.voucher-info-btn {
		display: inline-block;
		border: 0;
		background: transparent;
		padding: 0;
		line-height: 1;
		font-size: 18px;
		color: #4b79c9;
		cursor: pointer;
	}
	.voucher-info-btn:hover,
	.voucher-info-btn:focus { color: #355ea1; }
	.voucher-info-tip {
		position: fixed;
		left: 0;
		top: 0;
		transform: translateY(6px);
		min-width: 280px;
		max-width: 420px;
		padding: 10px 12px;
		border-radius: 10px;
		background: #fff;
		border: 1px solid #dfe5f1;
		box-shadow: 0 12px 28px rgba(25, 37, 63, 0.22);
		font-size: 12px;
		line-height: 1.55;
		color: #2f2f2f;
		text-align: left;
		opacity: 0;
		visibility: hidden;
		pointer-events: none;
		transition: opacity .16s ease, transform .16s ease, visibility .16s ease;
		z-index: 130;
	}
	.voucher-info-tip .formula {
		font-weight: 600;
		color: #1f1f1f;
	}
	.voucher-info-tip:after {
		content: '';
		position: absolute;
		left: var(--voucher-tip-arrow-left, 50%);
		width: 12px;
		height: 12px;
		background: #fff;
		transform: translateX(-50%) rotate(45deg);
	}
	.voucher-info-tip[data-place="top"]:after {
		bottom: -7px;
		border-right: 1px solid #dfe5f1;
		border-bottom: 1px solid #dfe5f1;
	}
	.voucher-info-tip[data-place="bottom"]:after {
		top: -7px;
		border-left: 1px solid #dfe5f1;
		border-top: 1px solid #dfe5f1;
	}
	.install-info-wrap {
		margin-top: 4px;
		position: relative;
		display: inline-block;
	}
	.install-info-btn {
		display: inline-block;
		border: 0;
		background: transparent;
		padding: 0;
		line-height: 1;
		font-size: 18px;
		color: #4b79c9;
		cursor: pointer;
	}
	.install-info-btn:hover,
	.install-info-btn:focus { color: #355ea1; }
	.install-info-tip {
		position: fixed;
		left: 0;
		top: 0;
		transform: translateY(6px);
		min-width: 260px;
		max-width: 360px;
		padding: 10px 12px;
		border-radius: 10px;
		background: #fff;
		border: 1px solid #dfe5f1;
		box-shadow: 0 12px 28px rgba(25, 37, 63, 0.22);
		font-size: 12px;
		line-height: 1.55;
		color: #2f2f2f;
		text-align: left;
		opacity: 0;
		visibility: hidden;
		pointer-events: none;
		transition: opacity .16s ease, transform .16s ease, visibility .16s ease;
		z-index: 120;
	}
	.install-info-tip:after {
		content: '';
		position: absolute;
		left: var(--install-tip-arrow-left, 50%);
		width: 12px;
		height: 12px;
		background: #fff;
		transform: translateX(-50%) rotate(45deg);
	}
	.install-info-tip[data-place="top"]:after {
		bottom: -7px;
		border-right: 1px solid #dfe5f1;
		border-bottom: 1px solid #dfe5f1;
	}
	.install-info-tip[data-place="bottom"]:after {
		top: -7px;
		border-left: 1px solid #dfe5f1;
		border-top: 1px solid #dfe5f1;
	}
	.tip-wrap.is-open .install-info-tip,
	.tip-wrap.is-open .voucher-info-tip {
		opacity: 1;
		visibility: visible;
		transform: translateY(0);
	}
	/* 툴팁 다크모드 */
	[data-site-theme="dark"] .voucher-info-tip,
	[data-site-theme="dark"] .install-info-tip {
		background: #1e1e24;
		border-color: #3a3a42;
		color: #c4c4cc;
		box-shadow: 0 12px 28px rgba(0, 0, 0, 0.45);
	}
	[data-site-theme="dark"] .voucher-info-tip .formula,
	[data-site-theme="dark"] .voucher-info-tip strong,
	[data-site-theme="dark"] .install-info-tip strong {
		color: #e4e4e7;
	}
	[data-site-theme="dark"] .voucher-info-tip:after,
	[data-site-theme="dark"] .install-info-tip:after {
		background: #1e1e24;
	}
	[data-site-theme="dark"] .voucher-info-tip[data-place="top"]:after,
	[data-site-theme="dark"] .install-info-tip[data-place="top"]:after {
		border-right-color: #3a3a42;
		border-bottom-color: #3a3a42;
	}
	[data-site-theme="dark"] .voucher-info-tip[data-place="bottom"]:after,
	[data-site-theme="dark"] .install-info-tip[data-place="bottom"]:after {
		border-left-color: #3a3a42;
		border-top-color: #3a3a42;
	}
	[data-site-theme="dark"] .voucher-info-tip [style*="color:#666"],
	[data-site-theme="dark"] .voucher-info-tip [style*="color: #666"],
	[data-site-theme="dark"] .install-info-tip [style*="color:#666"],
	[data-site-theme="dark"] .install-info-tip [style*="color: #666"] {
		color: #9ca3af !important;
	}
	.bsk-tbl .text-right,
	.bsk-tbl .text-center {
		font-variant-numeric: tabular-nums;
		font-feature-settings: "tnum" 1, "lnum" 1;
	}
</style>

<!-- Modal -->
<div class="modal fade" id="cartModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
		<div id="mod_option_box"></div>
	  </div>
    </div>
  </div>
</div>

<?php // $action_url = /shop/cartupdate.php ?>
<form name="frmcartlist" id="sod_bsk_list" method="post" action="<?php echo $action_url; ?>" class="form" role="form">
	<div class="text-muted" style="margin:0 0 8px; font-size:12px; text-align:right;">※ 본 화면의 금액 단위는 Point입니다.</div>
    <div class="table-responsive">
		<table class="div-table table bsk-tbl bg-white">
        <tbody>
		<?php if(!$cart_is_mixed_types) { ?>
		<tr class="<?php echo $head_class;?>">
			<th scope="col">
				<label for="ct_all" class="sound_only">상품 전체</label>
				<span><input type="checkbox" name="ct_all" value="1" id="ct_all" checked="checked"></span>
			</th>
			<th scope="col"><span><?php echo $cart_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 class="last">배송비</span></th> -->
		</tr>
		<?php } ?>

		<?php
		$cart_prev_group_type = '';
		for($i=0;$i < count($item); $i++) {
			$cart_row_is_vpn = apms_item_is_vpn_like($item[$i]);
			$cart_group_type = $cart_row_is_vpn ? 'vpn' : 'rpc';
			if($cart_is_mixed_types && $cart_prev_group_type !== $cart_group_type) {
				$cart_section_label = $cart_row_is_vpn ? 'VPN종류' : '운영체제';
				$cart_section_title = $cart_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 $cart_section_title; ?>
				</td>
			</tr>
			<tr class="<?php echo $head_class;?>">
				<th scope="col">
					<label for="ct_all_<?php echo $cart_group_type; ?>" class="sound_only">상품 전체</label>
					<span><input type="checkbox" name="ct_all" value="1" id="ct_all_<?php echo $cart_group_type; ?>" checked="checked"></span>
				</th>
				<th scope="col"><span><?php echo $cart_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>
			</tr>
		<?php
				$cart_prev_group_type = $cart_group_type;
			}
		?>
			<tr<?php echo ($i == 0) ? ' class="tr-line"' : '';?>>
				<td class="text-center">
					<label for="ct_chk_<?php echo $i; ?>" class="sound_only">상품</label>
					<input type="checkbox" name="ct_chk[<?php echo $i; ?>]" value="1" id="ct_chk_<?php echo $i; ?>" checked="checked" data-sell-price="<?php echo (int)$item[$i]['sell_price']; ?>">
				</td>
				<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 = 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]['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'];?>">
					[<?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 stripslashes($item[$i]['it_name']); ?></b>
					</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>
					*/
					?>

					<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

									// $extIP = $api_data['extIP'];
									// 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 = strtolower($dataArray_it_spec_remote_sw[0]['RemoteIP_CountryCode__0']);
									$remote_ip_country_name = $dataArray_it_spec_remote_sw[0]['RemoteIP_CountryName__0'];
									$remote_ip_city_name = $dataArray_it_spec_remote_sw[0]['RemoteIP_City__0'];
									$remote_ip_country_flag = "<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'>".$it_id."</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>
				<td class="text-center" style="line-height:3em;">
					<?php
						$cart_contract_hours = apms_contract_hours_from_day_hour((int)$item[$i]['ct_qty'], (int)$item[$i]['ct_qty_hour']);
						$cart_unit = apms_pricing_unit_from_day_hour((int)$item[$i]['ct_qty'], (int)$item[$i]['ct_qty_hour']);
						$cart_count = apms_pricing_count_from_day_hour((int)$item[$i]['ct_qty'], (int)$item[$i]['ct_qty_hour'], $cart_unit);
						echo apms_contract_hours_text($cart_contract_hours);
					?>
					<br>
					<button type="button" class="btn btn-primary btn-sm btn-block mod_options" style="padding:2px; font-size:1em;">수정</button>
				</td>
				<?php
					$cart_license_price = (int)$item[$i]['license_price'];
					$cart_unit_price = (int)$item[$i]['ct_price'];
					$cart_base_amount = $cart_unit_price * (int)$cart_contract_hours;
					$cart_extra_amount = $cart_license_price - $cart_base_amount;
				?>
				<td class="text-right">
					<?php echo number_format($cart_license_price); ?>
					<div class="voucher-info-wrap">
						<button type="button" class="voucher-info-btn" aria-label="이용권 금액 계산식 안내"
							data-license-price="<?php echo (int)$cart_license_price; ?>"
							data-unit-price="<?php echo (int)$cart_unit_price; ?>"
							data-contract-hours="<?php echo (int)$cart_contract_hours; ?>"
							data-extra-price="<?php echo (int)$cart_extra_amount; ?>">
							<i class="fa fa-info-circle" aria-hidden="true"></i>
						</button>
						<div class="voucher-info-tip" role="tooltip">
							<div><strong>이용권 금액 계산 안내</strong></div>
							<div class="formula" style="margin-top:8px;">계산식: (시간단가 × 총 이용시간) + 옵션/추가금액</div>
							<div class="formula">= (<?php echo number_format($cart_unit_price); ?> × <?php echo number_format((int)$cart_contract_hours); ?>) <?php echo ($cart_extra_amount >= 0 ? '+ ' : '- ').number_format(abs((int)$cart_extra_amount)); ?> = <?php echo number_format($cart_license_price); ?> Point</div>
							<div style="margin-top:8px; color:#666;">• 시간단가: 1시간 기준 금액</div>
							<div style="color:#666;">• 총 이용시간: 주문기간을 시간으로 환산한 값</div>
							<div style="color:#666;">• 옵션/추가금액: 선택옵션/사용량 과금 등 부가 금액 합계</div>
						</div>
					</div>
				</td>
				<?php
					$install_rule = function_exists('apms_install_rule_from_item') ? apms_install_rule_from_item($item[$i]) : array('free_start_hours' => 0);
					$install_free_start_hours = isset($install_rule['free_start_hours']) ? (int)$install_rule['free_start_hours'] : 0;
					$install_waive_msg = ($install_free_start_hours > 0)
						? ('이 상품은 '.apms_contract_hours_text($install_free_start_hours).' 이상 구매 시 면제됩니다.')
						: '이 상품은 현재 면제 기준이 설정되어 있지 않습니다.';
					$install_guide_title = '개통비/설치비 안내';
					$install_guide_line1 = '신규 주문 시 1회만 청구되는 초기 세팅 비용입니다.';
					$install_guide_line2 = '계약기간을 연장하는 경우에는 청구되지 않습니다.';
					if(isset($is_vpn_product) && $is_vpn_product) {
						$install_guide_title = 'VPN 설치비 안내';
						$install_guide_line1 = 'VPN 설치 작업비로서 신규 주문 시 1회만 청구됩니다.';
					} else {
						$install_guide_title = 'RPC 세팅비 안내';
						$install_guide_line1 = '원격제어컴퓨터(RPC) 초기 세팅 작업비로서 신규 주문 시 1회만 청구됩니다.';
					}
				?>
				<td class="text-right">
					<?php echo number_format($item[$i]['ct_install_price']); ?>
					<div class="install-info-wrap tip-wrap">
						<button type="button" class="install-info-btn" aria-label="개통비/설치비 안내">
							<i class="fa fa-info-circle" aria-hidden="true"></i>
						</button>
						<div class="install-info-tip" role="tooltip">
							<div><strong><?php echo $install_guide_title; ?></strong></div>
							<div style="margin-top:6px;"><?php echo $install_guide_line1; ?></div>
							<div><?php echo $install_guide_line2; ?></div>
							<div><?php echo $install_waive_msg; ?></div>
						</div>
					</div>
				</td>
				<td class="text-right"><span id="sell_price_<?php echo $i; ?>"><?php echo number_format($item[$i]['sell_price']); ?></span></td>
				<!-- <td class="text-right"><?php echo number_format($item[$i]['point']); ?>포인트</td> -->
				<!-- <td class="text-center"><?php echo $item[$i]['ct_send_cost']; ?>포인트</td> -->
			</tr>
		<?php } ?>
        <?php if ($i == 0) { ?>
            <tr><td colspan="8" class="text-center text-muted"><p style="padding:50px 0;">장바구니가 비어 있습니다.</p></td></tr>
		<?php } ?>
        </tbody>
        </table>
    </div>

    <?php if ($tot_price > 0 || $send_cost > 0) { ?>
		<div class="well bg-white">
			<div class="row">
				<?php if ($send_cost > 0) { // 배송비가 0 보다 크다면 (있다면) ?>
					<div class="col-xs-6">배송비</div>
					<div class="col-xs-6 text-right">
						<strong><?php echo number_format($send_cost); ?></strong>
					</div>
				<?php } ?>
				<?php if ($tot_price > 0) { ?>
					<div class="col-xs-6"> 주문합계</div>
					<div class="col-xs-6 text-right">
						<strong id="cart_selected_total"><?php echo number_format($tot_price); ?></strong>
					</div>
				<?php } ?>
			</div>
		</div>
	<?php } ?>

    <div style="margin-bottom:15px; text-align:center;">
        <?php if ($i == 0) { ?>
	        <a href="<?php echo G5_SHOP_URL; ?>/" class="btn btn-color btn-sm">계속하기</a>
        <?php } else { ?>
			<input type="hidden" name="url" value="./orderform.php">
			<input type="hidden" name="records" value="<?php echo $i; ?>">
			<input type="hidden" name="act" value="">
			<div class="row">
				<div class="col-sm-6 col-sm-offset-3">
					<div class="form-group">
						<button type="button" onclick="return form_check('buy');" class="btn btn-color btn-block btn-lg"><i class="fa fa-check-square fa-lg"></i> 주문하기</button>
					</div>
				</div>
			</div>
			<div class="row">
				<div class="col-sm-6 col-sm-offset-3">
					<div class="btn-group btn-group-justified">
						<div class="btn-group">
							<a href="<?php echo G5_SHOP_URL; ?>/list.php?ca_id=<?php echo $continue_ca_id; ?>" class="btn btn-black btn-block btn-sm"><i class="fa fa-cart-plus"></i> 계속하기</a>
						</div>
						<div class="btn-group">
							<button type="button" onclick="return form_check('seldelete');" class="btn btn-black btn-block btn-sm"><i class="fa fa-times"></i> 선택삭제</button>
						</div>
						<div class="btn-group">
							<button type="button" onclick="return form_check('alldelete');" class="btn btn-black btn-block btn-sm"><i class="fa fa-trash"></i> 비우기</button>
						</div>
					</div>
					<?php if ($naverpay_button_js) { ?>
						<div style="margin-top:20px;"><?php echo $naverpay_request_js.$naverpay_button_js; ?></div>
					<?php } ?>
				</div>
			</div>
		<?php } ?>
    </div>

</form>
<?php if($setup_href) { ?>
	<p class="text-center">
		<a class="btn btn-color btn-sm win_memo" href="<?php echo $setup_href;?>">
			<i class="fa fa-cogs"></i> 스킨설정
		</a>
	</p>
<?php } ?>

<script>
	$(function() {
		var close_btn_idx;

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

		function updateCheckedOrderTotal() {
			var sum = 0;
			$("input[name^=ct_chk]:checked").each(function() {
				var rowPrice = parseInt($(this).attr('data-sell-price'), 10);
				if (!isNaN(rowPrice)) sum += rowPrice;
			});

			var $total = $('#cart_selected_total');
			if ($total.length) {
				$total.text(numberFormat(sum));
			}
		}

		// 선택사항수정
		$(".mod_options").click(function() {
			var it_id = $(this).closest("tr").find("input[name^=it_id]").val();
			var $this = $(this);
			close_btn_idx = $(".mod_options").index($(this));
			$('#cartModal').modal('show');
			$.post(
				"./cartoption.php",
				{ it_id: it_id },
				function(data) {
					$("#mod_option_form").remove();
					//$this.after("<div id=\"mod_option_frm\"></div>");
					$("#mod_option_box").html(data);
					price_calculate();
				}
			);
		});

		// 모두선택
		$("input[name=ct_all]").click(function() {
			if($(this).is(":checked"))
				$("input[name^=ct_chk]").prop("checked", true);
			else
				$("input[name^=ct_chk]").prop("checked", false);

			updateCheckedOrderTotal();
		});

		$(document).on('change', "input[name^=ct_chk]", function() {
			var totalCount = $("input[name^=ct_chk]").length;
			var checkedCount = $("input[name^=ct_chk]:checked").length;
			$("input[name=ct_all]").prop("checked", totalCount > 0 && totalCount === checkedCount);
			updateCheckedOrderTotal();
		});

		// 옵션수정 닫기
	    $(document).on("click", "#mod_option_close", function() {
			$('#cartModal').modal('hide');
			//$("#mod_option_frm").remove();
			$("#mod_option_form").remove();
			$(".mod_options").eq(close_btn_idx).focus();
		});
		$("#win_mask").click(function () {
			$('#cartModal').modal('hide');
			//$("#mod_option_frm").remove();
			$("#mod_option_form").remove();
			$(".mod_options").eq(close_btn_idx).focus();
		});

		updateCheckedOrderTotal();

	});

	function fsubmit_check(f) {
		if($("input[name^=ct_chk]:checked").size() < 1) {
			alert("구매하실 상품을 하나이상 선택해 주십시오.");
			return false;
		}

		return true;
	}

	function form_check(act) {
		var f = document.frmcartlist;
		var cnt = f.records.value;

		if (act == "buy")
		{
			if($("input[name^=ct_chk]:checked").size() < 1) {
				alert("주문하실 상품을 하나이상 선택해 주십시오.");
				return false;
			}

			f.act.value = act;
			f.submit();
		}
		else if (act == "alldelete")
		{
			f.act.value = act;
			f.submit();
		}
		else if (act == "seldelete")
		{
			if($("input[name^=ct_chk]:checked").size() < 1) {
				alert("삭제하실 상품을 하나이상 선택해 주십시오.");
				return false;
			}

			f.act.value = act;
			f.submit();
		}

		return true;
	}

	(function($) {
		$('.voucher-info-wrap').addClass('tip-wrap');

		function positionInstallTip($wrap) {
			var $btn = $wrap.find('.install-info-btn');
			var $tip = $wrap.find('.install-info-tip');
			if (!$btn.length || !$tip.length) return;

			var rect = $btn[0].getBoundingClientRect();
			var vw = window.innerWidth || document.documentElement.clientWidth;
			var vh = window.innerHeight || document.documentElement.clientHeight;
			var gap = 10;
			var margin = 12;

			$tip.css({ left: 0, top: 0 });
			var tipW = $tip.outerWidth();
			var tipH = $tip.outerHeight();

			var anchorX = rect.left + (rect.width / 2);
			var left = anchorX - (tipW / 2);
			if (left < margin) left = margin;
			if (left + tipW > vw - margin) left = vw - tipW - margin;

			var placeTop = (rect.top >= (tipH + gap + margin));
			var top;
			if (placeTop) {
				top = rect.top - tipH - gap;
				$tip.attr('data-place', 'top');
			} else {
				top = rect.bottom + gap;
				$tip.attr('data-place', 'bottom');
			}

			if (top < margin) top = margin;
			if (top + tipH > vh - margin) top = vh - tipH - margin;

			$tip.css({ left: left + 'px', top: top + 'px' });

			var arrowLeft = anchorX - left;
			if (arrowLeft < 14) arrowLeft = 14;
			if (arrowLeft > tipW - 14) arrowLeft = tipW - 14;
			$tip[0].style.setProperty('--install-tip-arrow-left', arrowLeft + 'px');
		}

		function positionVoucherTip($wrap) {
			var $btn = $wrap.find('.voucher-info-btn');
			var $tip = $wrap.find('.voucher-info-tip');
			if (!$btn.length || !$tip.length) return;

			var rect = $btn[0].getBoundingClientRect();
			var vw = window.innerWidth || document.documentElement.clientWidth;
			var vh = window.innerHeight || document.documentElement.clientHeight;
			var gap = 10;
			var margin = 12;

			$tip.css({ left: 0, top: 0 });
			var tipW = $tip.outerWidth();
			var tipH = $tip.outerHeight();

			var anchorX = rect.left + (rect.width / 2);
			var left = anchorX - (tipW / 2);
			if (left < margin) left = margin;
			if (left + tipW > vw - margin) left = vw - tipW - margin;

			var placeTop = (rect.top >= (tipH + gap + margin));
			var top;
			if (placeTop) {
				top = rect.top - tipH - gap;
				$tip.attr('data-place', 'top');
			} else {
				top = rect.bottom + gap;
				$tip.attr('data-place', 'bottom');
			}

			if (top < margin) top = margin;
			if (top + tipH > vh - margin) top = vh - tipH - margin;

			$tip.css({ left: left + 'px', top: top + 'px' });

			var arrowLeft = anchorX - left;
			if (arrowLeft < 14) arrowLeft = 14;
			if (arrowLeft > tipW - 14) arrowLeft = tipW - 14;
			$tip[0].style.setProperty('--voucher-tip-arrow-left', arrowLeft + 'px');
		}

		$(document).on('mouseenter focusin', '.install-info-wrap', function() {
			var $wrap = $(this);
			positionInstallTip($wrap);
			$wrap.addClass('is-open');
		});

		$(document).on('mouseenter focusin', '.voucher-info-wrap', function() {
			var $wrap = $(this);
			positionVoucherTip($wrap);
			$wrap.addClass('is-open');
		});

		$(document).on('mouseleave focusout', '.install-info-wrap, .voucher-info-wrap', function() {
			$(this).removeClass('is-open');
		});

		$(window).on('resize scroll', function() {
			$('.install-info-wrap.is-open').each(function() {
				positionInstallTip($(this));
			});
			$('.voucher-info-wrap.is-open').each(function() {
				positionVoucherTip($(this));
			});
		});
	})(jQuery);
</script>
