<?php $this->load->view('includes/head') ?>
<?php $this->load->view('includes/topbar') ?>
<?php $this->load->view('includes/header') ?>
<style type="text/css">
	@media (min-width: 1025px) {
		.h-custom {
			height: 100vh !important;
		}
	}

	.card-registration .select-input.form-control[readonly]:not([disabled]) {
		font-size: 1rem;
		line-height: 2.15;
		padding-left: .75em;
		padding-right: .75em;
	}

	.card-registration .select-arrow {
		top: 13px;
	}

	.bg-grey {
		background-color: #eae8e8;
	}

	@media (min-width: 992px) {
		.card-registration-2 .bg-grey {
			border-top-right-radius: 16px;
			border-bottom-right-radius: 16px;
		}
	}

	@media (max-width: 991px) {
		.card-registration-2 .bg-grey {
			border-bottom-left-radius: 16px;
			border-bottom-right-radius: 16px;
		}
	}

	.booknow-btn {
		background-color: #ffc107;
		padding: 5px 14px;
		color: #15102e;
		border-radius: 6px !important;
		font-size: 17px;
		font-weight: 1000;
		border: 0px !important;
		margin: 0px 8px;
	}
</style>

<?php
$current_user = getUserDetails()->data[0];
$fgh = getFullPaymentSettings();


$dsbj = $fgh['result']['data'][0]['paymentGatewayoffon'];

foreach ($dsbj as $key => $dd) {
	if ($dd['source'] == 'WEBSITE') {
		$paymentSeverOn = $dd['isenable'];
		$paymentSeverText = $dd['desc'];
	}
}
$paymentSetting = @getPaymentGatewaySettings();
// echo $paymentSetting;

$getclientInfoById = @getclientInfoById()['data'][0];

 $CAW_MerchantId = @$getclientInfoById['ChargeAnywhereMerchantId'] ;
 $CAW_TerminalId = @$getclientInfoById['ChargeAnywhereTerminalId'] ;



