{% extends 'store/Main.html' %}
{% load static %}
{% block content %}
     <div class="row">
		<div class="col-lg-6">
			<div class="box-element" id="form-wrapper">
				<form id="form">
				
					<div id="user-info">
						<div class="form-field">
							<input required class="form-control" type="text" name="name" placeholder="Name..">
						</div>
						<div class="form-field">
							<input required class="form-control" type="email" name="email" placeholder="Email..">
						</div>
					</div>
					
					 

					<hr>
					<input id="form-button" class="btn btn-success btn-block" type="submit" value="Continue">
				</form>
			</div>

			<br>
			<div class="box-element hidden" id="payment-info">
				<small>Paypal Options</small>
				  <div id="paypal-button-container"></div>
				<!-- <button id="make-payment">Make payment</button> -->
			</div>
			
		</div>

		<div class="col-lg-6">
			<div class="box-element">
				<a  class="btn btn-outline-dark" href="{% url 'cart' %}">&#x2190; Back to Cart</a>
				<hr>
				<h3>Order Summary</h3>
				<hr>
				{% for item in items %}
				<div class="cart-row">
					<div style="flex:2"><img class="row-image" src="{{item.product.imageURL}}"></div>
					<div style="flex:2"><p>{{item.product.name}}</p></div>
					<div style="flex:1"><p>${{item.product.price|floatformat:2}}</p></div>
					<div style="flex:1"><p>x{{item.quantity}}</p></div>
				</div>
				{% endfor %}
				<h5>Items:   {{order.get_cart_items}}</h5>
				<h5>Total:   ${{order.get_cart_total|floatformat:2}}</h5>
			</div>
		</div>
	</div>

	<script src="https://www.paypal.com/sdk/js?client-id=AYb_sqnf4YfwkdwcBUYcwSW1CkU6bxUwFf3VIYFDhltrMZptZIdexhYQa9WYypqUJ5BsBYAnmmmYpYRb&currency=USD"></script>

    <script>

    	var total = '{{order.get_cart_total|floatformat:2}}';
        // Render the PayPal button into #paypal-button-container
        paypal.Buttons({

        	style: {
                color:  'blue',
                shape:  'rect',
            },

            // Set up the transaction
            createOrder: function(data, actions) {
                return actions.order.create({
                    purchase_units: [{
                        amount: {
                            value: parseFloat(total).toFixed(2)
                        }
                    }]
                });
            },

            // Finalize the transaction
            onApprove: function(data, actions) {
                return actions.order.capture().then(function(details) {
                    // Show a success message to the buyer
                    // alert('Transaction completed by ' + details.payer.name.given_name + '!');
                    submitFormData()
                    // var buyer = details.payer.name.given_name;
                });
            }


        }).render('#paypal-button-container');
    </script>


	<script type="text/javascript">
		var shipping = '{{order.shipping}}'
		

		 

		if (user != 'AnonymousUser'){
		 	document.getElementById('user-info').innerHTML = ''
		 }

		if (shipping == 'False' && user != 'AnonymousUser'){
			//Hide entire form if user is logged in and shipping is false
				document.getElementById('form-wrapper').classList.add("hidden");
				//Show payment if logged in user wants to buy an item that does not require shipping
			    document.getElementById('payment-info').classList.remove("hidden");
		}

		var form = document.getElementById('form')

		form.addEventListener('submit', function(e){
	    	e.preventDefault()
	    	console.log('Form Submitted...')
	    	document.getElementById('form-button').classList.add("hidden");
	    	document.getElementById('payment-info').classList.remove("hidden");
	    })

	   /* document.getElementById('make-payment').addEventListener('click', function(e){
	    	submitFormData()
	    })  */

	    function submitFormData(){
	    	console.log('Payment button clicked')

	    	var userFormData = {
				'name':null,
				'email':null,
				'total':total,
			}

			 

			 

	    	if (user == 'AnonymousUser'){
	    		userFormData.name = form.name.value
	    		userFormData.email = form.email.value
	    	}

	    	console.log('User Info:', userFormData)

	    	var url = "/process_order/"
	    	fetch(url, {
	    		method:'POST',
	    		headers:{
	    			'Content-Type':'applicaiton/json',
	    			'X-CSRFToken':csrftoken,
	    		}, 
	    		body:JSON.stringify({'form':userFormData}),
	    		
	    	})
	    	.then((response) => response.json())
	    	.then((data) => {
				 console.log('Success:', data);
				 alert('Transaction completed by ' + userFormData.name + '!');

				cart = {}
				document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/" 
				window.location.href = "{% url 'process_QR' %}"

				})
	    }
	</script>
{% endblock content %}


 
