<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="ui" uri="http://egovframework.gov/ctl/ui"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="ec" uri="/WEB-INF/tld/ecnet_tld.tld"%>

<style>
	/*.charg_cont .area_tab li{ width: calc((100% - 80px)/5);}*/
</style>
	
<!-- KG 모빌리언스 -->
<script src="https://mup.mobilians.co.kr/js/ext/ext_inc_comm.js"></script>
<script type="text/javascript" src="<c:url value='/js/MJUtill.js'/>"></script>
<script src="https://js.tosspayments.com/v1/payment-widget"></script>

<script>

	let paymentWidget;
	let paymentMethodWidget;

	$(document).ready(function(){

		// 서버에서 보낸 payErrorMsg가 있는지 확인
		var errorMsg = "${payErrorMsg}";

		if (errorMsg && errorMsg !== "") {
			// 사용자에게 익숙한 alert 띄우기
			alert("결제에 실패하였습니다.\n사유: " + errorMsg);
		}


		setPriceMake();
		// 다음 결제시 결제수단 SELECT (필요 시 유지)
		// getNextPayMethod();

		// 토스페이먼츠 위젯 초기화 세팅
		const clientKey = 'test_gck_KNbdOvk5rk15kdKpqQGo3n07xlzm';
		const customerKey = 'test_customer_1234'; // 테스트용 가상 고객 ID (실제 연동 시에는 로그인한 유저의 고유 ID를 넣으세요)
		paymentWidget = PaymentWidget(clientKey, customerKey);

		// 충전금액 세팅 및 렌더링
		setPriceMake();
		const initialAmount = parseInt($("#price").val(), 10);

		// 결제수단 및 약관 위젯 화면에 렌더링
		paymentMethodWidget = paymentWidget.renderPaymentMethods('#payment-method', { value: initialAmount });
		paymentWidget.renderAgreement('#agreement');
	});

	function setPriceMake() {
		var tempPrice = parseInt($('.list_seType1').val(), 10);
		var vatPrice = Math.round(parseInt(tempPrice, 10) * 0.1);
		var lastPrice = parseInt(tempPrice, 10) + parseInt(vatPrice, 10);

		$("#price").val(lastPrice);
		$('#supplyPriceStr').html(numberWithCommas(tempPrice));
		$('#vatPriceStr').html(numberWithCommas(vatPrice));
		$('#lastPriceStr').html(numberWithCommas(lastPrice));

		// [추가] 변경된 최종 결제 금액을 토스 위젯에 업데이트
		if (typeof paymentMethodWidget !== 'undefined') {
			paymentMethodWidget.updateAmount(lastPrice);
		}
	}

	// 후불제여부 체크
	function getMjUserAfterPayCheck() {
		var isAfterPay = false;

		$.ajax({
			type: "POST",
			url: "/web/main/selectUserAfterPayAjax.do",
			data: {},
			dataType:'json',
			async: false,
			success: function (data) {
				if (data.isSuccess) {
					if (data.isAfterPay == true) {
						isAfterPay = true;
					}
				}
			},
			error: function (e) {

			}
		});

		return isAfterPay;
	}

	function pgOpenerPopup(){
		// 후불제여부 체크 (기존 로직 유지)
		if (getMjUserAfterPayCheck() == true) {
			alert("후불제 고객은 해당 서비스를 이용할수 없습니다.");
			return false;
		}

		var lastPrice = parseInt($("#price").val(), 10);
		if(lastPrice < 5500){
			alert("최소 충전금액 5천원 이상 선택해주세요.");
			return false;
		}
		// const paymentMethodsWidget = paymentWidget.renderPaymentMethods();
		// const selectedPaymentMethod = paymentMethodsWidget.getSelectedPaymentMethod();
		// console.log('paymentMethodsWidget : ', paymentMethodsWidget);
		// console.log('selectedPaymentMethod : ', selectedPaymentMethod);

		// 토스페이먼츠 결제창 바로 호출
		paymentWidget.requestPayment({
			orderId: 'ORDER_' + new Date().getTime(), // 고유한 상점 주문번호 생성
			orderName: '문자온 충전 ' + lastPrice + '원',
			successUrl: window.location.origin + '/web/member/pay/tossSuccess.do', // 결제 성공 시 이동할 URL (백엔드 컨트롤러 생성 필요)
			// paymentType=NORMAL
			// &orderId=ORDER_1778047452906
			// &paymentKey=tmunj2026050615041659Zv9
			// &amount=55000
			failUrl: window.location.origin + '/web/member/pay/tossFail.do',       // 결제 실패 시 이동할 URL (백엔드 컨트롤러 생성 필요)
			customerEmail: $('#mberEmailAdres').val(), // 필요시 로그인한 사용자의 이메일 매핑
			customerName: $('#mberNm').val(),   // 필요시 로그인한 사용자의 이름 매핑
			customerMobilePhone: $('#moblphonNo').val()
		}).catch(function (error) {
			if (error.code === 'USER_CANCEL') {
				alert('결제를 취소하셨습니다.');
			} else {
				alert(error.message);
			}
		});
	}

	//충전금액 Change Event
	$(document).on('change', '#tempPrice', function() {
	// $(document).on('change', '.list_seType1', function() {
		// 충전금액 세팅
		setPriceMake();
	});


