<?php
	session_start();
	// send to step 1 if user does not meet requirements
    if ( $_SESSION['gift-card']['rezgoAction'] != 'firstStepGiftCard' || !isset($_COOKIE['rezgo_gift_card_'.REZGO_CID]) ){
        $site->sendTo($site->base.'/gift-card');
    } else {
        // save form in session
		$gc_details_array = [];
        foreach ($_SESSION['gift-card'] as $k => $v){
			$gc_details_array[$k] = $v;
			$this->setCookie('rezgo_gc_details_'.REZGO_CID, json_encode($gc_details_array));
        }
    }

    $company = $site->getCompanyDetails();
	$gateway_id = (string)$company->gateway_id;
	$currency_base = (string)$company->currency_base;
	$using_tmt = $gateway_id == 'tmt';
    $companyCountry = $company->country;
    $site->readItem($company);
    $card_fa_logos = array(
        'visa' => 'fa-cc-visa',
        'mastercard' => 'fa-cc-mastercard',
        'american express' => 'fa-cc-amex',
        'discover' => 'fa-cc-discover'
    );

	$billing_address = (int)$company->billing_address;
	$billing_country_required = in_array($gateway_id, ['tmt','square']);

    $r = REZGO_WORDPRESS ? $_SESSION['gift-card'] : $_POST;
    $complete_booking_total = ($r['billing_amount'] == 'custom' ) ? $r['custom_billing_amount'] : $r['billing_amount'];

	if (REZGO_WORDPRESS) {
		if ($r['billing_amount'] == 'custom') {
			$_SESSION['gift-card']['billing_amount'] = 'custom';
		} else {
			unset($_SESSION['gift-card']['custom_billing_amount']);
		}
	}
	$show_gc = $site->showGiftCardPurchase();
	$tg_enabled = $tips_enabled = $analytics_ga4 = $analytics_gtm = 0;
?>

<script>
	let debug = <?php echo DEBUG; ?>;
	let overall_total = parseFloat(decodeURIComponent( '<?php echo rawurlencode( (string) $complete_booking_total ); ?>' ));
	complete_booking_total = overall_total.toFixed(2);

	setTimeout(() => {
		jQuery('input[name=billing_amount]').val(complete_booking_total);
        parent.scrollTo(0,0);
	}, 500);
</script>

