class PaypalPaywall{
	onApprove=(data,actions)=>{
		var form=new FormData();form.append('c','AO');form.append('r',this.rid);form.append('id',data.orderID);
		return fetch(this.pproot+'/PaypalPaywall.php',{method:'post',body:form})
		.then(function(res){return res.json();})
		.then(function(orderData){window.location.reload();});
	}
	createOrder=(data,actions)=>{
//?c=CO&r=1753978183104-admin&q=undefined
		this.rid=Date.now()+'-'+this.user;
console.log('creating order:'+this.rid);
		var form=new FormData();form.append('c','CO');form.append('r',this.rid);form.append('q',this.total);
		return fetch(this.pproot+'/PaypalPaywall.php',{method:'post',body:form})
		.then(function(res){return res.json();})
		.then(function(orderData){return orderData.id;});
	}
	renderPaypalButtons=()=>{
		this.goldenButton.innerHTML='Opening Paypal...';
		var ppscript=document.createElement('script');
		ppscript.onload=()=>{
			this.goldenButton.remove();
			paypal.Buttons({createOrder:this.createOrder,onApprove:this.onApprove,style:{disableMaxWidth:true}}).render('#'+this.elid);
		}
		document.head.appendChild(ppscript);ppscript.src="https://www.paypal.com/sdk/js?client-id="+this.clientId+"&currency=USD";
	}
	setTotal(){
		this.total=(this.AgOzUSD/480)*this.quant;this.showTotal.innerHTML='$'+this.total.toFixed(2)+' USD';
	}
	create(){
		this.goldenButton=document.createElement('button');this.goldenButton.className='gold';this.goldenButton.innerHTML='Buy Credit';
			this.goldenButton.onclick=()=>{this.renderPaypalButtons();};
		this.showTotal=document.createElement('h5');
		this.showQuant=document.createElement('input');this.showQuant.type='number';this.showQuant.value=this.quant;this.showQuant.min=50;this.showQuant.step=50;
			this.showQuant.onchange=()=>{this.quant=this.showQuant.value;this.setTotal();};
		this.paypalContainer=document.createElement('div');this.paypalContainer.id='paypal-button-container';
		this.paypalContainer.append(this.goldenButton);
		this.el.append(this.showTotal);
		this.el.append(this.showQuant);
		this.el.append(this.paypalContainer);
	}
	initialise(){
		fetch(this.wroot+'/main/modules/paypalPaywall/AgOzUSD.txt').then(response=>response.text()).then(text=>{
			this.AgOzUSD=parseFloat(text);
			this.quant=100;
			this.create();
			this.setTotal();
		});
	}
	constructor(elid,wroot,user,clientId){
		this.elid=elid;this.wroot=wroot;this.user=user;this.clientId=clientId;
		this.el=document.getElementById(elid);this.pproot=this.wroot+'/main/modules/paypalPaywall';
		this.initialise();
	}
}