/* 윈도우팝업 열기 */
function infoPop(pageUrl){
	document.infoPopForm.pageType.value = pageUrl;
	document.infoPopForm.action = "/web/pop/infoPop.do";
	document.infoPopForm.method = "post"; 
	window.open("about:blank", 'infoPop', 'width=790, height=220, top=100, left=100, fullscreen=no, menubar=no, status=no, toolbar=no, titlebar=yes, location=no, scrollbars=1');
	document.infoPopForm.target = "infoPop";
	document.infoPopForm.submit();
}


/* 사용내역서 클릭 시 내역서 새창 팝업 오픈  */
function fnShowVaViewPrintPopup() { 
	//만들려는 팝업의 크기
	var popup_wid = '840';
	var popup_ht = '800';

	var popup_left = (window.screen.width / 2) - (popup_wid / 2);
	var popup_top =(window.screen.height / 2) - (popup_ht / 2);

	$("#pgForm").attr("target","payVaPrint");
	
	window.open('', 'payVaPrint', 'width='+ popup_wid +', height='+ popup_ht +', left=' + popup_left + ', top='+ popup_top +',scrollbars=1');
	$("#pgForm").attr({"action":"/web/member/pay/selectVaViewPrintPopupAjax.do", "method":"post"}).submit();
	
}

</script>

