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

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

?>
<style>
	#mod_option_form #it_sel_option .ct_total_hours_inline {display:flex;align-items:stretch;gap:8px;flex-wrap:nowrap;min-width:0;width:100%;}
	#mod_option_form #it_sel_option .ct_total_hours_inline .ct_pricing_unit {flex:1 1 54%;min-width:0;width:54%;height:44px;line-height:42px;}
	#mod_option_form #it_sel_option .ct_total_hours_inline .ct_pricing_count_wrap {flex:1 1 calc(46% - 8px);min-width:0;width:calc(46% - 8px);max-width:calc(46% - 8px);display:flex !important;align-items:stretch;}
	#mod_option_form #it_sel_option .ct_total_hours_inline .ct_pricing_count_field {position:relative;display:block;flex:1 1 auto;min-width:72px;width:100%;}
	#mod_option_form #it_sel_option .ct_total_hours_inline .ct_pricing_count {height:44px;line-height:42px;padding:0 34px 0 8px;min-width:4ch;text-align:right;font-variant-numeric:tabular-nums;-moz-appearance:textfield;}
	#mod_option_form #it_sel_option .ct_total_hours_inline .ct_pricing_count::-webkit-outer-spin-button,
	#mod_option_form #it_sel_option .ct_total_hours_inline .ct_pricing_count::-webkit-inner-spin-button { -webkit-appearance:none; margin:0; }
	#mod_option_form #it_sel_option .ct_total_hours_inline .ct_pricing_count_wrap .input-group-addon {display:inline-flex;align-items:center;justify-content:center;min-width:40px;height:44px;box-sizing:border-box;padding:0 7px;flex:0 0 40px;}
	#mod_option_form #it_sel_option .ct_count_stepper {position:absolute;top:1px;right:1px;bottom:1px;width:24px;display:flex;flex-direction:column;overflow:hidden;border-left:1px solid #d0d7e2;border-radius:0 3px 3px 0;background:#f8fafc;z-index:3;}
	#mod_option_form #it_sel_option .ct_count_stepper .ct_count_btn {flex:1 1 50%;min-width:0;height:auto;line-height:1;padding:0;border:0;border-radius:0;background:transparent;color:#111827;font-size:11px;font-weight:800;display:flex;align-items:center;justify-content:center;}
	#mod_option_form #it_sel_option .ct_count_stepper .ct_count_btn + .ct_count_btn {border-top:1px solid #d0d7e2;}
	#mod_option_form #it_sel_option .ct_count_stepper .ct_count_btn:hover,
	#mod_option_form #it_sel_option .ct_count_stepper .ct_count_btn:focus {background:#eef2f7;color:#111827;outline:0;}
	#mod_option_form #it_sel_option .ct_human_time_hint,
	#mod_option_form #it_sel_option .ct_auto_pricing_notice {display:block;width:100%;max-width:100%;margin-top:2px;}

	@media screen and (max-width: 600px) {
		#mod_option_form #it_sel_option .ct_total_hours_inline {gap:6px;}
		#mod_option_form #it_sel_option .ct_total_hours_inline .ct_pricing_unit {flex:0 0 52%;max-width:52%;height:42px;line-height:40px;font-size:15px;}
		#mod_option_form #it_sel_option .ct_total_hours_inline .ct_pricing_count_wrap {flex:0 0 calc(48% - 6px);max-width:calc(48% - 6px);}
		#mod_option_form #it_sel_option .ct_total_hours_inline .ct_pricing_count {height:42px;line-height:40px;font-size:16px;padding-right:32px;}
		#mod_option_form #it_sel_option .ct_total_hours_inline .ct_pricing_count_wrap .input-group-addon {height:42px;line-height:40px;}
	}

	/* ── 실시간 계산식 카드 ── */
	.cart-price-formula {
		margin: 12px 0 4px;
		padding: 11px 14px;
		background: #f4f6f9;
		border: 1px solid #d8e0ea;
		border-radius: 8px;
		font-size: 12.5px;
		line-height: 1.5;
	}
	.cart-price-formula .formula-row {
		display: flex;
		align-items: baseline;
		justify-content: space-between;
		gap: 8px;
		padding: 2px 0;
	}
	.cart-price-formula .formula-label {
		color: #6b7280;
		font-weight: 500;
		white-space: nowrap;
		flex-shrink: 0;
	}
	.cart-price-formula .formula-expr {
		color: #374151;
		font-variant-numeric: tabular-nums;
		font-weight: 600;
		text-align: right;
		flex: 1;
	}
	.cart-price-formula .formula-expr .formula-eq {
		color: #1d4ed8;
		font-weight: 700;
	}
	.cart-price-formula .formula-divider {
		border: 0;
		border-top: 1px dashed #c8d5e2;
		margin: 6px 0;
	}
	.cart-price-formula .formula-install .formula-expr {
		color: #6b7280;
	}
