<%@ page contentType="text/html; charset=UTF-8"%><%@ include file="/WEB-INF/jspf/include/taglibs.jsp"%>

<script type="text/javascript">
<!--
function checkAutopayment( form )
{
	var mode = form.mode.value;
	var title = "Ошибка"; 
	var okTitle = "Подтверждение";
	var message;
	var okMessage = window.okMessage == undefined ? "Для активации Автоплатежа необходимо совершить платеж.<br><br>Выберите способ оплаты" : window.okMessage;
	var buttons = "close";
	var okButtons = "yesCancel";

	if ( mode == '0' )
	{
		title = okTitle;
		message = "Отключение Автоплатежа приведет к отзыву разрешения на списание средств в платежной системе.<br><br>Отменить?";
		buttons = okButtons;
	}
	
	<c:if test="${dataMap['autopayment.mode.week.enable']}">
	if ( mode == '1' )
	{
		message = checkSum( form.weekSum.value, ${dataMap['autopayment.mode.week.sum.min']}, ${dataMap['autopayment.mode.week.sum.max']} );
	}
	</c:if>
	
	<c:if test="${dataMap['autopayment.mode.month.enable']}">
	if ( mode == '2' )
	{
		var day = parseInt(form.dayOfMonth.value);
		if ( isNaN(day) || day < 1 || day > 31 )
		{
			message = "День месяца должен быть в диапазоне от 1 до 31";
		}
		else
		{
			message = checkSum( form.monthSum.value, ${dataMap['autopayment.mode.month.sum.min']}, ${dataMap['autopayment.mode.month.sum.max']} ); 
		}
	}
	</c:if>
	
	<c:if test="${dataMap['autopayment.mode.auto.enable']}">
	if ( mode == '3' )
	{
		message = checkSum( form.maxDaySum.value, 0, ${dataMap['autopayment.mode.auto.day.sum.max']} );
		if ( message == undefined )
		{
			message = checkSum( form.maxWeekSum.value, 0, ${dataMap['autopayment.mode.auto.week.sum.max']} );
			if ( message == undefined )
			{
				message = checkSum( form.maxMonthSum.value, 0, ${dataMap['autopayment.mode.auto.month.sum.max']} );
				if ( message != undefined )
				{
					message = message + ": \"Максимальная сумма в месяц\"";
				}
			}
			else
			{
				message = message + ": \"Максимальная сумма в неделю\"";
			}
		}
		else
		{
			message = message + ": \"Максимальная сумма в день\"";
		}
	}
	</c:if>

	if ( message == undefined )
	{
		title = okTitle;
		message = okMessage;
		buttons = "paymentMethods";
	}

	var autopaymentDialog = jQuery("#autopaymentDialog");
	jQuery("h1.modal-title", autopaymentDialog ).html( title );
	jQuery("div.modal-body", autopaymentDialog ).html( message );
	autopaymentDialog.modal("show");

	var footer = jQuery("div.modal-footer", autopaymentDialog ).empty(); 
	//var dialog = jQuery("#autopaymentDialog").dialog({ autoOpen: false, closeOnEscape: true, dialogClass: "autopaymentDialog", draggable: false, height: "auto", width: 500, modal: true, resizable: false });
	if ( buttons == "close" )
	{
		footer.append( '<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>' );
	}
	else if ( buttons == "yesCancel" )
	{
		footer.append( '<button type="button" class="btn btn-primary" data-bs-dismiss="modal" onclick="doAutopayment(); return false;">Да</button>' );
		footer.append( '<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>' );
	}
	else
	{
		<c:forEach var="paymentMethod" items="${paymentMethods}">
		<c:choose>
			<c:when test="${paymentMethod eq 'SBP'}">
			footer.append( '<div class="paymentMethod d-flex justify-content-center align-items-center" onclick="document.forms[\'autopayment\'].sbp.value = \'true\'; doAutopayment(); return false;"><img src="${pageContext.request.contextPath}/img/default/payment_sbp.png" title="СБП - система быстрых платежей" style="height: 3rem;"></div>' );
			</c:when>
			<c:when test="${paymentMethod eq 'CARD'}">
			footer.append( '<div class="paymentMethod d-flex justify-content-center align-items-center" onclick="doAutopayment(); return false;"><img src="${pageContext.request.contextPath}/img/default/payment_mir.png" title="Оплата банковской картой" style="height: 3rem;"></div>' );
			</c:when>
		</c:choose>
		</c:forEach>
//		<button type="button" class="btn btn-primary" data-bs-dismiss="modal" ">Да</button>			
//		<div class="" onclick="let form = document.getElementById('paymentForm'); form.sbp.value = 'true'; if ( ${customerAddressRequiredFunction} checkPaymentSum( { sum: form.sum.value, sumMin: ${sumMin}, sumMax: ${sumMax}, currency: '${currencyTitleMedium}', phoneNeed: false } ) ) { if ( doPay( form ) ) form.submit(); } return false;"></div>
//		<div class="paymentMethod d-flex justify-content-center align-items-center" onclick="let form = document.getElementById('paymentForm'); let hasPaymentPhoneField=document.getElementById('paymentPhoneField').style.display != 'none'; form.sbp.value = 'false'; if ( ${customerAddressRequiredFunction} checkPaymentSum( { sum: form.sum.value, sumMin: ${sumMin}, sumMax: ${sumMax}, currency: '${currencyTitleMedium}', phoneNeed: hasPaymentPhoneField, phone: form['payment.phone'] ? form['payment.phone'].value : '+70000000000' } ) ) { if ( doPay( form ) ) form.submit(); } return false;"></div>
		
	}
	return false;
}
//-->
</script>