<div class="container-fluid rezgo-container rezgo-gift-card-outer-container" role="main">
    <div class="row">
		<div class="rezgo-gift-card-inner-col">

			<?php if ($show_gc) { ?>

				<?php $option = isset($r['option']) ? $site->getTours('t=uid&q='.$r['option']) : ''; ?>

					<form id="rezgo-payment-form" class="gift-card-purchase" role="form" method="post" target="rezgo_content_frame">

						<input type="hidden" name="billing_amount">

							<?php if ($option) { ?>
								<input type="hidden" name="option" value ="<?php echo $r['option']; ?>">
							<?php } ?>

							<?php if (REZGO_WORDPRESS) { ?> 
								<?php foreach ($r as $k => $v) {
										if (in_array($k, PAX_ARRAY)) {
											if ((int)$v > 0) {  ?>
											<input type="hidden" name="<?php echo $k; ?>" value ="<?php echo $v; ?>">
										<?php } ?>
									<?php } ?>
								<?php } ?>

							<?php } else { ?>
								<?php if ($r['pax']) { ?>

									<?php foreach ($r['pax'] as $pax => $num){
										if ((int)$num > 0) { ?>
											<input type="hidden" name="<?php echo $pax . '_num'; ?>" value ="<?php echo $num; ?>">
										<?php } ?>
									<?php } ?>

								<?php } ?>
							<?php } ?>

						<div class="rezgo-gift-card-container step-two row">

							<div class="col-lg-8 col-md-12 rezgo-gift-card-left-wrp">

							<div class="col-12">
								<div class="rezgo-gift-card-head">
									<h3 class="gc-page-header space-below"><span>Gift Card Recipient</span></h3>
									<i class="far fa-gift-card gift-icon"></i>
								</div>

								<div class="row">
									<div class="col-12 col-sm-6">
										<div class="form-group">
											<label for="recipient_name" class="control-label">
												<span>Name</span>
											</label>

											<input class="form-control required" name="recipient_name" type="text" placeholder="Full Name" value="">
										</div>
									</div>

									<div class="col-12 col-sm-6">
										<div class="form-group">
											<label for="recipient_email" class="control-label">
												<span>Email Address</span>
											</label>

											<input class="form-control required" name="recipient_email" type="email" placeholder="Email Address" value="">
										</div>
									</div>

								</div>

								<div class="row">
									<div class="col-12">
										<div class="form-group">
											<label for="recipient_message" class="control-label">Your Message (optional)</label>

											<textarea class="form-control gc-recipient-message" name="recipient_message" rows="5" style="resize:none;height:130px;" placeholder="Your Message"></textarea>
										</div>
									</div>
								</div>

								<div id="rezgo-gift-card-memo-sendto"><span></span></div>
							</div>

							<div class="clearfix">

									<div class="rezgo-payment-frame gift-card-payment" id="payment_info">
										<div class="col-12 rezgo-gift-card-head">
											<h3 class="gc-page-header space-below">Payment Method</h3>
										</div>
										<!-- PAYMENT MODULE -->
                               			<?php require 'payment_module.php'; ?>
									</div>
								</div>

								<hr>

								<div class="clearfix">
									<div class="rezgo-gift-card-head">
										<h3 class="gc-page-header space-below"><span>Billing Information</span></h3>
									</div>

									<div class="col-12">
										<div class="form-group">
											<div class="col-12">
												<label for="billing_first_name" class="control-label">
													<span>Name</span>
												</label>
											</div>
											<div class="row">
												<div class="col-12 col-sm-6">
													<input class="form-control required" name="billing_first_name" id="billing_first_name" type="text" placeholder="First Name" />
												</div>

												<div class="col-12 col-sm-6">
													<input class="form-control required" name="billing_last_name" id="billing_last_name" type="text" placeholder="Last Name" />
												</div>
											</div>
										</div>

										<div class="form-group">
											<label for="billing_address_1" class="control-label">
												<span>Address</span>
											</label>
											<div class="rezgo-form-input col-12">
												<input class="form-control required" name="billing_address_1" id="billing_address_1" type="text" placeholder="Address 1" />
											</div>
											<div class="rezgo-form-input col-12">
												<input class="form-control" name="billing_address_2" id="billing_address_2" type="text" placeholder="Address 2 (optional)" />
											</div>
										</div>

										<label for="rezgo_confirm_id" id="rezgo_confirm_label">
											<span>Confirm ID</span>
										</label>

										<input name="rezgo_confirm_id" id="rezgo_confirm_id" type="text" value="" tabindex="-1" autocomplete="off">

										<div class="form-group">
											<div class="rezgo-form-row">
												<div class="col-12 rezgo-form-input">
													<label for="billing_city" class="control-label">
														<span>City</span>
													</label>

													<input class="form-control required" id="billing_city" name="billing_city" type="text" placeholder="City" />
												</div>
											</div>
										</div>


										<div class="form-group">
											<div class="rezgo-form-row">
												<div class="col-12 rezgo-form-input">
													<label for="billing_postal_code" class="control-label">
														<span>Zip/Postal</span>
													</label>

													<input class="form-control required" name="billing_postal_code" type="text" placeholder="Zip/Postal Code" id="billing_postal_code" />
												</div>
											</div>
										</div>

										<div class="form-group">
											<div class="rezgo-form-row">
												<div class="col-12 rezgo-form-input">
													<label for="billing_country" class="control-label">
														<span>Country</span>
													</label>

													<select id="billing_country" name="billing_country" class="form-select">
														<?php foreach ($site->getRegionList() as $iso => $name) { ?>
															<option value="<?php echo $iso; ?>" <?php echo (($iso == $companyCountry) ? 'selected' : ''); ?> ><?php echo ucwords($name); ?></option>
														<?php } ?>
													</select>
												</div>
											</div>
										</div>

										<div class="form-group">
											<div class="rezgo-form-row">
												<div class="col-12 rezgo-form-input">
														<div class="rezgo-form-row">
														<label for="billing_stateprov" class="control-label">
															<span>State/Prov</span>
														</label>

														<select id="billing_stateprov" class="form-select" style="<?php echo (($companyCountry != 'ca' && $companyCountry != 'us' && $companyCountry != 'au') ? 'display:none' : ''); ?>" ></select>

														<input id="billing_stateprov_txt" class="form-control" name="billing_stateprov" type="text" value="" placeholder="State/Province" style="<?php echo (($companyCountry != 'ca' && $companyCountry != 'us' && $companyCountry != 'au') ? '' : 'display:none'); ?>" />
													</div>
												</div>
											</div>
										</div>

										<div class="form-group">
											<div class="rezgo-form-row">
												<div class="col-12 rezgo-form-input">
													<label for="billing_email" class="control-label">
														<span>Email</span>
													</label>

													<input class="form-control required" name="billing_email" id="billing_email" type="email" placeholder="Email Address" />
												</div>
											</div>
										</div>

										<div class="form-group">
											<div class="rezgo-form-row">
												<div class="col-12 rezgo-form-input">
													<label for="billing_phone" class="control-label">
														<span>Phone</span>
													</label>

													<input class="form-control required" name="billing_phone" id="billing_phone" type="text" placeholder="Phone Number" />
												</div>
											</div>
										</div>


										<input type="hidden" name="validate[language]" id="validate_language" value="">
										<input type="hidden" name="validate[height]" id="validate_height" value="">
										<input type="hidden" name="validate[width]" id="validate_width" value="">
										<input type="hidden" name="validate[tz]" id="validate_tz" value="">
										<input type="hidden" name="validate[agent]" id="validate_agent" value="">
										<input type="hidden" name="validate[callback]" id="validate_callback" value="">

										<script>
										jQuery(function($) {
											$('#validate_language').val(navigator.language);
											$('#validate_height').val(window.innerHeight);
											$('#validate_width').val(window.innerWidth);
											$('#validate_tz').val(new Date().getTimezoneOffset());
											$('#validate_agent').val(navigator.userAgent);
											$('#validate_callback').val(window.location.protocol + '//' + window.location.hostname + '<?php echo esc_html($site->base); ?>' + '/3DS');
										});
										</script>

										<div id='rezgo-credit-card-success' style='display:none;'></div>
										
										<div id="rezgo-payment-wrp">
											<div class="row">
												<div class="col-12">
													<div class="rezgo-form-row rezgo-terms-container">
														<div class="col-sm-12 rezgo-payment-terms">
															<div class="rezgo-form-input">

																<div class="checkbox">
																	<label id="rezgo-terms-check">

																		<input type="checkbox" id="agree_terms" name="agree_terms" value="1" required style="position:relative; top:1px;"/>

																		I agree to the

																		<a data-toggle="collapse" class="rezgo-terms-link" onclick="jQuery('#rezgo-privacy-panel').hide(); jQuery('#rezgo-terms-panel').toggle();">
																			<span>Terms and Conditions</span>
																		</a>
																		and
																		<a data-toggle="collapse" class="rezgo-terms-link" onclick="jQuery('#rezgo-terms-panel').hide(); jQuery('#rezgo-privacy-panel').toggle();">
																			<span>Privacy Policy</span>
																		</a>

																	</label>

																	<span for="agree_terms" class="help-block"></span>

																	<div id="rezgo-terms-panel" class="collapse rezgo-terms-panel">
																		<?php echo wp_kses($site->getPageContent('terms'), ALLOWED_HTML); ?>
																	</div>

																	<div id="rezgo-privacy-panel" class="collapse rezgo-terms-panel">
																		<?php echo wp_kses($site->getPageContent('privacy'), ALLOWED_HTML); ?>
																	</div>

																</div>

															</div>

														</div>
													</div>
												</div>
											</div>
										</div>

										<div class="col-sm-12 rezgo-payment-terms">
											<div id="rezgo-book-terms">
												<div class="help-block" id="terms_credit_card">
												<span> Please note that your credit card will be charged.</span>
													<br>
													<span>If you are satisfied with your entries, please confirm by clicking the
														<span id="rezgo-book-terms-wording">
															<span>&quot;Complete Purchase&quot;</span>
														</span>
														button.
													</span>
												</div>
											</div>
										</div>

								</div>
							</div>

							<div id="rezgo-book-message" class="row" style="display:none;">
								<div id="rezgo-book-message-body" class="col-sm-8 offset-sm-2"></div>
								<div id="rezgo-book-message-wait" class="col-sm-2"><i class="far fa-sync fa-spin fa-3x fa-fw"></i></div>
							</div>

							<hr>

							<div id="rezgo-book-errors" style="display:none;">
								<div>Some required fields are missing or incorrect. Please review the highlighted fields.</div>
							</div>

							<div class="rezgo-gift-card-cta">
								<span class="btn-check"></span>
								<button type="submit" class="btn rezgo-btn-book btn-lg btn-block rezgo-btn-wrp" id="rezgo-complete-payment">
									<span>
										Complete Purchase <span id="gc_total_due"></span>
									</span>
								</button>

								<?php if (REZGO_LITE_CONTAINER) { ?>
									<?php // build link with $_POST
									$pax = '';
									foreach ($_POST['pax'] as $k => $v) {
										if ((int)$v > 0) {
											$pax .= '&'.$k.'='.$v;
										}
									}
									$giftlink = $_POST['option'] ? '/'.$_POST['option'].'/'.$_POST['date'] : '';
									$backlink = '?billing_amount='.$_POST['billing_amount'].'&custom_billing_amount='.$_POST['custom_billing_amount'].'&recipient_name='.$_POST['recipient_name'].'&recipient_email='.$_POST['recipient_email'].'&recipient_message='.$_POST['recipient_message']; ?>
									
									<a class="underline-link" id="gc_backlink" onclick="<?php echo LOCATION_WINDOW; ?>.location.href='<?php echo $site->base; ?>/gift-card<?php echo $giftlink.$backlink.$pax; ?>'; return false;"><span>Previous Step</span></a>

								<?php } else { ?>
								<?php // create backlink to preserve pax changes on back
									$pax = '';
									$pax_count = 0;
									$giftlink = '';
									if (isset($r['buy_as_gift'])){ 
										if (REZGO_WORDPRESS) {
											foreach ($r as $k => $v) {
												if (in_array($k, PAX_ARRAY)) {
													if (strpos($k, '_num')) {
														$k = str_replace('_num','', $k);
													} 
													if ((int)$v > 0) {
														$pax .= ($pax_count > 0 ? '&' : '?') .$k.'='.$v;
														$pax_count++;
													}
												}
											}
											$giftlink = $r['option'] ? '/'.$r['option'].'/'.$r['date'] : '';
										} else {
											foreach ($_POST['pax'] as $k => $v) {
												if ((int)$v > 0) {
													$pax .= ($pax_count > 0 ? '&' : '?') .$k.'='.$v;
													$pax_count++;
												}
											}
											$giftlink = $_POST['option'] ? '/'.$_POST['option'].'/'.$_POST['date'] : '';
										}
									}
								?>

									<a class="underline-link" id="gc_backlink" onclick="<?php echo LOCATION_WINDOW; ?>.location.href='<?php echo $site->base; ?>/gift-card<?php echo $giftlink.$pax; ?>'; return false;"><span>Previous Step</span></a>
								<?php } ?>
							</div>

							<?php if($site->exists(REZGO_CAPTCHA_PUB_KEY)) { ?>	
								<input type="hidden" name="recaptcha_response" id="recaptchaResponse">
							<?php } ?>
						</form>
					</div>
					<?php require('fixed_cart_gift_card.php'); ?>
				</div>

			<?php } ?>
		</div>
	</div>