</style>
<div id="mod_option_form">
	<form name="foption" class="form" role="form" method="post" action="<?php echo $action_url; ?>" onsubmit="return formcheck(this);">
		<input type="hidden" name="act" value="optionmod">
		<input type="hidden" name="it_id[]" value="<?php echo $option['it_id']; ?>">
		<input type="hidden" name="it_msg1[]" value="<?php echo $it['pt_msg1']; ?>">
		<input type="hidden" name="it_msg2[]" value="<?php echo $it['pt_msg2']; ?>">
		<input type="hidden" name="it_msg3[]" value="<?php echo $it['pt_msg3']; ?>">
		<input type="hidden" id="it_price" value="<?php echo $option['ct_price']; ?>">
		<?php $base_hourly_price = apms_item_hourly_base_price($it); ?>
		<input type="hidden" id="it_price_base" value="<?php echo (int)$base_hourly_price; ?>">
		<?php
			$discount_hour = apms_pricing_unit_discount_for_item($it, 'hour');
			$discount_day = apms_pricing_unit_discount_for_item($it, 'day');
			$discount_month = apms_pricing_unit_discount_for_item($it, 'month');
			$discount_year = apms_pricing_unit_discount_for_item($it, 'year');
			$usage_deposit_price = apms_usage_deposit_price_from_item($it);
		?>

		<input type="hidden" name="default_install_price" id="default_install_price" value="<?php echo $it['it_install_price'];?>">
		<input type="hidden" name="io_install_price" id="io_install_price" value="<?php echo $option['ct_install_price'];?>">
		<input type="hidden" id="install_free_start_hours" value="<?php echo (int)$it['it_10']; ?>">
		<?php $install_rule_text = apms_install_rule_text($it); ?>

		<input type="hidden" name="ct_send_cost" value="<?php echo $option['ct_send_cost']; ?>">
		<input type="hidden" name="sw_direct">
		<input type="hidden" id="mb_point_balance" value="<?php echo (int)(isset($member['mb_point']) ? $member['mb_point'] : 0); ?>">
		<?php if($option_1) { ?>
			<p>&nbsp; <b><i class="fa fa-check-square-o fa-lg"></i> 선택옵션</b></p>
			<table class="opt-tbl">
			<tbody>
			<?php echo $option_1; // 선택옵션 ?>
			</tbody>
			</table>
		<?php } ?>

		<?php if($option_2) { ?>
			<p>&nbsp; <b><i class="fa fa-check-square-o fa-lg"></i> 추가옵션</b></p>
			<table class="opt-tbl">
			<tbody>
			<?php echo $option_2; // 추가옵션 ?>
			</tbody>
			</table>
		<?php } ?>

		<div id="it_sel_option">

			<div class="list-group-item" style="margin-bottom:20px; border:0; padding:0;">
				<div class="cart-opt-name-bar" style="display:flex;flex-direction:column;align-items:center;justify-content:center;padding:16px 14px 14px;text-align:center;background:#f0f4f8;gap:6px;border-radius:8px;border:1px solid #d1dae6;">
					<?php
						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('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>';
							}
						}
						$_badge_os    = isset($it['it_spec_os'])    ? $it['it_spec_os']    : '';
						$_badge_grade = isset($it['it_spec_grade']) ? $it['it_spec_grade'] : '';
						$_badge_html  = vpn_category_badge_html($_badge_os) . vpn_grade_badge_html($_badge_grade);
						if($_badge_html) {
							echo '<span style="display:inline-flex;align-items:center;line-height:1;">' . $_badge_html . '</span>';
						}
					?>
					<span class="it_opt_subj cart-opt-item-name" style="font-size:1.1rem;font-weight:800;color:#101828;letter-spacing:-0.2px;"><?php echo htmlspecialchars($io[0]['ct_option'], ENT_QUOTES); ?></span>
					<span class="it_opt_prc"><?php // echo $io[$i]['io_display_price']; ?></span>
				</div>
			</div>

			<div>
				<ul id="it_opt_added" class="list-group">
					<?php for($i=0; $i < count($io); $i++) { ?>
						<?php
							$allowed_units = apms_allowed_pricing_units_from_item($it);
							$min_contract_hours = apms_buy_qty_to_hours($it['it_buy_min_qty']);
							if($min_contract_hours <= 0) {
								$min_contract_hours = 1;
							}
							$max_contract_hours = apms_buy_qty_to_hours($it['it_buy_max_qty']);
							if($max_contract_hours <= 0) {
								$max_contract_hours = (365 * 24);
							}
							$default_day_qty = isset($io[$i]['ct_qty']) ? (int)$io[$i]['ct_qty'] : 0;
							$default_hour_qty = isset($io[$i]['ct_qty_hour']) ? (int)$io[$i]['ct_qty_hour'] : 0;
							$total_contract_hours = ($default_day_qty * 24) + $default_hour_qty;
							if($total_contract_hours < $min_contract_hours) {
								$total_contract_hours = $min_contract_hours;
							}
							if($total_contract_hours > $max_contract_hours) {
								$total_contract_hours = $max_contract_hours;
							}
							$default_unit = apms_pricing_unit_from_day_hour((int)floor($total_contract_hours / 24), (int)($total_contract_hours % 24));
							if(empty($allowed_units[$default_unit])) {
								$default_unit = apms_best_pricing_unit_for_hours($it, $total_contract_hours, 'hour');
							}
							$auto_best_unit = apms_best_pricing_unit_for_hours($it, $total_contract_hours, $default_unit);
							$default_count = apms_pricing_count_from_day_hour((int)floor($total_contract_hours / 24), (int)($total_contract_hours % 24), $default_unit);
							if($default_unit === 'usage') {
								$default_count = (int)$usage_deposit_price;
								if($default_count < 5000) $default_count = 5000;
								if($default_count > 1000000) $default_count = 1000000;
							}
							list($default_day_qty, $default_hour_qty) = apms_day_hour_from_pricing_unit($default_unit, $default_count);
						?>
						<li class="it_<?php echo $io[$i]['cls']; ?>_list list-group-item">
							<input type="hidden" name="io_type[<?php echo $it['it_id']; ?>][]" value="<?php echo $io[$i]['io_type']; ?>">
							<input type="hidden" name="io_id[<?php echo $it['it_id']; ?>][]" value="<?php echo $io[$i]['io_id']; ?>">
							<input type="hidden" name="io_value[<?php echo $it['it_id']; ?>][]" value="<?php echo $io[$i]['ct_option']; ?>">
							<input type="hidden" class="io_price" value="<?php echo $io[$i]['io_price']; ?>">
							<input type="hidden" class="io_stock" value="<?php echo $io[$i]['it_stock_qty']; ?>">

							<div class="row">
								<div class="col-sm-3">
									<label>
										<span>이용권 선택</span>
									</label>
								</div>
								<div class="col-sm-9">
									<div class="ct_total_hours_inline" style="display:flex; align-items:stretch; gap:8px; flex-wrap:nowrap; min-width:0; width:100%;">
										<select id="ct_pricing_unit_<?php echo $i; ?>" class="form-control input-sm ct_pricing_unit" style="flex:1 1 54%; min-width:0; width:54%; height:44px;"
											data-discount-hour="<?php echo $discount_hour; ?>"
											data-discount-day="<?php echo $discount_day; ?>"
											data-discount-month="<?php echo $discount_month; ?>"
											data-discount-year="<?php echo $discount_year; ?>"
											data-discount-usage="<?php echo apms_pricing_unit_discount_for_item($it, 'usage'); ?>"
											data-package-usage="<?php echo (int)$usage_deposit_price; ?>"
											data-allow-hour="<?php echo $allowed_units['hour'] ? '1' : '0'; ?>"
											data-allow-day="<?php echo $allowed_units['day'] ? '1' : '0'; ?>"
											data-allow-month="<?php echo $allowed_units['month'] ? '1' : '0'; ?>"
											data-allow-year="<?php echo $allowed_units['year'] ? '1' : '0'; ?>"
											data-auto-year="<?php echo (apms_pricing_unit_package_price_by_item($it, 'year') > 0) ? '1' : '0'; ?>"
											data-allow-usage="<?php echo $allowed_units['usage'] ? '1' : '0'; ?>">
											<?php if($allowed_units['usage']) { ?><option value="usage" <?php echo get_selected('usage', $default_unit); ?>>종량제 이용권</option><?php } ?>
											<?php if($allowed_units['hour']) { ?><option value="hour" <?php echo get_selected('hour', $default_unit); ?>>1시간 이용권</option><?php } ?>
											<?php if($allowed_units['day']) { ?><option value="day" <?php echo get_selected('day', $default_unit); ?>>1일 이용권</option><?php } ?>
											<?php if($allowed_units['month']) { ?><option value="month" <?php echo get_selected('month', $default_unit); ?>>1개월(30일) 이용권</option><?php } ?>
											<?php if($allowed_units['year']) { ?><option value="year" <?php echo get_selected('year', $default_unit); ?>>1년(365일) 이용권</option><?php } ?>
										</select>
										<div class="input-group ct_pricing_count_wrap" style="flex:1 1 calc(46% - 8px); min-width:0; width:calc(46% - 8px); max-width:calc(46% - 8px);">
											<div class="ct_pricing_count_field">
												<input type="number" name="ct_pricing_count[<?php echo $it['it_id']; ?>][]" min="1" step="1" value="<?php echo (int)$default_count; ?>" class="form-control input-sm ct_pricing_count" inputmode="numeric" pattern="[0-9]*" style="height:44px; width:100%;">
												<div class="ct_count_stepper" aria-label="수량 조절">
													<button type="button" class="btn btn-default btn-xs ct_count_btn ct_count_plus" aria-label="수량 증가">▲</button>
													<button type="button" class="btn btn-default btn-xs ct_count_btn ct_count_minus" aria-label="수량 감소">▼</button>
												</div>
											</div>
											<span class="input-group-addon ct_pricing_suffix">시간</span>
										</div>
										<input type="hidden" name="ct_pricing_unit[<?php echo $it['it_id']; ?>][]" value="<?php echo $auto_best_unit; ?>" class="ct_pricing_unit_hidden">
										<input type="hidden" name="ct_pricing_discount[<?php echo $it['it_id']; ?>][]" value="<?php echo apms_pricing_unit_discount_for_item($it, $auto_best_unit); ?>" class="ct_pricing_discount_hidden">
										<input type="hidden" name="ct_qty[<?php echo $it['it_id']; ?>][]" value="<?php echo $default_day_qty; ?>" id="ct_qty_<?php echo $i; ?>" class="ct_qty_hidden" min="<?php echo $min_contract_hours;?>" max="<?php echo $max_contract_hours;?>">
										<input type="hidden" name="ct_qty_hour[<?php echo $it['it_id']; ?>][]" value="<?php echo $default_hour_qty; ?>" id="ct_qty_hour_<?php echo $i; ?>" class="ct_qty_hour_hidden" min="0" max="23">
									</div>
									<div class="ct_human_time_hint" style="width:100%; font-size:12px; color:#666; margin-top:6px;"><?php echo ($default_unit === 'usage') ? ('유효기한: 주문일로부터 365일 / 충전필요금액: '.number_format(max(0, (int)$default_count - (int)(isset($member['mb_point']) ? $member['mb_point'] : 0))).' Point') : ('선택기간: '.apms_contract_hours_text($total_contract_hours)); ?></div>
									<div class="ct_auto_pricing_notice" style="width:100%; font-size:12px; color:#0b6e4f; margin-top:2px; display:none;"></div>
								</div>
							</div>

							<?php if($it['pt_msg1']) { ?>
								<div style="margin-top:10px;">
									<input type="text" name="pt_msg1[<?php echo $it['it_id']; ?>][]" class="form-control input-sm" placeholder="<?php echo $it['pt_msg1'];?>" value="<?php echo $io[$i]['pt_msg1'];?>">
								</div>
							<?php } ?>
							<?php if($it['pt_msg2']) { ?>
								<div style="margin-top:10px;">
									<input type="text" name="pt_msg2[<?php echo $it['it_id']; ?>][]" class="form-control input-sm" placeholder="<?php echo $it['pt_msg2'];?>" value="<?php echo $io[$i]['pt_msg2'];?>">
								</div>
							<?php } ?>
							<?php if($it['pt_msg3']) { ?>
								<div style="margin-top:10px;">
									<input type="text" name="pt_msg3[<?php echo $it['it_id']; ?>][]" class="form-control input-sm" placeholder="<?php echo $it['pt_msg3'];?>" value="<?php echo $io[$i]['pt_msg3'];?>">
								</div>
							<?php } ?>
						</li>
					<?php } ?>
				</ul>
			</div>
		</div>

		<div id="it_sel_option_hour" style="display:none;"></div>

		<div>
			<ul id="it_opt_added" class="list-group">
				<li class="it_<?php echo $io[$i]['cls']; ?>_list list-group-item">
					<div class="row">
						<div class="col-sm-4">
							<label>
								<span>개통비/설치비</span>
							</label>
						</div>
						<div class="col-sm-6">
							<span id="io_install_price_disp" data-rule-text="<?php echo htmlspecialchars($install_rule_text ? ' '.$install_rule_text : '', ENT_QUOTES); ?>"></span>
						</div>
					</div>
				</li>
			</ul>
		</div>

		<div id="cart-price-formula" class="cart-price-formula" style="display:none;" aria-live="polite"></div>

		<h4 style="text-align:center; margin-bottom:20px; margin-top:14px;">
			<div id="it_tot_price"></div>
		</h4>

		<p></p>

		<div class="text-center">
			<button type="submit" class="btn btn-color btn-sm">적용</button>
			<button type="button" id="mod_option_close" class="btn btn-black btn-sm">닫기</button>
		</div>
	</form>
