<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);

$root = realpath(dirname(dirname(__FILE__)));
$library = "$root/library";

$path = array($library, get_include_path());
set_include_path(implode(PATH_SEPARATOR, $path));

require_once('vendor/autoload.php');

/*
 * API to check Android/iOS Subscription Validation
 */
$invalid_request = true;
$android_output = '';
$ios_output = '';
$error_reponse = array('response' => (object) array(), 'error' => array('status' => 'failure', 'message' => 'Request could not be executed properly'));
$success_reponse = array();

if (isset($_POST['request_token']) && !empty($_POST['request_token'])) {
    //API to check Android Subscription Validation
    if (isset($_POST['subscription_platform']) && !empty($_POST['subscription_platform']) && $_POST['subscription_platform'] == 'Android') {
	if (isset($_POST['purchase_token']) && !empty($_POST['purchase_token']) && isset($_POST['purchase_sku']) && !empty($_POST['purchase_sku'])) {
	    //If Request is valid then set variable to false
            $invalid_request = false;
 
	    // google authencation 
	    $applicationName = 'Barcode To Sheet';//Constant
	    $scope = ['https://www.googleapis.com/auth/androidpublisher']; //Constant
	    $configLocation = 'client_key.json'; //Constant

	    // receipt data
	    $packageName = 'com.vel.barcodetosheet'; //Constant
	    $productId = $_POST['purchase_sku'];
	    $purchaseToken = $_POST['purchase_token'];

	    $client = new \Google_Client();
	    $client->setApplicationName($applicationName);
	    $client->setAuthConfig($configLocation);
	    $client->setScopes([\Google_Service_AndroidPublisher::ANDROIDPUBLISHER]);

	    $validator = new ReceiptValidator\GooglePlay\Validator(new \Google_Service_AndroidPublisher($client));

	    $expirationTime = '';
	    try {
	        $response = $validator->setPackageName($packageName)->setProductId($productId)->setPurchaseToken($purchaseToken)->validateSubscription();
	        $reader = new ReceiptValidator\GooglePlay\SubscriptionResponse($response);
	        $expirationTime = !empty($reader->getExpiryTimeMillis()) ? $reader->getExpiryTimeMillis()/1000 : '';
	        $currentTime = time();

	        if (!empty($expirationTime) && $expirationTime > $currentTime) {
		    $android_output = 'true';
	        } else {
		    $android_output = 'false';
		}
	    } catch (Exception $e) {
	        $android_output = 'false';
	    }

	    //Response
	    if (isset($android_output) && !empty($android_output)) {
	        $success_response = array('response' => array('subscription_status' => $android_output), 'error' => (object) array());
	        echo json_encode($success_response);
       	        die;
	    }
    	}
    } 
    //API to check iOS Subscription Validation
    else if (isset($_POST['subscription_platform']) && !empty($_POST['subscription_platform']) && $_POST['subscription_platform'] == 'iOS') {
	if (isset($_POST['purchase_token']) && !empty($_POST['purchase_token'])) {
 	    //If Request is valid then set variable to false
            $invalid_request = false;
            
        //if(isset($_POST['sandbox']) && $_POST['sandbox'] == 'true') {
        $validator = new ReceiptValidator\iTunes\Validator(ReceiptValidator\iTunes\Validator::ENDPOINT_SANDBOX); // Or iTunesValidator::ENDPOINT_SANDBOX if sandbox testing
        //} else {
        //    $validator = new ReceiptValidator\iTunes\Validator(ReceiptValidator\iTunes\Validator::ENDPOINT_PRODUCTION); // Or iTunesValidator::ENDPOINT_SANDBOX if sandbox testing
        //}
	    $receiptBase64Data = $_POST['purchase_token']; //Receipt Data encoded in Base64

	    try {
	  	//$response = $validator->setReceiptData($receiptBase64Data)->validate();
	  	$sharedSecret = 'a8ab885c7e6f470ea31b91aac0e06795'; // Generated in iTunes Connect's In-App Purchase menu   //Constant
  	  	$response = $validator->setSharedSecret($sharedSecret)->setReceiptData($receiptBase64Data)->validate(); // use setSharedSecret() if for recurring subscriptions
		if (!empty($response->getLatestReceiptInfo())) {
		    foreach ($response->getLatestReceiptInfo() as $purchase) {
	      	        $expirationTime = !empty($purchase->getExpiresDate()) ? strtotime($purchase->getExpiresDate()) : '';
		        $currentTime = time();

		        if (!empty($expirationTime) && $expirationTime > $currentTime) {
			    $ios_output = 'true';
			} else {
			    $ios_output = 'false';
			}
		        break;
		    }
		} else {
		    $ios_output = 'false';
		}
    	    } catch (Exception $e) {
  	        $ios_output = 'false';
            }
    	}
	//Response
	if (isset($ios_output) && !empty($ios_output)) {
            $success_response = array('response' => array('subscription_status' => $ios_output), 'error' => (object) array());
	    echo json_encode($success_response);
    	    die;
	}
    }
}

//If Invalid Request or Parameters then send error response
if ($invalid_request) {
    echo json_encode($error_reponse);
    die;
}

die;
?>