?>
<main id="main">
	<section style="background-size: auto;">
		<center>
			<h2 class="bottomborder" style="font-weight:bold!important;font-size: 35px!important;">Checkout</h2>
		</center>
		<!-- <button onclick="window.history.back()">Go Back</button> -->
		<br>
		<div class="h-100 responsive-container">
			<div class="row d-flex justify-content-center align-items-center h-100">
				<div class="col-12">
					<div class="card card-registration card-registration-2 mb-4" style="border-radius: 15px;">
						<div class="card-body p-3">
							<div class="card-header text-end px-3" style="font-size: 18px!important;background-color:var(--main-color-new-theme);">
								<a href="javaScript:void(0)" class="btn" onclick="window.history.back()" style="background-color:var(--main-color-new-theme);color: white!important;border-radius: 1px!important; display:none;">← Back</a>
								<a href="<?= base_url('donations'); ?>" class="btn" style=";background-color:#e78b00;color: white!important;border-radius: 1px!important;">Close X</a>
							</div>
							<?php
							$currencySymbol = isset($GeneralSettings['currencySymbol']) ? (CheckEmptyNullVar($GeneralSettings['currencySymbol']) != '' ? $GeneralSettings['currencySymbol'] : '$') : '$';

							if (isset($this->session->userdata($session_data)['ids'])) { ?>


								<div class="row g-0">
									<div class="col-lg-7" style="background-color:#f5f5f5">
										<div class="p-5">
											<?php $cart_items = $this->session->userdata($session_data); ?>
											<div class="d-flex justify-content-between align-items-center mb-5">
												<h3 class="fw-bold mb-0 text-black">Order Summary</h3>
												<?php foreach ($cart_items['ids'] as $key => $value) {
												} ?>
												<h6 class="mb-0 text-muted"><?= $key + 1; ?> items</h6>
											</div>
											<hr class="my-4">
											<!-- ============================================= -->
											<div class="table-responsive">
												<table style="width:100%">
													<thead>
														<tr>
															<th style="width:40%" class="text-start">Donation Name</th>
															<!-- <th style="width:40%" class="text-center">Category</th> -->
															<th style="width:5%" class="text-center">Qty</th>
															<th style="width:15%" class="text-end">Amount</th>
														</tr>
													</thead>
													<tbody>
														<?php
														foreach ($cart_items['ids'] as $key => $value) { ?>
															<tr>
																<td class="text-start"><?= $cart_items['serviceName'][$key]; ?></td>
																<!-- <td class="text-center"><?= $cart_items['ctg'][$key]; ?></td> -->
																<td class="text-center"><?= $cart_items['qty'][$key]; ?></td>
																<td class="text-end"><?= $currencySymbol . ' ' . price_format($cart_items['serviceAmount'][$key], 2); ?></td>
															</tr>
														<?php } ?>
													</tbody>
												</table>
											</div>
											<!-- ============================================= -->

											<hr class="my-4">
											<?php if (@CheckEmptyNullVar($GeneralSettings['TaxPercent']) != '' && @$GeneralSettings['TaxPercent'] > 0) { ?>

												<div class="row mt-3">
													<div class="col-md-10">
														<h5 class="mb-0" style="font-weight:bold!important;">Tax (<?= @$GeneralSettings['TaxPercent'] != '' || @$GeneralSettings['TaxPercent'] != 0 ?  @$GeneralSettings['TaxPercent'] : 0 ?>%)</h5>
													</div>
													<div class="col-md-2 text-end"><span style="font-weight:bold!important;"><?= $currencySymbol ?> <?= (price_format($cart_items['totalPrice'], 2) * price_format(@$GeneralSettings['TaxPercent'], 2)) / 100; ?></span></div>

													<?php $taxAmt = (price_format($cart_items['totalPrice'], 2) * price_format(@$GeneralSettings['TaxPercent'], 2)) / 100; ?>
												</div>

												<hr class="my-4">
											<?php } else {
												$taxAmt = 0;
											} ?>

											<div class="row mt-3">
												<div class="col-md-10">
													<h5 class="mb-0" style="font-weight:bold!important;">Subtotal</h5>
												</div>
												<div class="col-md-2 text-end"><span style="font-weight:bold!important;"><?= $currencySymbol ?> <?= price_format($cart_items['totalPrice'], 2); ?></span></div>

											</div>


											<hr class="my-4">

											<div class="row p-3" style="background-color:#dbdbdb">
												<div class="col-md-8">
													<h4 class="text-dark" style="margin-top:auto;margin-bottom:auto;font-weight: bold!important;">Sale Total</h4>
												</div>
												<div class="col-md-4">

													<h4 class="text-dark text-end" style="margin-top:auto;margin-bottom:auto;font-weight: bold!important;"><?= $currencySymbol ?>&nbsp;<?= price_format(($cart_items['totalPrice'] + @$taxAmt), 2); ?>
												</h4>
											</div>
										</div>
									</div>
								</div>
								<div class="col-lg-5">
									<div class="p-5">
										<div class="row">
											<div class="col-md-7 fw-bold text-start">
												<h5 class="mb-2" style="color:var(--main-color-new-theme)!important"><?= @$this->session->userdata('refDataName'); ?></h5><span><?= @base64_decode($this->session->userdata('email')); ?></span>
											</div>
											<div class="col-md-5 fw-bold text-end" style="word-wrap:none ;color:var(--main-color-new-theme)!important">

												<?= formatPhoneNumber(@base64_decode($this->session->userdata('phone'))); ?>

											</div>
										</div>
										<hr class="my-4">

										<?php $subTotal =  price_format(((($cart_items['totalPrice'] * @($GeneralSettings['TaxPercent'] ? $GeneralSettings['TaxPercent'] : 0)) / 100) +  $cart_items['totalPrice']), 2);
										$this->session->set_userdata('totalPrice', $subTotal);
										$newSubTotal = $this->session->userdata('totalPrice');
										?>
										<?php if (@CheckEmptyNullVar($GeneralSettings['TaxPercent']) != '' && @$GeneralSettings['TaxPercent'] > 0) {
											$cart_items['totalPrice'] = (price_format($cart_items['totalPrice'], 2) * price_format(@$GeneralSettings['TaxPercent'], 2)) / 100;
										} ?>
										<div class="text-center my-3">
											<div class="d-flex justify-content-between my-4">
												<h3 class="fw-bold" style="font-size: 25px;">Amount to Pay:</h3>
												<h3 class="fw-bold text-end" style="font-size: 25px;border: 2px solid #dbdbdb;border-radius: 9px;padding: 3px;" id="total-price"><?= $currencySymbol ?>&nbsp;<?= price_format($cart_items['totalPrice'], 2); ?></h3>
											</div>

											<?php if ($paymentSeverOn == 1) {

												if (isset($paymentSetting) && ($paymentSetting == 'MPI'|| $paymentSetting == 'MPITEST')) { ?>

													<style>
														#amount {
															width: 75px;
														}

														#card {
															background: #ffffffa3;
															height: 100px;
															padding: 10px 12px;
															border-radius: 5px;
															border: 1px solid #84a6ae;
															box-sizing: border-box;
															line-height: 0;
															margin: 9px 0px;
															width: 500px;
														}

														.input-style {
															color: #32a866;
														}

														.input-hint {
															color: #5e95a1;
															border-color: #9ac0c8;
														}

														/* All fields in form */
														.form-wrapper {
															width: 400px;
														}

														/* Credit Card Number */
														.input-wrapper {
															width: 200px;
														}

														/* Expiry Date */
														.sub-wrapper {
															width: 100px;
														}

														.valid-class {
															color: #217195;
														}

														.invalid-class {
															color: #b05826;
														}

														* {
															box-sizing: border-box;
														}

														.row {
															display: -ms-flexbox;
															/* IE10 */
															display: flex;
															-ms-flex-wrap: wrap;
															/* IE10 */
															flex-wrap: wrap;
															margin: 0 -16px;
														}

														.col-25 {
															-ms-flex: 25%;
															/* IE10 */
															flex: 25%;
														}

														.col-50 {
															-ms-flex: 50%;
															/* IE10 */
															flex: 50%;
														}

														.col-30 {
															-ms-flex: 30%;
															/* IE10 */
															flex: 30%;
														}

														.col-75 {
															-ms-flex: 75%;
															/* IE10 */
															flex: 75%;
														}

														.col-25,
														.col-50,
														.col-75 {
															padding: 0 16px;
														}


														.form-control:focus {
															color: #495057;
															background-color: #fff;
															border-color: #000408;
															outline: 0;
															box-shadow: 0 0 0 0.04rem rgb(0 0 0);
														}


														.icon-container {
															margin-bottom: 20px;
															padding: 7px 0;
															font-size: 24px;
														}




														hr {
															border: 1px solid lightgrey;
														}

														span.price {
															float: right;
															color: grey;
														}
													</style>
													<form id="paymentForm" action="https://www.bridgepaynetsecuretx.com/WebSecurity/echo.aspx" method="post" style=" max-width: 500px;margin: auto;">
														<div class="row px-0">
															<div class="col-md-12 px-0">
																<h6 class="text-center">Card Details</h6>
																<div id="card" class="mx-0" style="width: 100%!important;height: 150px;"></div>
																<div id="errorMessage" style="margin-bottom: 10px; color: #c0392b;"></div>
															</div>

															<div class="col-md-12 px-0">
																<!-- <h6 class="text-center">Billing Address</h6> -->
																<p for="fname" style="text-align: justify;margin-bottom: 0px;font-weight: 600;">Name on Card <span class="text-danger">*</span></p>

																<input type="text" class="form-control" id="fname" name="firstname" placeholder="Enter Your Full Name*" required style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?=@$current_user->refDataName; ?>">
																<input type="email" id="email" class="form-control d-none" name="email" placeholder="Enter Your Email Address" style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?=base64_decode(@$current_user->email);?>" oninput="this.value = this.value.toLowerCase();">
																<!-- <input type="text" class="form-control" id="address" name="address" placeholder="Enter Your Street Address" style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?=@$current_user->addressLine1;?>"> -->
																<p for="zipcode" style="text-align: justify;margin-bottom: 0px;font-weight: 600;">ZIP Code <span class="text-danger">*</span></p>

																<input type="number" class="form-control" id="zipcode" name="zipcode" placeholder="Enter Your Zipcode" required style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?=@$current_user->zip;?>">

																<div class="row m-0 p-0 d-none">
																	<div class="col-md-12 px-0 d-none">
																		<input type="text" id="state" name="state" placeholder="State*" style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?=@$current_user->stateTypes;?>">
																	</div>
																	<div class="col-md-12 px-0 d-none">
																		<input type="text" id="city" name="city" placeholder="City*" style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?=@$current_user->cityTypes;?>">
																	</div>
																</div>

																<!-- <div class="col-md-12 px-0">
																	<h6 class="text-center">Billing Address</h6>
																	<input type="text" class="form-control" id="fname" name="firstname" placeholder="Enter Your Full Name*" required style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?= @$current_user->refDataName; ?>">
																	<input type="email" id="email" class="form-control" name="email" placeholder="Enter Your Email Address" required style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?= base64_decode(@$current_user->email); ?>" oninput="this.value = this.value.toLowerCase();">
																	<input type="text" class="form-control" id="address" name="address" placeholder="Enter Your Street Address" style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?= @$current_user->addressLine1; ?>">

																	<input type="number" class="form-control" id="zipcode" name="zipcode" placeholder="Enter Your Zipcode" style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?= @$current_user->zip; ?>">

																	<div class="row m-0 p-0 ">
																		<div class="col-md-12 px-0">
																			<input type="text" id="state" name="state" placeholder="State*" style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?= @$current_user->stateTypes; ?>">
																		</div>
																		<div class="col-md-12 px-0">
																			<input type="text" id="city" name="city" placeholder="City*" style="width: 100%; margin-bottom: 20px; padding: 12px; border: 1px solid #ccc; border-radius: 3px;    padding-top: 12px!important;" value="<?= @$current_user->cityTypes; ?>">
																		</div>
																	</div> -->

																	<center>
																		<button type="submit" class="btn btn-success" style="max-width: 500px;margin: auto;border-radius: 4px!important;font-weight: 800;padding: 8px 24px;background: #e78b00;border: 0;text-shadow: 1px 1px 0px black;">PAY NOW</button>
																	</center>
																</div>
															</div>

														</form>

													</form>

												<?php } else if (isset($paymentSetting) && $paymentSetting == 'CHARGEANYWHERE') { ?>

													<iframe id="paymentIframe" title="Payment Page" width="100%" height="600px"></iframe>

												<?php }else{ ?>

													<div id="paypal-button-container"></div>

												<?php } } else { ?>

													<span class="alert mt-5 alert-danger text-center fw-bold"><i class="fa fa-warning fw-bold"></i> <?= $paymentSeverText; ?></span>
												<?php } ?>



											
											</div>
										</div>
									</div>
								</div>
								<input type="hidden" id="totalDonation" value="<?= price_format($cart_items['totalPrice'], 2); ?>">
							<?php } else { ?>

								<div class="text-center  my-5">
									<h3 class="text-danger text-center fw-bold mb-5">Your Cart is empty!</h3>
									<a href="<?= base_url('donations') ?>" class='btn text-center btn-primary btn-sm checkoutbtn' style='background: #910301; border: 1px solid yellow;'>Go to Donations</a>
								</div>

							<?php } ?>
						</div>
					</div>
				</div>
			</div>
		</div>
	</section>
