<?php
$root=$_SERVER['DOCUMENT_ROOT'];$wroot=dirname($_SERVER['SCRIPT_NAME']);while((strlen($wroot)>1)&&(!file_exists($root.$wroot.'/main')))$wroot=dirname($wroot);if($wroot=='/')$wroot='';
$froot=$root.$wroot;
class PaypalPaywall{
	function mkdir($dir){if (!file_exists($dir)){$mask=umask(0);mkdir($dir,0777,true);umask($mask);}}
	function approveOrder($requestId,$orderId){
		global $froot;
		$ordraw=file_get_contents("$froot/main/modules/paypalPaywall/orders/$requestId");
		$order=json_decode($ordraw);array_push($order,$orderId);
		$this->mkdir("$froot/main/users/$ouser/orders");
		file_put_contents("$froot/main/users/$ouser/orders/$requestId",json_encode($order));
		$ouser=$order[0];$grains=$order[2];
		$response=$db->query("select * from users where user='$ouser';");
		if (($db->errno===0)&&($response->num_rows!=0)){
			$user=$response->fetch_assoc();$creds=floatVal($user['cred']);$creds+=floatVal($grains);
			$db->query("update users set cred='$creds' where user='$ouser';");
			if ($db->errno===0){
				unlink("$froot/main/modules/paypalPaywall/orders/$requestId");
				$c=curl_init();
				curl_setopt($c,CURLOPT_URL,$this->apiURL."/v2/checkout/orders/$orderId/capture");
				curl_setopt($c,CURLOPT_RETURNTRANSFER,true);
				curl_setopt($c,CURLOPT_HTTPHEADER,["PayPal-Request-Id: $requestId","Authorization: Bearer {$this->accessToken}","Content-Type: application/json"]);
				curl_setopt($c,CURLOPT_POST,true);
				curl_setopt($c,CURLOPT_POSTFIELDS,'{}');
				return curl_exec($c);
			}
		}
		return false;
	}
	function createOrder($requestId,$grains){
		global $froot;
		$total=$grains*$this->AgOzUSD/480;$total=number_format($total,2);
		$rid=explode('-',$requestId);
		$otime=$rid[0];$ouser=$rid[1];
		$order=json_encode([$ouser,$otime,$this->AgOzUSD,$grains,$total]);
		$this->mkdir("$froot/main/modules/paypalPaywall/orders");
		file_put_contents("$froot/main/modules/paypalPaywall/orders/$requestId",$order);
		$c=curl_init();
		curl_setopt($c,CURLOPT_URL,$this->apiURL.'/v2/checkout/orders');
		curl_setopt($c,CURLOPT_RETURNTRANSFER,true);
		curl_setopt($c,CURLOPT_HTTPHEADER,["PayPal-Request-Id: $requestId","Authorization: Bearer {$this->accessToken}","Content-Type: application/json"]);
		curl_setopt($c,CURLOPT_POST,true);
		$json='{"intent":"CAPTURE","purchase_units":[{
			"amount":{"breakdown":{"item_total":{"value":"'.$total.'","currency_code":"USD"}},"value":"'.$total.'","currency_code":"USD"},
			"items":[{"name":"'.$grains.' Grains","description":"'.$grains.'Grains of Auranos.org credit","quantity":"1","unit_amount":{"value":"'.$total.'","currency_code":"USD"}}]
		}]}';
		curl_setopt($c,CURLOPT_POSTFIELDS,$json);
		return curl_exec($c);
	}
	function getAccessToken(){
		$c=curl_init();
		curl_setopt($c,CURLOPT_URL,$this->apiURL.'/v1/oauth2/token');
		curl_setopt($c,CURLOPT_USERPWD,$this->clientId.':'.$this->clientSecret);
		curl_setopt($c,CURLOPT_HTTPHEADER,['Content-Type'=>'application/x-www-form-urlencoded']);
		curl_setopt($c,CURLOPT_POST,true);
		curl_setopt($c,CURLOPT_POSTFIELDS,'grant_type=client_credentials');
		curl_setopt($c,CURLOPT_RETURNTRANSFER,true);
		$response=curl_exec($c);
		$json=json_decode($response,true);
		return $json['access_token'];
	}
	function getAgOzUSD(){
		if ((time()-filemtime(__DIR__.'/AgOzUSD.txt'))>3600*24){
			$url="https://www.xe.com/currencyconverter/convert/?Amount=1&From=XAG&To=USD";
			$ch=curl_init();curl_setopt($ch,CURLOPT_URL,$url);curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);$h=curl_exec($ch);curl_close($ch);
			$h=substr($h,strpos($h,'1.00 Silver Ounce'));$h=substr($h,strpos($h,'">')+2);$h=floatVal(substr($h,0,strpos($h,'<')));
			file_put_contents(__DIR__.'/AgOzUSD.txt',$h);
		}
		else $h=floatVal(file_get_contents(__DIR__.'/grainPriceUSD.txt'));
		return $h;
	}
	function dbConnect(){
		global $froot;
		$db=false;
		if (file_exists("$froot/main/app/config.json")){
			$config=json_decode(file_get_contents("$froot/main/app/config.json"),true);
    		mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);
			try{$db=new mysqli($config['dbHost'],$config['dbUser'],$config['dbPass'],$config['dbName'],$config['dbPort']);}
			catch (Exception $exception){return false;};
			if ($db->connect_errno===0) return $db;
		}
		return $db;
	}
	function __construct(){
		$ppcfg=json_decode(file_get_contents(__DIR__.'/config.json')); if (!$ppcfg) return;
		$this->db=$this->dbConnect(); if (!$this->db) return;
		$this->AgOzUSD=$this->getAgOzUSD(); if (!$this->AgOzUSD) return;
		$this->livemode=$ppcfg->livemode;
		$this->clientId=$this->livemode?$ppcfg->live_clientId:$ppcfg->sbox_clientId;
		$this->clientSecret=$this->livemode?$ppcfg->live_clientSecret:$ppcfg->sbox_clientSecret;
		$this->apiURL=$this->livemode?"https://api-m.paypal.com":"https://api-m.sandbox.paypal.com";
		$this->accessToken=$this->getAccessToken();
		switch($_POST['c']){
			case 'CO':if (isset($_POST['r'])&&isset($_POST['q'])){
				$q=intVal($_POST['q']);
				if($q<100)$q=100;
				echo $this->createOrder($_POST['r'],$q);}break;
			case 'AO':if (isset($_POST['r'])&&isset($_POST['id'])){
				echo $this->approveOrder($_POST['r'],$_POST['id']);}break;
		}
	}
}
if (isset($_POST['c'])&&(($_POST['c']=='CO')||($_POST['c']=='AO'))) $paypalPaywall=new PaypalPaywall();
?>
