<?php
// Include the configuration file
require_once 'config.php';
header('Access-Control-Allow-Origin: *'); //for al
//header( 'Access-Control-Allow-Headers: Accept, Accept-Encoding, Accept-Language, Authorization, Cache-Control, Pragma, Content-Type, Origin, Referer, Sec-Fetch-Dest, Sec-Fetch-Mode, Sec-Fetch-Site, User-Agent, X-Requested-With');
?>

<!DOCTYPE html>
<html lang="en-US">
	<head>
		<title>CrowdKode Checkout</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<link rel="preconnect" href="https://fonts.googleapis.com">
		<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
		<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@100;200;300;400;500;600;700;800;900&display=swap" rel="stylesheet">
		<link href='//fonts.googleapis.com/css?family=Open+Sans:400,600,700,300' rel='stylesheet' type='text/css'>

		<meta http-equiv="X-UA-Compatible" content="ie=edge" />
		<link rel="apple-touch-icon" href="/assets/logo.png" />

		<style>
			body, html {
				font-family: Montserrat,Helvetica,Verdana,sans-serif;
			}
			a, a:active, a:visited, a:link {
				text-decoration: none;
			}
			h1, h2, h3, h4, h5, h6 {
				font-family: Montserrat,Helvetica,Verdana,sans-serif;
			}
			/*body {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100vh;
			margin: 0;
			}*/

			/*.container {
			display: flex;
			flex-direction: column;
			text-align: center;
			background-color: lightgray;
			max-width: 500px;
			min-height: 15em;
			padding: 20px;
			}*/
			#btn-appl {
				display: inline-block;
				width: var(--apple-pay-button-width, auto);
				/*min-width: 320px;*/
				min-height: 45px;
				height: 45px !important;
			}
			apple-pay-button {
				--apple-pay-button-width: 340px;
				--apple-pay-button-height: 35px;
				--apple-pay-button-border-radius: 5px;
				--apple-pay-button-padding: 5px 0px;
			}
			button, apple-pay-button {
			}
			button.apple-pay-btn.black {
				height: 45px !important;
			}

			.apple-pay-btn-wrapper.buy.en-US, .apple-pay-btn-wrapper {
				min-height: 45px !important;
				height: 45px !important;
			}

			.apple-pay-btn-wrapper .apple-pay-btn {
				background-color: black;
				border-top-style: none;
				border-right-style: none;
				border-bottom-style: none;
				border-left-style: none;
				color: white;
				cursor: pointer;
				font-synthesis-small-caps: none;
				font-synthesis-style: none;
				font-synthesis-weight: none;
				justify-content: center;
				position: relative;
				margin-top: 0px;
				box-sizing: var(--apple-pay-button-box-sizing, content-box);
				/*min-height: 45px !important;
				height:45px !important;*/
				height: calc(var(--apple-pay-button-height, 45px)) !important;
				min-width: var(--apple-pay-button-width-default, 320px) !important;
				width: 100% !important;
				border-top-left-radius: ;
				border-top-right-radius: ;
				border-bottom-right-radius: ;
				border-bottom-left-radius: ;
				padding-top: ;
				padding-right: ;
				padding-bottom: ;
				padding-left: ;
				-webkit-font-smoothing: antialiased;
			}

			.apple-pay-button {
				display: inline-block;
				-webkit-appearance: -apple-pay-button;
				-apple-pay-button-type: donate; /* Use any supported button type. */
				height: 45px !important;
				min-height: 45px !important;
			}
			.apple-pay-button-black {
				-apple-pay-button-style: black;
				height: 45px !important;
				min-height: 45px !important;
			}

			#applepay-container {
				flex-grow: 1;
				/*width:320px !important;
				min-width:320px !important;*/
				max-width: 305px !important;
				height: 45px !important;
				min-height: 45px !important;
				margin-bottom: 15px;
			}

			/* ################################### */
			/*            MOBILE STYLES            */
			/* ################################### */

			/* Portrait tablet to landscape and desktop */
			@media (min-width: 980px) and (max-width: 1024px) {
				.logintext {
					margin-bottom: 7px;
				}
			}

			/* Portrait tablet to landscape and desktop */
			@media (min-width: 768px) and (max-width: 979px) {

			}

			/* Landscape phone to portrait tablet */
			@media (max-width: 767px) {
				.logintext {
					margin-bottom: 7px;
				}
			}

			/* Landscape phones and down */
			@media (max-width: 586px) {
				.spacer {
					padding-top: 56px !important;
				}
				.logintext {
					margin-bottom: 7px;
				}
				.half {
					float: none;
					width: 100%;
					display: block;
					overflow: hidden;
					padding-bottom: 35px;
				}
			}

			/* Landscape phones and down */
			@media (max-width: 480px) {
				.logintext {
					margin-bottom: 7px;
				}
			}

			/* Older phones with super small screens, iPhone SE */
			@media (max-width: 375px) {
				.logintext {
					margin-bottom: 7px;
				}
				#applepay-container {
					flex-grow: 1;
					/*width:320px !important;
					min-width:320px !important;*/
					max-width: 305px !important;
					height: 45px !important;
					min-height: 45px !important;
					margin-bottom: 15px;
				}
				apple-pay-button {
					--apple-pay-button-width: 330px;
					--apple-pay-button-height: 37px;
					--apple-pay-button-border-radius: 5px;
					--apple-pay-button-padding: 5px 0px;
				}
				#btn-appl {
					display: inline-block;
					width: var(--apple-pay-button-width, auto);
					/*min-width: 320px;*/
					min-height: 40px;
					height: 40px !important;
				}

				button.apple-pay-btn.black {
					height: 40px !important;
				}

				.apple-pay-btn-wrapper.buy.en-US, .apple-pay-btn-wrapper {
					min-height: 40px !important;
					height: 40px !important;
				}

				.apple-pay-btn-wrapper .apple-pay-btn {
					height: calc(var(--apple-pay-button-height, 40px)) !important;
				}

				.apple-pay-button {
					height: 40px !important;
					min-height: 40px !important;
				}
				.apple-pay-button-black {
					-apple-pay-button-style: black;
					height: 40px !important;
					min-height: 40px !important;
				}
			}
		</style>

		<!-- Stylesheet file -->
		<link rel="stylesheet" href="css/style.css">

		<!-- PayPal JS SDK -->
		<!--<script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID&currency=USD&buyer-country=US&merchant-id=SUB_MERCHANT_ID&components=applepay"></script>-->
		<!-- THIS IS THE OFFICIAL SCRIPT THAT WORKS -->
		<script src="https://www.paypal.com/sdk/js?client-id=<?php echo PAYPAL_SANDBOX?PAYPAL_SANDBOX_CLIENT_ID:PAYPAL_PROD_CLIENT_ID; ?>&currency=USD&merchant-id=H6MLL7DW7SMQ6&components=buttons,applepay&enable-funding=venmo" data-partner-attribution-id="APPLEPAY"> </script>
		<!-- data-partner-attribution-id="APPLEPAY"  -->
		<script src="https://applepay.cdn-apple.com/jsapi/v1/apple-pay-sdk.js"> </script>
		<script src="app.js"> </script>
	</head>
	<body>

		<!--XMLHttpRequest cannot load https://www.paypal.com/xoplatform/logger/api/logger?disableSetCookie=true due to access control checks.-->

		<div class="container">
			<h1>CrowdKode Checkout (V7)</h1>
			<div class="panel">
				<div class="overlay hidden">
					<div class="overlay-content"><img src="css/loading.gif" alt="Processing..."/></div>
				</div>

				<div class="panel-heading">

					<!--<h3 class="panel-title">Charge <?php echo '$'.$itemPrice; ?> with PayPal</h3>-->

					<!-- Product Info -->
					<!--<p><b>Item Name:</b> <?php echo $itemName; ?></p>-->
					<!--<p><b>Price:</b> <?php echo '$'.$itemPrice.' '.$currency; ?></p>-->

					<p style="margin:0; padding:0 0 10px 0"><b>Checkout Total</b></p>
					Pay: <input type="hiddenx" id="t_amount" value="0.50" style="width:40px;">

					<input type="hiddenx" id="mem_ID" value="sillystats@gmail.com" style="float:right;">
				</div>
				<div class="panel-body">
					<!-- Display status message -->
					<div id="paymentResponse" class="hidden"></div>

					<p id="result-message" class="hidden"
			style="background:#00c808; color:#fff; padding:7px; text-align:center;
				-webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px;
				line-height:22px;">
						<!--Thank you! Your ApplePay payment was successful.-->
					</p>

					<div id="applepay-container"></div>

					<!-- Set up a container element for the button -->
					<div id="paypal-button-container"></div>
				</div>
				<div class="clear"></div>
				<center>
					<a href="javascript:top.frames.location.reload();"
					class="refresh" style="color:#000; font-weight:800; font-size:17px;">
					Refresh</a>
				</center>
				<br />
			</div>
		</div>

		<script>
			paypal.Buttons({
				// Sets up the transaction when a payment button is clicked
				createOrder: (data, actions) => {
					return actions.order.create({
						"purchase_units": [{
								"custom_id": "<?php echo $itemNumber; ?>",
								"description": "<?php echo $itemName; ?>",
								"amount": {
									"currency_code": "<?php echo $currency; ?>",
									"value": <?php echo $itemPrice; ?>,
									"breakdown": {
										"item_total": {  /* Required when including the items array */
											"currency_code": "<?php echo $currency; ?>",
											"value": <?php echo $itemPrice; ?>
										}
									}
								},
								"items": [
									{
										"name": "<?php echo $itemName; ?>", /* Shows within upper-right dropdown during payment approval */
										"description": "<?php echo $itemName; ?>", /* Item details will also be in the completed paypal.com transaction view */
										"unit_amount": {
											"currency_code": "<?php echo $currency; ?>",
											"value": <?php echo $itemPrice; ?>
										},
										"quantity": "1",
										"category": "DIGITAL_GOODS"
									},
								]
							}]
					});
				},
				// Finalize the transaction after payer approval
				onApprove: (data, actions) => {
					return actions.order.capture().then(function(orderData) { //console.log(orderData);
						// Successful capture! For dev/demo purposes:
						//console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
						//const transaction = orderData.purchase_units[0].payments.captures[0]; //console.log(transaction);
						//alert(`Transaction ${transaction.status}: ${transaction.id}\n\nSee console for all available details`);
						// When ready to go live, remove the alert and show a success message within this page. For example:
						// const element = document.getElementById('paypal-button-container');
						// element.innerHTML = '<h3>Thank you for your payment!</h3>';
						// Or go to another URL:  actions.redirect('thank_you.html');

						setProcessing(true);

						var postData = {paypal_order_check: 1, order_id: orderData.id};
						fetch('paypal_checkout_validate.php', {
							method: 'POST',
							headers: {'Accept': 'application/json'},
							body: encodeFormData(postData)
						})
						.then((response) => response.json())
						.then((result) => {
							if (result.status == 1) {
								window.location.href = "payment-status.php?checkout_ref_id="+result.ref_id;
							} else {
								const messageContainer = document.querySelector("#paymentResponse");
								messageContainer.classList.remove("hidden");
								messageContainer.textContent = result.msg;

								setTimeout(function () {
									messageContainer.classList.add("hidden");
									messageText.textContent = "";
								}, 5000);
							}
							setProcessing(false);
						})
						.catch(error => console.log(error));
					});
				}
			}).render('#paypal-button-container');

			const encodeFormData = (data) => {
				var form_data = new FormData();

				for ( var key in data ) {
					form_data.append(key, data[key]);
				}
				return form_data;
			}

			// Show a loader on payment form processing
			const setProcessing = (isProcessing) => {
				if (isProcessing) {
					document.querySelector(".overlay").classList.remove("hidden");
				} else {
					document.querySelector(".overlay").classList.add("hidden");
				}
			}
		</script>
	</body>
</html>