<?php if (REZGO_WORDPRESS && $site->exists(REZGO_CAPTCHA_PUB_KEY)) { ?>
	<script src="https://www.google.com/recaptcha/api.js?render=<?php echo esc_html(REZGO_CAPTCHA_PUB_KEY); ?>"></script>
<?php } ?>

<?php if ($show_gc) { ?>
	<script>

		<?php if (REZGO_LITE_CONTAINER) { ?>
			// simulates user click on the back button with backlink params
			if (window.history && window.history.pushState) {
				$(window).on('popstate', function() {
					$('#gc_backlink').click();
					return false;
				});
				window.history.pushState('forward', null);
			}
		<?php } ?>

		// FORM VALIDATE
	 	jQuery('#rezgo-payment-form').validate({
			rules: {
				recipient_email: {
					validate_domain: true,
				},
				billing_email: {
					validate_domain: true,
				}
			},
			messages: {
				recipient_first_name: {
					required: "Enter recipient first name"
				},
				recipient_last_name: {
					required: "Enter recipient last name"
				},
				recipient_address_1: {
					required: "Enter recipient address"
				},
				recipient_city: {
					required: "Enter recipient city"
				},
				recipient_postal_code: {
					required: "Enter recipient postal code"
				},
				recipient_phone_number: {
					required: "Enter recipient phone number"
				},
				recipient_email: {
					required: "Enter a valid email address"
				},
				billing_first_name: {
					required: "Enter billing first name"
				},
				billing_last_name: {
					required: "Enter billing last name"
				},
				billing_address_1: {
					required: "Enter billing address"
				},
				billing_city: {
					required: "Enter billing city"
				},
				billing_state: {
					required: "Enter billing state"
				},
				billing_country: {
					required: "Enter billing country"
				},
				billing_postal_code: {
					required: "Enter billing postal code"
				},
				billing_email: {
					required: "Enter a valid email address"
				},
				billing_phone: {
					required: "Enter billing phone number"
				},
				payment_method: {
					required: "Please select a payment method"
				},
				terms_agree: {
					required: "You must agree to our terms &amp; conditions"
				}
			}
		});

		// FORM COUNTRY & STATES OPTIONS SWITCH
		jQuery('#billing_country').change(function() {
			var country = jQuery(this).val();

			jQuery('#billing_stateprov').removeOption(/.*/);
			switch (country) {
				case 'ca':
					jQuery('#billing_stateprov_txt').hide();
					jQuery('#billing_stateprov').addOption(ca_states, false).show();
					jQuery('#billing_stateprov_txt').val(jQuery('#billing_stateprov').val());
					break;
				case 'us':
					jQuery('#billing_stateprov_txt').hide();
					jQuery('#billing_stateprov').addOption(us_states, false).show();
					jQuery('#billing_stateprov_txt').val(jQuery('#billing_stateprov').val());
					break;
				case 'au':
					jQuery('#billing_stateprov_txt').hide();
					jQuery('#billing_stateprov').addOption(au_states, false).show();
					jQuery('#billing_stateprov_txt').val(jQuery('#billing_stateprov').val());
					break;		
				default:
					jQuery('#billing_stateprov').hide();
					jQuery('#billing_stateprov_txt').val('');
					jQuery('#billing_stateprov_txt').show();
					break;
			}
		});
		jQuery('#billing_stateprov').change(function() {
			var state = jQuery(this).val();

			jQuery('#billing_stateprov_txt').val(state);
		});
		<?php if (in_array($companyCountry, array('ca', 'us', 'au'))) { ?>
		jQuery('#billing_stateprov').addOption(<?php echo $company->country ?>_states, false);
			jQuery('#billing_stateprov_txt').val(jQuery('#billing_stateprov').val());
		<?php } ?>

		<?php if ($site->exists(REZGO_CAPTCHA_PUB_KEY)) { ?>
			// RECAPTCHA V3
			function verifyRecaptcha() {
				grecaptcha.ready(function() {
					grecaptcha.execute('<?php echo REZGO_CAPTCHA_PUB_KEY; ?>', {action: 'submit'}).then(function(token) {
						var recaptchaResponse = document.getElementById('recaptchaResponse');
						recaptchaResponse.value = token;
					});
				});
			}
		<?php } ?>

		function show_response () {
			let strArray, json, card, body;

			strArray = response.split("|||");         
			strArray = strArray.slice(-1)[0];     
			json = JSON.parse(strArray);          
			response = json.response;
			card = json.card;

			if (response == 1) {
				jQuery('#rezgo-payment-form')[0].reset();
				<?php echo LOCATION_REPLACE; ?>('<?php echo esc_html($site->base); ?>/gift-receipt/'+card);
			} else {
				if (response == 2) {
					body = 'Sorry, your transaction could not be completed at this time.';
				} else if (response == 3) {
					body = 'Sorry, your payment could not be completed. Please verify your card details and try again.';
				} else if (response == 4) {
					body = 'Sorry, there has been an error with your transaction and it can not be completed at this time.';
				} else if (response == 5) {
					body = 'Sorry, you must have a credit card attached to your Rezgo Account in order to purchase a gift card.<br><br>Please go to "Settings &gt; Rezgo Account" to attach a credit card.';
				} else if (response == 8) {

					if(json.direct) {
						// frictionless flow   
						sca_window('direct', null, json.direct, json.pass);
						return false;
					} else {
						// challenge flow
						sca_window('iframe', json.url, json.post, json.pass);
					}
					
				} else {
					body = 'Sorry, an unknown error has occurred. If this keeps happening, please contact <?php echo addslashes($company->company_name); ?>.';
				}

				jQuery('#rezgo-credit-card-success').hide().empty();
				
				if(body) {
					reset_payment(body);
				}
			}
		}

		function formatCurrency(amount){
			jQuery.ajax({
				url: '<?php echo admin_url('admin-ajax.php'); ?>', 
				data: {
					action: 'rezgo',
					method: 'gift_card_ajax',
					rezgoAction:'formatCurrency',
					amount: amount,
				},
				type: 'POST',
				success: function (result) {
					// console.log(result);
					jQuery('#gc_total_due').html('of ' + result);
				}
			});
		}

		// fill in default value of the first selected amount
		formatCurrency(<?php echo $complete_booking_total; ?>);

		jQuery('#rezgo-payment-form').submit(function(e) {
			e.preventDefault();
			submit_payment();
		});
	</script>
<?php } ?>