<!-- </head>
<body> -->


	<form id="payTypeForm" name="payTypeForm" method="post"> 
		<input type="hidden" name="payTypeCode" />
	</form>
	<form id="pgForm" name="pgForm" action="/web/member/pay/PayActionAjax.do" method="post"> 
	<input type="hidden" id="price" name="price" />
	<input type="hidden" id="payMethod" name="payMethod" />
	<input type="hidden" id="accMsg" name="accMsg" />
	<input type="hidden" id="sendCnt" name="sendCnt" value="<c:out value='${resultMsgInfo.sendCnt}'/>" />
	<input type="hidden" id="mberEmailAdres" value="<c:out value='${mberManageVO.mberEmailAdres}'/>" />
	<input type="hidden" id="moblphonNo" value="<c:out value='${mberManageVO.moblphonNo}'/>" />
	<input type="hidden" id="mberNm" value="<c:out value='${mberManageVO.mberNm}'/>" />
     <!-- content 영역 -->
        <div class="inner">
            <!-- send top -->
            <div class="send_top">
                <!-- tab button -->
                <ul class="tabType4">
                    <li class="tab"><button type="button" onclick="location.href='/web/pay/PayGuide.do'">요금안내/견적내기</button></li>
                    <li class="tab active"><button type="button">결제하기</button></li>
                    <li class="tab"><button type="button" onclick="location.href='/web/member/pay/PayList.do'">요금 결제내역</button></li>
                    <li class="tab"><button type="button" onclick="location.href='/web/member/pay/payUserSWList.do'">요금 사용내역</button></li>
					<!-- 현금영수증 자동발행 주석 -->
					<!-- <li class="tab"><button type="button" onclick="location.href='/web/member/pay/BillPub.do'">계산서/현금영수증 발행 등록</button></li> -->
					<li class="tab"><button type="button" onclick="location.href='/web/member/pay/BillPub.do'">세금계산서 발행 등록</button></li>
                </ul><!--// tab button -->
				<!-- 결제관리 - 결제하기 -->
                <div class="serv_content charg_cont current" id="tab5_2">
                    <div class="heading">
                        <h2>결제하기</h2>
                        <button type="button" class="button info" onclick="infoPop('PayView');">사용안내</button>
                    </div>
                    <%--<div class="titBox">
						<p>- 서비스 이용을 위해 충전이 필수 입니다.</p>
						<p>- 충전 자체로 매출 인식이 되지 않는 서비스 특성상, 부가세 신고는 전자 세금계산서로만 가능합니다.</p>
						<p>- 모든 요금은 VAT별도 금액입니다.</p>
					</div>--%>
					<div>
						<p class="tab_tit">충전수단 선택</p><%--
						<ul class="area_tab">
							<li class="btn_charge1 btn_tab active"><button type="button" onclick="TabTypePay(this,'1');"><i></i>신용카드</button></li>
							<li class="btn_charge2 btn_tab"><button type="button" onclick="TabTypePay(this,'2');" id="btnDdedicatedAccount"><i></i>전용계좌</button></li>
							<li class="btn_charge3 btn_tab"><button type="button" onclick="TabTypePay(this,'3');"><i></i>휴대폰결제</button></li>
							<li class="btn_charge4 btn_tab"><button type="button" onclick="TabTypePay(this,'4');"><i></i>즉시이체</button></li>
							
							<li class="btn_charge5 btn_tab simple_pay"><button type="button" onclick="TabTypePay(this,'5');"><i></i></button></li>
							<li class="btn_charge6 btn_tab simple_pay"><button type="button" onclick="TabTypePay(this,'6');"><i></i></button></li>
							<li class="btn_charge7 btn_tab simple_pay"><button type="button" onclick="TabTypePay(this,'7');"><i></i></button></li>
							<li class="btn_charge8 btn_tab simple_pay"><button type="button" onclick="TabTypePay(this,'8');"><i></i></button></li>							
						</ul>
						<div class="checkbox_wrap"><input type="checkbox" id="agree"><label for="agree">선택한 수단을 다음 충전 시에도 이용합니다.</label></div>