<c:if test="${dataMap['autopayment.enable']}">
	<c:set var="displayNone"><c:if test="${tab ne 'autopayment'}"> display: none;</c:if></c:set>
    <div class="tile tab ${requestScope.paymentName} autopayment textColor4 borderRadius border4" style="padding: 10px 20px; background-color: #fff; margin-top: 0;${displayNone}">
	<form action="" method="POST" class="autopayment" name="autopayment">
		<input type="hidden" name="action" value="${action}">
		<input type="hidden" name="module" value="${module}">
		<input type="hidden" name="mid" value="${moduleId}">
		<input type="hidden" name="operation" value="autopayment" />
		<input type="hidden" name="sbp" value="false" />

		<div class="text1 textIndent" style="margin-top: 20px;">Подключение услуги автоплатежа позволяет периодически пополнять баланс по заданным ниже параметрам. После подключения автоплатежа его можно в любой момент отключить или изменить параметры.</div>

		<script>
			function bgSelectAutopaymentMode( value )
			{
				jQuery('div.autopaymentParam').hide(); 
				jQuery('div.autopaymentParam.mode_'+value).show();
				if ( value != 0 )
				{
					jQuery('div.customerAddress, div.customerEmail').show();
				};
				return false;				
			}
		</script>
		
		<div class="">
			<div class="subTitle mx-3 mb-1 mt-3 fs-4">Режим:</div>
			<div class="btn-group" role="group" aria-label="">
	
				<c:set var="checked"><c:if test="${dataMap['autopayment.mode'] == 0}">checked</c:if></c:set>
				<input type="radio" class="btn-check" name="mode" value="0" id="btnradio1" autocomplete="off" ${checked} onchange="return bgSelectAutopaymentMode( 0 );">
				<label class="btn btn-outline-primary" for="btnradio1">выключен</label>
	
				<c:if test="${dataMap['autopayment.mode.week.enable']}">
				<c:set var="checked"><c:if test="${dataMap['autopayment.mode'] == 1}">checked</c:if></c:set>
				<input type="radio" class="btn-check" name="mode" value="1" id="btnradio2" autocomplete="off" ${checked} onchange="return bgSelectAutopaymentMode( 1 );">
				<label class="btn btn-outline-primary" for="btnradio2">еженедельный</label>
				</c:if>
	
				<c:if test="${dataMap['autopayment.mode.month.enable']}">
				<c:set var="checked"><c:if test="${dataMap['autopayment.mode'] == 2}">checked</c:if></c:set>
				<input type="radio" class="btn-check" name="mode" value="2" id="btnradio3" autocomplete="off" ${checked} onchange="return bgSelectAutopaymentMode( 2 );">
				<label class="btn btn-outline-primary" for="btnradio3">ежемесячный</label>
				</c:if>

				<c:if test="${dataMap['autopayment.mode.auto.enable']}">
				<c:set var="checked"><c:if test="${dataMap['autopayment.mode'] == 3}">checked</c:if></c:set>
				<input type="radio" class="btn-check" name="mode" value="3" id="btnradio4" autocomplete="off" ${checked} onchange="return bgSelectAutopaymentMode( 3 );">
				<label class="btn btn-outline-primary" for="btnradio4">автоматический</label>
				</c:if>
			</div>
		</div>
		
		<div class="">
		<c:set var="hide"><c:if test="${dataMap['autopayment.mode'] == 0}">hide</c:if></c:set>
		<div class="autopaymentParam mode_1 mode_2 mode_3 subTitle ${hide} mx-3 mb-1 mt-3 fs-4">Параметры режима:</div>	

		<c:if test="${dataMap['autopayment.mode.week.enable']}">
		<c:set var="hide"><c:if test="${dataMap['autopayment.mode'] != 1}">hide</c:if></c:set>
		<c:set var="weekSum"><fmt:formatNumber groupingUsed="false" maxFractionDigits="2" minFractionDigits="2" value="${dataMap['autopayment.mode.week.sum']}" /></c:set>
		<div class="autopaymentParam mode_1 ${hide}">
			<div class="fs-5">Выберите день недели и сумму</div>
			<div class="alert alert-primary mt-2">
				 Введите сумму в диапазоне от <fmt:formatNumber groupingUsed="true" maxFractionDigits="2" minFractionDigits="2" value="${dataMap['autopayment.mode.week.sum.min']}" /> до <fmt:formatNumber groupingUsed="true" maxFractionDigits="2" minFractionDigits="2" value="${dataMap['autopayment.mode.week.sum.max']}"/> ${currencyTitleMedium}
			</div>
			<div class="hstack gap-3">
				<div class="form-floating mt-2">
					<select name="dayOfWeek" id="dayOfWeek" class="form-control"><c:forTokens var="option" items="2:Понедельник;3:Вторник;4:Среда;5:Четверг;6:Пятница;7:Суббота;1:Воскресенье" delims=";"><c:set var="selected"><c:if test="${dataMap['autopayment.mode.week.day'] eq fn:substring(option, 0, 1)}"> selected="selected"</c:if></c:set><option value="${fn:substring(option, 0, 1)}"${selected}>${fn:substring(option, 2, -1)}</option></c:forTokens></select>
					<label for="dayOfWeek">День недели:</label> 
				</div>
				<div class="form-floating mt-2">
					<input type="text" name="weekSum" size="10" maxlength="10" value="${weekSum}" id="weekSum" class="autopaymentSum form-control text-center">
					<label for="weekSum">Сумма:</label>
				</div>
			</div>
		</div>
		</c:if>

		<c:if test="${dataMap['autopayment.mode.month.enable']}">
		<c:set var="hide"><c:if test="${dataMap['autopayment.mode'] != 2}">hide</c:if></c:set>
		<c:set var="monthSum"><fmt:formatNumber groupingUsed="false" maxFractionDigits="2" minFractionDigits="2" value="${dataMap['autopayment.mode.month.sum']}" /></c:set>
		<div class="autopaymentParam mode_2 ${hide}">
			<div class="fs-5">Выберите день месяца и сумму</div>
			<div class="alert alert-primary mt-2">Если в текущем месяце нет указаного дня, платеж будет произведен в последний день месяца.<br/>
				 Введите сумму в диапазоне от <fmt:formatNumber groupingUsed="true" maxFractionDigits="2" minFractionDigits="2" value="${dataMap['autopayment.mode.month.sum.min']}" /> до <fmt:formatNumber groupingUsed="true" maxFractionDigits="2" minFractionDigits="2" value="${dataMap['autopayment.mode.month.sum.max']}"/> ${currencyTitleMedium}
			</div>
			<div class="hstack gap-3">
				<div class="form-floating mt-2"> 
					<input type="text" name="dayOfMonth" maxlength="2" value="${dataMap['autopayment.mode.month.day']}" size="15" id="dayOfMonth" class="autopaymentMonthDay form-control text-center">
					<label for="dayOfMonth">День месяца (от 1 до 31):</label>
				</div>
				<div class="form-floating mt-2">
					<input type="text" name="monthSum" value="${monthSum}" size="10" id="monthSum" class="autopaymentSum form-control text-center">
					<label for="monthSum">Сумма:</label>
				</div>
			</div>
		</div>
		</c:if>
		
		<c:if test="${dataMap['autopayment.mode.auto.enable']}">
		<c:set var="hide"><c:if test="${dataMap['autopayment.mode'] != 3}">hide</c:if></c:set>
		<c:set var="autoDaySum"><fmt:formatNumber groupingUsed="false" maxFractionDigits="2" minFractionDigits="2" value="${dataMap['autopayment.mode.auto.day.sum']}" /></c:set>
		<c:set var="autoWeekSum"><fmt:formatNumber groupingUsed="false" maxFractionDigits="2" minFractionDigits="2" value="${dataMap['autopayment.mode.auto.week.sum']}" /></c:set>
		<c:set var="autoMonthSum"><fmt:formatNumber groupingUsed="false" maxFractionDigits="2" minFractionDigits="2" value="${dataMap['autopayment.mode.auto.month.sum']}" /></c:set>
		<c:set var="helpAutoDaySum">Введите сумму в диапазоне от <fmt:formatNumber groupingUsed="true" maxFractionDigits="2" minFractionDigits="2" value="0" /> до <fmt:formatNumber groupingUsed="true" maxFractionDigits="2" minFractionDigits="2" value="${dataMap['autopayment.mode.auto.day.sum.max']}"/> ${currencyTitleMedium}</c:set>
		<c:set var="helpAutoWeekSum">Введите сумму в диапазоне от <fmt:formatNumber groupingUsed="true" maxFractionDigits="2" minFractionDigits="2" value="0" /> до <fmt:formatNumber groupingUsed="true" maxFractionDigits="2" minFractionDigits="2" value="${dataMap['autopayment.mode.auto.week.sum.max']}"/> ${currencyTitleMedium}</c:set>
		<c:set var="helpAutoMonthSum">Введите сумму в диапазоне от <fmt:formatNumber groupingUsed="true" maxFractionDigits="2" minFractionDigits="2" value="0" /> до <fmt:formatNumber groupingUsed="true" maxFractionDigits="2" minFractionDigits="2" value="${dataMap['autopayment.mode.auto.month.sum.max']}"/> ${currencyTitleMedium}</c:set>
		<div class="autopaymentParam mode_3 ${hide}">
			<div class="fs-5">Сумма и частота списания определяется провайдером</div>
			<div class="card mt-3">
  				<div class="card-header">Максимальная сумма</div>
				<div class="card-body">
					<div class="hstack gap-3">
					<div class="form-floating">
						<input type="text" name="maxDaySum" size="8" maxlength="10" value="${autoDaySum}" onfocus="showHelpMessage('${helpAutoDaySum}');" onblur="hideHelpMessage();" id="maxDaySum" class="autopaymentSum form-control text-center">
						<label for="maxDaySum" class="form-label">в день:</label>
					</div>
					<div class="form-floating">
					 	<input type="text" name="maxWeekSum" size="8" maxlength="10" value="${autoWeekSum}" onfocus="showHelpMessage('${helpAutoWeekSum}');" onblur="hideHelpMessage();" id="maxWeekSum" class="autopaymentSum form-control text-center">
						<label for="maxWeekSum" class="form-label">в неделю:</label>
					</div>
					<div class="form-floating"> 
					 	<input type="text" name="maxMonthSum" size="8" maxlength="10" value="${autoMonthSum}" onfocus="showHelpMessage('${helpAutoMonthSum}');" onblur="hideHelpMessage();" id="maxMonthSum" class="autopaymentSum form-control text-center">
						<label for="maxMonthSum" class="form-label">в месяц:</label>
					</div>
					</div>
				</div>
			</div>
		</div>
		</c:if>
		</div>
		
		<c:if test="${not empty dataMap['customerAddressEnable'] and dataMap['customerAddressEnable']}">
			<c:if test="${not empty dataMap['customerAddressRequired'] and dataMap['customerAddressRequired']}"><c:set var="customerAddressRequiredFunction">checkCustomerAddress( this.form.customerAddress.value, '${dataMap['customerAddressTitle']}' ) &&</c:set></c:if>
			<c:set var="hide"><c:if test="${dataMap['autopayment.mode'] == 0}">hide</c:if></c:set>
			<div class="form-floating autopaymentParam customerAddress ${hide} mt-3">
				<input type="text" name="customerAddress" maxlength="50" value="${dataMap['customerAddress']}" id="customerAddress" class="form-control text-center"/>
				<label for="customerAddress" class="form-label">${dataMap['customerAddressTitle']}:</label>
			</div>
		</c:if>
		<c:if test="${not empty dataMap['customerEmailEnable'] and dataMap['customerEmailEnable']}">
			<c:set var="hide"><c:if test="${dataMap['autopayment.mode'] == 0}">hide</c:if></c:set>
			<div style="margin-top: 10px; text-align: right;" class="autopaymentParam customerEmail ${hide}">E-mail для оповещения о статусе транзакции: <input type="text" name="customerEmail" size="15" maxlength="50" value="${dataMap['customerEmail']}" class=" form-control"/></div>
		</c:if>
		<div class="formButtons"><button type="button" class="btn btn-primary" onclick="checkAutopayment(form)">Применить изменения</button></div>
	</form>
	</div>
	<div id="autopaymentDialog" class="modal fade" tabindex="-1" style="display: none;">
		<div class="modal-dialog modal-dialog-centered">
		    <div class="modal-content">
				<div class="modal-header">
        			<h1 class="modal-title fs-4"></h1>
        			<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
      			</div>
      			<div class="modal-body fs-5"></div>
      			<div class="modal-footer"></div>
			</div>
		</div>
	</div>
</c:if>