</div>

<script>
	// BS3
	$(function() {
		$("select.it_option").addClass("form-control input-sm");
		$("select.it_supply").addClass("form-control input-sm");
		var basePriceVal = parseFloat($('#it_price_base').val());
		if (!isNaN(basePriceVal) && basePriceVal >= 0) {
			$('#it_price').val(String(basePriceVal));
		}

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

		function unitDiscount(unit, $li) {
			var $unitSelect = $li.find('.ct_pricing_unit');
			if (unit === 'day') return parseFloat($unitSelect.data('discount-day')) || 1;
			if (unit === 'month') return parseFloat($unitSelect.data('discount-month')) || 1;
			if (unit === 'year') return parseFloat($unitSelect.data('discount-year')) || 1;
			if (unit === 'usage') return parseFloat($unitSelect.data('discount-usage')) || 1;
			return parseFloat($unitSelect.data('discount-hour')) || 1;
		}

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

		function isAllowedUnit(unit, $li) {
			var $unitSelect = $li.find('.ct_pricing_unit');
			if (unit === 'day') return String($unitSelect.data('allow-day')) === '1';
			if (unit === 'month') return String($unitSelect.data('allow-month')) === '1';
			if (unit === 'year') return String($unitSelect.data('allow-year')) === '1' || String($unitSelect.data('auto-year')) === '1';
			if (unit === 'usage') return String($unitSelect.data('allow-usage')) === '1';
			return String($unitSelect.data('allow-hour')) === '1';
		}

		function bestAllowedUnit($li, totalHours, fallbackUnit) {
			var units = ['hour', 'day', 'month', 'year', 'usage'];
			var bestUnit = '';
			var bestTotal = null;

			for (var i = 0; i < units.length; i++) {
				var u = units[i];
				if (!isAllowedUnit(u, $li)) continue;
				var unitH = unitHours(u);
				var packagePrice = Math.round((parseFloat($('#it_price').val()) || 0) * unitDiscount(u, $li) * unitH);
				var lineTotal = Math.max(1, Math.ceil(totalHours / unitH)) * packagePrice;
				if (bestTotal === null || lineTotal < bestTotal) {
					bestTotal = lineTotal;
					bestUnit = u;
				}
			}

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

			return bestUnit;
		}

		function syncContractPeriod($li) {
			var $qtyHidden = $li.find("input.ct_qty_hidden");
			var minHoursRaw = parseFloat($qtyHidden.attr("min"));
			var maxHoursRaw = parseFloat($qtyHidden.attr("max"));
			if (isNaN(minHoursRaw) || minHoursRaw < 1) minHoursRaw = 1;
			if (isNaN(maxHoursRaw) || maxHoursRaw < minHoursRaw) maxHoursRaw = (365 * 24);
			var minHours = Math.max(1, Math.ceil(minHoursRaw));
			var maxHours = Math.max(minHours, Math.floor(maxHoursRaw));

			var $unitSelect = $li.find('.ct_pricing_unit');
			var unit = String($unitSelect.val() || 'hour');
			var hoursPerUnit = unitHours(unit);
			$li.find('.ct_pricing_suffix').text(unitSuffix(unit));

			var $countInput = $li.find('.ct_pricing_count');
			var $countWrap = $li.find('.ct_pricing_count_wrap');
			var count = parseInt($countInput.val(), 10);
			if (isNaN(count) || count < 1) count = 1;
			if (unit === 'usage') {
				if (count < 5000) count = 5000;
				if (count > 1000000) count = 1000000;
				$countInput.attr('min', '5000').attr('max', '1000000').attr('step', '1000').prop('disabled', false).val(String(count));
				$countWrap.show();
				$li.find('.ct_pricing_unit_hidden').val('usage');
				$li.find('.ct_pricing_discount_hidden').val(String(unitDiscount('usage', $li)));
				$li.find("input[name^='ct_qty']").val(0);
				$li.find("input[name^='ct_qty_hour']").val(1);
				var mbPoint = parseInt($('#mb_point_balance').val(), 10);
				if (isNaN(mbPoint) || mbPoint < 0) mbPoint = 0;
				var needAmount = Math.max(0, count - mbPoint);
				$li.find('.ct_human_time_hint').text('유효기한: 주문일로부터 365일 / 충전필요금액: ' + number_format(String(needAmount)) + ' Point');
				price_calculate();
				return;
			} else {
				$countInput.attr('min', '1').removeAttr('max').attr('step', '1');
				$countInput.prop('disabled', false);
				$countWrap.show();
			}

			var totalHours = count * hoursPerUnit;
			if (totalHours < minHours) totalHours = minHours;
			if (totalHours > maxHours) totalHours = maxHours;
			count = Math.max(1, Math.round(totalHours / hoursPerUnit));
			totalHours = count * hoursPerUnit;
			if (totalHours > maxHours) totalHours = maxHours;

			var day = Math.floor(totalHours / 24);
			var hour = totalHours % 24;

			$countInput.val(String(count));
			var autoUnit = (unit === 'usage') ? 'usage' : bestAllowedUnit($li, totalHours, unit);
			$li.find('.ct_pricing_unit_hidden').val(autoUnit);
			$li.find('.ct_pricing_discount_hidden').val(String(unitDiscount(autoUnit, $li)));

			$li.find("input[name^='ct_qty']").val(day);
			$li.find("input[name^='ct_qty_hour']").val(hour);

			var hintText = '선택기간: ' + contractHoursText(totalHours);
			var freeStartHours = parseInt($('#install_free_start_hours').val(), 10);
			if (!isNaN(freeStartHours) && freeStartHours > 0 && totalHours >= freeStartHours) {
				var waivedInstallPrice = parseFloat($("input[name^=default_install_price]").val());
				if (isNaN(waivedInstallPrice) || waivedInstallPrice < 0) waivedInstallPrice = 0;
				hintText += ' ※ 개통비/설치비 ' + number_format(String(Math.round(waivedInstallPrice))) + ' Point 면제';
			}
			$li.find('.ct_human_time_hint').text(hintText);

			price_calculate();
		}

		$(document).on('change', '.ct_pricing_unit', function() {
			syncContractPeriod($(this).closest("li"));
		});

		$(document).on('input', '.ct_pricing_count', function() {
			var value = String($(this).val() || '');
			if (value === '') {
				return;
			}
			syncContractPeriod($(this).closest("li"));
		});

		$(document).on('change blur', '.ct_pricing_count', function() {
			syncContractPeriod($(this).closest("li"));
		});

		$(document).on('click', '.ct_count_minus, .ct_count_plus', function() {
			var $btn = $(this);
			var $li = $btn.closest('li');
			var $input = $li.find('.ct_pricing_count');
			var step = parseInt($input.attr('step'), 10);
			if (isNaN(step) || step < 1) step = 1;

			var min = parseInt($input.attr('min'), 10);
			if (isNaN(min) || min < 1) min = 1;

			var max = parseInt($input.attr('max'), 10);
			if (isNaN(max)) max = null;

			var value = parseInt($input.val(), 10);
			if (isNaN(value)) value = min;

			if ($btn.hasClass('ct_count_minus')) {
				value = value - step;
				if (value < min) value = min;
			} else {
				value = value + step;
				if (max !== null && value > max) value = max;
			}

			$input.val(String(value));
			syncContractPeriod($li);
		});

		$(document).on('focus', '.ct_pricing_count', function() {
			this.select();
		});

		$("#it_sel_option li").each(function() {
			syncContractPeriod($(this));
		});
	});

	/* ── 실시간 계산식 표시 ── */
	function updateCartPriceFormula() {
		var $li = $('#it_sel_option li').first();
		if (!$li.length) return;

		var baseHourlyPrice = parseFloat($('#it_price').val()) || 0;
		var unit  = $li.find('.ct_pricing_unit').val() || 'hour';
		var count = parseInt($li.find('.ct_pricing_count').val(), 10) || 1;
		var discount = parseFloat($li.find('.ct_pricing_discount_hidden').val());
		if (isNaN(discount) || discount <= 0) discount = 1;

		var unitHoursMap = {hour: 1, day: 24, month: 720, year: 8760, usage: 1};
		var uh = unitHoursMap[unit] || 1;
		var unitPkg = Math.round(baseHourlyPrice * discount * uh);

		var installPrice = parseInt($("input[name^=io_install_price]").val(), 10) || 0;
		var totalText    = $('#it_tot_price').text().replace(/[^0-9]/g, '');
		var total        = parseInt(totalText, 10) || 0;
		var usagePrice   = Math.max(0, total - installPrice);

		var unitLabelMap  = {hour: '시간', day: '일', month: '개월', year: '년', usage: 'Point'};
		var ul = unitLabelMap[unit] || '시간';

		var html = '';

		if (unit === 'usage') {
			html += '<div class="formula-row">' +
				'<span class="formula-label">종량제 충전</span>' +
				'<span class="formula-expr">' + number_format(String(usagePrice)) + ' P</span>' +
				'</div>';
		} else if (usagePrice > 0 && unitPkg > 0 && count > 0) {
			html += '<div class="formula-row">' +
				'<span class="formula-label">이용요금</span>' +
				'<span class="formula-expr">' +
					number_format(String(unitPkg)) + ' P &times; ' +
					number_format(String(count)) + ' ' + ul +
					'&nbsp;<span class="formula-eq">= ' + number_format(String(usagePrice)) + ' P</span>' +
				'</span>' +
				'</div>';
		}

		if (installPrice > 0) {
			html += (html ? '<hr class="formula-divider">' : '') +
				'<div class="formula-row formula-install">' +
				'<span class="formula-label">개통비/설치비</span>' +
				'<span class="formula-expr">' + number_format(String(installPrice)) + ' P</span>' +
				'</div>';
		}

		var $box = $('#cart-price-formula');
		if (html) {
			$box.html(html).show();
		} else {
			$box.hide();
		}
	}

	// #it_tot_price 내용이 바뀔 때마다 계산식 갱신
	$(function() {
		var _totEl = document.getElementById('it_tot_price');
		if (_totEl && window.MutationObserver) {
			new MutationObserver(function() {
				updateCartPriceFormula();
			}).observe(_totEl, {childList: true, subtree: true, characterData: true});
		}
		// 초기 렌더 (price_calculate 가 먼저 실행된 후)
		setTimeout(updateCartPriceFormula, 80);
	});

	function formcheck(f) {
		var result = true;
		var sum_qty = 0;
		var min_qty = parseInt(<?php echo (int)apms_buy_qty_to_hours($it['it_buy_min_qty']); ?>, 10);
		var max_qty = parseInt(<?php echo (int)apms_buy_qty_to_hours($it['it_buy_max_qty']); ?>, 10);
		if (isNaN(min_qty) || min_qty < 1) min_qty = 1;

		$("#it_sel_option li").each(function() {
			var $li = $(this);
			var day = parseInt($li.find("input[name^='ct_qty']").val(), 10);
			var hour = parseInt($li.find("input[name^='ct_qty_hour']").val(), 10);
			if (isNaN(day) || day < 0) day = 0;
			if (isNaN(hour) || hour < 0) hour = 0;
			if (hour > 23) hour = 23;

			var totalHours = (day * 24) + hour;
			if (totalHours < 1) {
				alert("계약일수와 계약시간이 모두 0입니다.\n주문은 최소 1시간 이상이어야 합니다.");
				result = false;
				return false;
			}

			sum_qty += totalHours;
		});

		if(!result) {
			return false;
		}

		if(min_qty > 0 && sum_qty < min_qty) {
			alert("계약시간 총합은 "+number_format(String(min_qty))+"시간 이상으로 주문해 주십시오.");
			return false;
		}

		if(max_qty > 0 && sum_qty > max_qty) {
			alert("계약시간 총합은 "+number_format(String(max_qty))+"시간 이하로 주문해 주십시오.");
			return false;
		}

		return true;
	}
</script>