--%>
						<!-- 신용카드 -->
						<div class="area_tabcont on" id="tab2_1">
							<p class="tType1_title"><img src="/publish/images/content/icon_charging1_small.png" alt=""> 신용카드</p>
							<!-- 충전금액 선택 영역 -->
							<div class="charge_amount_box" style="margin-bottom: 20px;">
								<label for="tempPrice" style="font-weight: bold; margin-right: 10px;">충전금액 선택 :</label>
								<select name="tempPrice" id="tempPrice" class="list_seType1">
									<option value="5000">5,000</option>
									<option value="10000">10,000</option>
									<option value="50000" selected>50,000</option>
									<!-- 필요하신 금액대 옵션 유지 -->
								</select> 원
								<p style="margin-top: 10px; color: #666;">
									최종 결제금액: <strong id="lastPriceStr" style="color: #000; font-size: 16px;">55,000</strong>원 (공급가액 <span id="supplyPriceStr">50,000</span>원 + 부가세 <span id="vatPriceStr">5,000</span>원)
								</p>
							</div>

							<!-- 토스페이먼츠 결제수단 위젯 영역 -->
							<div id="payment-method"></div>

							<!-- 토스페이먼츠 이용약관 영역 -->
							<div id="agreement"></div>

							<!-- 결제하기 버튼 -->
							<div style="text-align: center; margin-top: 20px;">
								<button type="button" class="btnType" onclick="pgOpenerPopup(); return false;" style="width: 200px; height: 50px; font-size: 16px;">충전하기</button>
							</div>
						</div>
					</div>

					<!--누적결제액별 등급 및 단가 추가 시작-->
					<div class="accrue_price" id="grdShowArea" style="display: none;">
					</div>
					<div class="accrue_level" id="mberGrdSettingArea" style="display: none;">
						<p class="tType1_title level"><img src="/publish/images/level/accrue.png" alt="누적결제액별 등급 및 단가 아이콘"> 누적결제액별 등급 및 단가
						</p>
						<table class="tType2 tType2_level">
							<caption></caption>
							<colgroup>
								<col style="width: 13%;">
								<col style="width: auto;">
								<col style="width: 11%;">
								<col style="width: 11%;">
								<col style="width: 11%;">
								<col style="width: 11%;">
								<col style="width: 11%;">
							</colgroup>
							<thead>
								<tr>
									<th>등급</th>
									<th class="th_second">누적결제액<span id="levelSubTitle"></span></th>
									<th>단문</th>
									<th>장문</th>
									<th>그림(1장)</th>
									<th>그림(2장)</th>
									<th>그림(3장)</th>
								</tr>
							</thead>
							<tbody>
			    				<c:forEach var="result" items="${mberGrdSettingList}" varStatus="status">
								<tr>
									<th><c:out value="${result.grdSetNm}"/></th>
									<td class="level_price"><c:out value="${result.stdAmtComma}"/></td>
									<td><c:out value="${result.shortPrice}"/></td>
									<td><c:out value="${result.longPrice}"/></td>
									<td><c:out value="${result.picturePrice}"/></td>
									<td><c:out value="${result.picture2Price}"/></td>
									<td><c:out value="${result.picture3Price}"/></td>
								</tr>
								</c:forEach>																				
							</tbody>
						</table>
						<span class="reqTxt4">
							* 등급별 요금제는 당사의 정책 및 운영의 필요상 수정, 중단 또는 변경될 수 있습니다. <br>
							* 누적결제액은 등급별 요금제 적용일로부터 적립된 결제금액을 말하며, 누적결제액에 따라 등급은 자동으로 적용됩니다. <br>
							* "첫결제 이벤트" 등 이벤트 결제금액은 등급별 요금제 누적결제액에서 제외됩니다. <br>
						</span>
						<p class="reqTxt4 reqTxt4_last">
							* 문자피싱, 스미싱, 주식, 도박, 로또, 스팸, 사기, 협박, 범죄, 유사투자, 유사수신 등을 목적으로 하거나 교사 또는 방조하는 내용의 정보, 발신번호 조작
							등으로 인지되는 문자에 대해서는
							사전 또는 즉시 발송을 차단하고
							이용을 정지시킬 수 있으며, 이에 대한 어떠한 환불이나 보상을 실시하지 않습니다. 또한, 상기 문자를 발송한 회원에 대해서는 그 즉시 등급별 요금제 혜택을
							취소합니다.
						</p>
					</div>            
					<!--문자_등급별 요금 안내 추가 끝-->    


				</div><!-- 결제관리 - 결제하기 -->
            </div><!--// send top -->
        </div>
    </form>

<form name="infoPopForm" id="infoPopForm" method="post">
	<input type="hidden" name="pageType" id="pageType" value=""/> 
</form>


<!-- KG 모빌리언스 CARD -->
<form name="payCardForm" accept-charset="euc-kr">
<input type="hidden" name="CASH_GB">
<input type="hidden" name="CN_SVCID">
<input type="hidden" name="PAY_MODE">
<input type="hidden" name="VER">
<input type="hidden" name="Prdtprice">
<input type="hidden" name="Prdtnm">
<input type="hidden" name="Tradeid">
<input type="hidden" name="Siteurl">
<input type="hidden" name="Okurl">
<input type="hidden" name="Notiurl">
<input type="hidden" name="CALL_TYPE">
<input type="hidden" name="Failurl">
<input type="hidden" name="Userid">
<input type="hidden" name="Username">
<input type="hidden" name="MSTR">
<input type="hidden" name="Payeremail">
<input type="hidden" name="Cryptyn">
<input type="hidden" name="Cryptstring">
<input type="hidden" name="Closeurl">
<input type="hidden" name="CN_BILLTYPE">
<input type="hidden" name="CN_TAX">
<input type="hidden" name="CN_TAXFREE">
<input type="hidden" name="CN_FREEINTEREST">
<input type="hidden" name="CN_POINT">
<input type="hidden" name="Termregno">
<input type="hidden" name="APP_SCHEME">
<input type="hidden" name="CN_FIXCARDCD">
<input type="hidden" name="CN_DIRECT">
<input type="hidden" name="CN_INSTALL">
<input type="hidden" name="Deposit">
</form>