</main>

<!-- Live Client Id -->

<?php if ($paymentSeverOn == 1 && $paymentSetting == 'PAYPAL') { ?>
	<?php $paypalLiveClientId  = $getclientInfoById['paypalClientId']; ?>
	<script src="https://www.paypal.com/sdk/js?client-id=<?= $paypalLiveClientId ?>&enable-funding=venmo&intent=capture" data-sdk-integration-source="integrationbuilder"></script>
<?php } ?>

<?php $this->load->view('includes/footer') ?>

<script type="text/javascript">
	var loader = new ldLoader({
		root: ".ldld.full"
	});
	if (window.performance && window.performance.navigation.type === window.performance.navigation.TYPE_BACK_FORWARD) {
		loader.on();
	}
	document.addEventListener("click", function(event) {
		if (event.target.matches(".navlink, .loader")) {
			loader.on();
		}
	});
	window.onload = function() {
		loader.off();
	};
</script>

<?php if (isset($paymentSetting) && $paymentSetting == 'PAYPAL') { ?>

	<script type="text/javascript">
		const paypalButtonsComponent = paypal.Buttons({
			style: {
				shape: 'rect',
				color: 'gold',
				layout: 'vertical',
				label: 'paypal',
			},
			createOrder: (data, actions) => {
				var currency = "USD";

				amt = $("#totalDonation").val();

				var status = 'TEMP';
				var paymentSource = data.paymentSource;

				var totalPrice = amt;

				var cart_data = '<?php echo json_encode($cart_items) ?>';

				$.ajax({
					url: "<?= base_url('Donations/AddToCart') ?>",
					type: "POST",
					dataType: "json",
					data: {
						'status': status,
						'paymentSource': paymentSource,
						'totalPrice': totalPrice,
						'cart_data': cart_data,
					},
					success: function(response) {
						loader.off();
						console.log(response);
					}
				});




				const createOrderPayload = {
					purchase_units: [{
						amount: {
							currency_code: currency,
							value: amt
						}
					}]
				};
				return actions.order.create(createOrderPayload);
			},
			onApprove: (data, actions) => {
				const captureOrderHandler = (details) => {

					loader.on();
					var status = 'COMPLETED';

					// var orderid = details.id;
					var status = details.status;

					var transaction_id = details.purchase_units[0].payments.captures[0].id;

					$.ajax({
						url: "<?= base_url('Donations/updateTransactionStatus') ?>",
						type: "POST",
						dataType: "json",
						data: {
							'status': status,
							'transaction_id': transaction_id,
							'paymentDescription': details
						},
						success: function(response) {
							loader.off();
							if (response.statusCode == 1) {
								swal({
									html: true,
									title: "Payment Successfully Processed!",
									text: "<span style='font-weight: 600;margin:5px;padding:5px'>Order No:</span> " + response.envoiceNo,
									type: "success",
									confirmButtonText: 'OK',
									confirmButtonColor: 'var(--main-color-new-theme)',
								},
								function() {
									window.location.reload();
								});
							} else {
								swal({
									html: true,
									title: "Failed!",
									text: "<span>Transaction Failed!<span><br><span style='font-weight: 600;margin:5px;padding:5px'>Order No:</span> " + response.envoiceNo,
									type: "error",
									confirmButtonText: 'OK',
									confirmButtonColor: 'var(--main-color-new-theme)',
								},
								function() {
									window.location.reload();
								});
							}
						}
					});
				};

				return actions.order.capture().then(captureOrderHandler);
			},

			onError: (err) => {

				console.log(err);
				alert('Transaction Failed');

			}
		});

		paypalButtonsComponent
		.render("#paypal-button-container")
		.catch((err) => {
			console.log('PayPal Buttons failed to render');
		});
	</script>

<?php } ?>