<!-- KG 모빌리언스 MOBILE -->
<form name="payMobileForm" accept-charset="euc-kr">
<input type="hidden" name="CASH_GB">
<input type="hidden" name="Okurl">
<input type="hidden" name="MC_SVCID">
<input type="hidden" name="Prdtnm">
<input type="hidden" name="Prdtprice">
<input type="hidden" name="Siteurl">
<input type="hidden" name="PAY_MODE">
<input type="hidden" name="Tradeid">
<input type="hidden" name="LOGO_YN">
<input type="hidden" name="CALL_TYPE">
<input type="hidden" name="MC_AUTHPAY">
<input type="hidden" name="Notiurl">
<input type="hidden" name="MC_AUTOPAY">
<input type="hidden" name="Closeurl">
<input type="hidden" name="MC_PARTPAY">
<input type="hidden" name="Failurl">
<input type="hidden" name="MC_No">
<input type="hidden" name="MC_FIXNO">
<input type="hidden" name="MC_Cpcode">
<input type="hidden" name="Userid">
<input type="hidden" name="Item">
<input type="hidden" name="Prdtcd">
<input type="hidden" name="Payeremail">
<input type="hidden" name="MC_DEFAULTCOMMID">
<input type="hidden" name="MC_FIXCOMMID">
<input type="hidden" name="MSTR">
<input type="hidden" name="Sellernm">
<input type="hidden" name="Sellertel">
<input type="hidden" name="Notiemail">
<input type="hidden" name="IFRAME_NAME">
<input type="hidden" name="INFOAREA_YN">
<input type="hidden" name="FOOTER_YN">
<input type="hidden" name="HEIGHT">
<input type="hidden" name="PRDT_HIDDEN">
<input type="hidden" name="EMAIL_HIDDEN">
<input type="hidden" name="CONTRACT_HIDDEN">
<input type="hidden" name="Cryptyn">
<input type="hidden" name="Cryptstring">
<input type="hidden" name="MC_EZ_YN">
<input type="hidden" name="MC_EZ_KEY">
<input type="hidden" name="MC_PUSH_KEY">
</form>

<!-- KG 모빌리언스 BANK -->
<form name="payBankForm" accept-charset="euc-kr">
<input type="hidden" name="CASH_GB">
<input type="hidden" name="Okurl">
<input type="hidden" name="RA_SVCID">
<input type="hidden" name="Prdtnm">
<input type="hidden" name="Prdtprice">
<input type="hidden" name="Siteurl">
<input type="hidden" name="PAY_MODE">
<input type="hidden" name="Tradeid">
<input type="hidden" name="LOGO_YN">
<input type="hidden" name="CALL_TYPE">
<input type="hidden" name="Notiurl">
<input type="hidden" name="Closeurl">
<input type="hidden" name="Failurl">
<input type="hidden" name="Userid">
<input type="hidden" name="Item">
<input type="hidden" name="Prdtcd">
<input type="hidden" name="Payeremail">
<input type="hidden" name="MSTR">
<input type="hidden" name="Notiemail">
<input type="hidden" name="IFRAME_NAME">
<input type="hidden" name="INFOAREA_YN">
<input type="hidden" name="FOOTER_YN">
<input type="hidden" name="HEIGHT">
<input type="hidden" name="PRDT_HIDDEN">
<input type="hidden" name="EMAIL_HIDDEN">
<input type="hidden" name="CONTRACT_HIDDEN">
<input type="hidden" name="Cryptyn">
<input type="hidden" name="Cryptstring">
<input type="hidden" name="Deposit">
<input type="hidden" name="Billyn">
</form>