<?php if (isset($paymentSetting) && ($paymentSetting == 'MPITEST' || $paymentSetting == 'MPI') && $paymentSeverOn == 1) { ?>

	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>



<!-- <script type="text/javascript" src="https://www.bridgepaynetsecuretx.com/Bridgepay.WebSecurity/TokenPay/js/tokenPay.js"></script> -->
<!-- <script type="text/javascript" src="https://www.bridgepaynetsecuretest.com/WebSecurity/TokenPay/js/tokenPay.js"></script> -->

<?php $mpiTokenPayId  = @getclientInfoById()['data'][0]['MPItokenPay'];
$MpiPayUrl = base_url('MPI_Payments/Paynow');
if (isset($mpiTokenPayId) && $mpiTokenPayId != '' && $paymentSetting == 'MPI') {
  $TokenPay = $mpiTokenPayId;
?>
  <script type="text/javascript" src="https://www.bridgepaynetsecuretx.com/Bridgepay.WebSecurity/TokenPay/js/tokenPay.js"></script>
<?php
} else {
  $TokenPay = 'tokenpay10579api20211508121542285';
  $MpiPayUrl = base_url('MPI_Payments/PaynowTest');
?>
  <script type="text/javascript" src="https://www.bridgepaynetsecuretest.com/WebSecurity/TokenPay/js/tokenPay.js"></script>
<?php
}

?>

<script>
	var tokenpay = TokenPay('<?= $TokenPay ?>');
	tokenpay.initialize({
		dataElement: '#card',
		errorElement: '#errorMessage',
		amountElement: '#amount',
		useStyles: false,
		useACH: false,
		disableZip: true,
		disableCvv: false
	});

	var form = document.getElementById('paymentForm');
	form.addEventListener('submit', function(event) {



		event.preventDefault();
		loader.on();
		tokenpay.createToken(function(result) {


			console.log(result);


			var totalPriceText = $("#total-price").text();
			var mpi_zipcode = $("#zipcode").val();
			var mpi_fname = $("#fname").val();
			var mpi_address = $("#address").val();

			var numericValue = totalPriceText.replace(/[^0-9.]/g, '');
			var numericAmount = parseFloat(numericValue);

			var totolAmt = numericAmount;


			if (result.status == 'auth_success') {
				// loader.on();

				$.ajax({
					url: "<?= $MpiPayUrl ?>",
					type: "POST",
					dataType: "json",
					data: {
						'token': result.token,
						'totolAmt': totolAmt,
						'name': mpi_fname,
						'address': mpi_address,
						'zipcode': mpi_zipcode
					},
					success: function(mpicardpayment_response) {

						console.log(mpicardpayment_response.data);
						var paymentSource = 'MPI';

						var status = 'TEMP';

						var totalPrice = totolAmt;




						var cart_data = '<?= json_encode($cart_items) ?>';


						if (mpicardpayment_response.data.responseCode == 00000) {
							var status = 'COMPLETED';

							$.ajax({
								url: "<?= base_url('Donations/AddToCart') ?>",
								type: "POST",
								dataType: "json",
								data: {
									'status': status,
									'paymentSource': paymentSource,
									'totalPrice': totalPrice,
									'cart_data': cart_data,
								},
								success: function(addtocart_response) {
									if (addtocart_response.statusCode == 1) {

										var status = 'COMPLETED';
										var trnxId = "Payment completed~" + mpicardpayment_response.data.ReferenceNumber + "~" + mpicardpayment_response.data.cardType + "~" + mpicardpayment_response.data.maskedAccountNumber;

										$.ajax({
											url: "<?= base_url('Donations/updateTransactionStatus') ?>",
											type: "POST",
											dataType: "json",
											data: {
												'status': status,
												'transaction_id': trnxId,
												'paymentDescription': mpicardpayment_response
											},
											success: function(update_transactionstatus_response) {
												if (update_transactionstatus_response.statusCode == 1) {


													swal({
															html: true,
															title: "Payment Successfully Processed!",
															text: "<span style='font-weight: 600;margin:5px;padding:5px;font-size: 27px !important;'>Order No: " + update_transactionstatus_response.envoiceNo + "</span>",
															type: "success",
															confirmButtonText: 'OK',
															confirmButtonColor: 'var(--main-color-new-theme)',
														},
														function() {
															// window.location.reload();
															window.location.href="<?= base_url('donations')?>";
														});

													loader.off();
												}

											}
										});

									}
								}
							});

						} else {

							$.ajax({
								url: "<?= base_url('Donations/AddToCart') ?>",
								type: "POST",
								dataType: "json",
								data: {

									'status': status,
									'paymentSource': paymentSource,
									'totalPrice': totalPrice,
									'cart_data': cart_data
								},
								success: function(addtocart_response) {

									if (addtocart_response.statusCode == 1) {

										var status = 'FAILED';
										var trnxId = "Payment failed~0~" + mpicardpayment_response.message;

										$.ajax({
											url: "<?= base_url('Donations/updateTransactionStatus') ?>",
											type: "POST",
											dataType: "json",
											data: {

												'status': status,
												'transaction_id': trnxId,
												'paymentDescription': mpicardpayment_response
											},
											success: function(update_transactionstatus_response) {
												if (update_transactionstatus_response.statusCode == 1) {


													var original_string = update_transactionstatus_response.message;
													var substring_to_replace = "Payment failed~0~"

													var new_string = original_string.replace(substring_to_replace, "");


													swal({
															html: true,
															title: "Failed!",
															text: "<span>" + new_string + "!<span><br><span style='font-weight: 600;margin:5px;padding:5px;font-size: 27px !important;'>Order No: " + update_transactionstatus_response.envoiceNo + "</span>",
															type: "error",
															confirmButtonText: 'OK',
															confirmButtonColor: 'var(--main-color-new-theme)',
														},
														function() {
															window.location.reload();
														});

													loader.off();
												}

											}
										});

									}
								}
							});
						}

					}
				});
			} else {
				alert('Please enter valid details');
			}

		}, function(result) {
			loader.off();
			console.log("error@@@: " + result.token);
		});
	});
</script>



<?php } ?>



<?php 

if (isset($paymentSetting) && $paymentSetting == 'CHARGEANYWHERE' && $paymentSeverOn == 1) { ?>

	<script type="text/javascript">


		$(document).ready(function() {



			var amountString = $("#total-price").text();
			var finalAmtWithoutDollar = amountString.replace("$", "");
			var finalAmt = parseInt(finalAmtWithoutDollar);
			

			var iframe = document.getElementById('paymentIframe');
			var url = "https://www.chargeanywhere.com/APIs/PayOnline.aspx?Version=2.0&MerchantId=<?=$CAW_MerchantId?>&TerminalId=<?=$CAW_TerminalId?>&Amount=" + finalAmt + "&Mode=0";
			iframe.src = url;


		});


		window.addEventListener('message', handleMessage, false);
		window.addEventListener('message', chargeanywher, false);

		function handleMessage(event) {

			if (event.origin != "https://www.chargeanywhere.com") {
				return;
			}

			var customData = event.data;


		}



		function chargeanywher(event)
		{

			loader.on();

			if (event.origin != "https://www.chargeanywhere.com") {
				return;
			}

					// console.log(event);

			var customData = event.data;


			console.log(customData);


			var cart_data = '<?= json_encode($cart_items) ?>';
			var paymentSource = 'CREDIT CARD';


			var grand_totalPrice = customData.GrandTotal;

			totalPrice = parseFloat(grand_totalPrice);




			if (customData.ResponseCode === "000") {

				var status = 'COMPLETED';



				$.ajax({
					url: "<?= base_url('Donations/AddToCart') ?>",
					type: "POST",
					dataType: "json",
					data: {

						'status': status,
						'paymentSource': paymentSource,
						'totalPrice': totalPrice,
						'cart_data': cart_data,
					},
					success: function(addtocart_response) {

						console.log(addtocart_response);



						if (addtocart_response.statusCode == 1) {

							var status = 'COMPLETED';

							var cardTypeCode = customData.CardType; 
							var cardTypeName = getCardTypeName(cardTypeCode);
							var trnxId = "Payment completed~" + customData.ReferenceNumber + "~" + cardTypeName + "~" + customData.CardNumber;


							$.ajax({
								url: "<?= base_url('Donations/updateTransactionStatus') ?>",
								type: "POST",
								dataType: "json",
								data: {

									'status': status,
									'transaction_id': trnxId,
									'paymentDescription': customData
								},
								success: function(update_transactionstatus_response) {
									if (update_transactionstatus_response.statusCode == 1) {


										swal({
											html: true,
											title: "Payment Successfully Processed!",
											text: "<span style='font-weight: 600;margin:5px;padding:5px'>Order No:</span> " + update_transactionstatus_response.envoiceNo,
											type: "success",
											confirmButtonText: 'OK',
											confirmButtonColor: 'var(--main-color-new-theme)',
										},
										function() {
											window.location.reload();
										});

										loader.off();
									}

								}
							});

						}
					}
				});



			}else{

				$.ajax({
					url: "<?= base_url('Donations/AddToCart') ?>",
					type: "POST",
					dataType: "json",
					data: {

						'status': 'TEMP',
						'paymentSource': paymentSource,
						'totalPrice': totalPrice,
						'cart_data': cart_data,
					},
					success: function(addtocart_response) {

						if (addtocart_response.statusCode == 1) {
							var status = 'FAILED';
							var cardTypeCode = customData.CardType; 
							var cardTypeName = getCardTypeName(cardTypeCode);
							var trnxId = "Payment failed~0~" + customData.ResponseText + "~" + cardTypeName + "~" + customData.CardNumber;

							$.ajax({
								url: "<?= base_url('Donations/updateTransactionStatus') ?>",
								type: "POST",
								dataType: "json",
								data: {

									'status': status,
									'transaction_id': trnxId,
									'paymentDescription': customData
								},
								success: function(update_transactionstatus_response) {
									if (update_transactionstatus_response.statusCode == 1) {

										var original_string = update_transactionstatus_response.message;
										var substring_to_replace = "Payment failed~0~"

										var new_string = original_string.replace(substring_to_replace, "");

										swal({
											html: true,
											title: "Failed!",
											text: "<span>" + new_string + "!<span><br><span style='font-weight: 600;margin:5px;padding:5px'>Order No:</span> " + update_transactionstatus_response.envoiceNo,
											type: "error",
											confirmButtonText: 'OK',
											confirmButtonColor: 'var(--main-color-new-theme)',
										},
										function() {
											window.location.reload();
										});

										loader.off();
									}

								}
							});

						}
					}
				});
			}
		}


	</script>

<?php } ?>









<!-- ==========Language Translator Code============= -->
<a href="#" class="back-to-top d-flex align-items-center justify-content-center" style="background-color:var(--headerFooter)!important;"><i class="bi bi-arrow-up-short"></i></a>


<!-- Vendor JS Files -->
<script src="<?= base_url('assets/vendor/aos/aos.js'); ?>"></script>
<script src="<?= base_url('assets/vendor/bootstrap/js/bootstrap.bundle.min.js'); ?>"></script>
<script src="<?= base_url('assets/vendor/glightbox/js/glightbox.min.js'); ?>"></script>
<script src="<?= base_url('assets/vendor/swiper/swiper-bundle.min.js'); ?>"></script>

<!-- Template Main JS File -->
<script src="<?=base_url('assets/js/main.js');?>"></script>
<div class="ldld full" style="z-index: 9999;"></div>
