<?php

include_once('/home/www/share/ksdapi/var/keys/google_access_token.inc');

/*
$msisdn = '85293538820';

$operator = 'taiwanmobile';
$classname = $operator.'api';

$api = new $classname();

if ($api) {
    $ret = $api->chkSub($msisdn,$rawreturn);
    print_r($rawreturn);
}
*/

class GoogleApi
{
    var $debug = false;
    var $error_str;

    var $env = 'production';

    //var $STATUS_API = 'https://www.googleapis.com/androidpublisher/v1/applications/<packageName>/subscriptions/<subscriptionId>/purchases/<token>';
    var $STATUS_API = 'https://www.googleapis.com/androidpublisher/v1/applications';
    //var $packageName = 'com.koreastardaily.android.billingsample';
    var $packageName = 'com.koreastardaily.apps.android.media';
    var $subscriptionId = 'monthly_subscription';


    public function GoogleApi ($env='production') {
	$this->env = $env;

	return true;
    }

    public function showError() {
	echo $this->error_str;
    }

    public function chkSub($token,&$rawreturn) {

	global $ACCESS_TOKEN;

	// for development
	$subid = isset($_REQUEST['subid']) ? $_REQUEST['subid'] : $this->subscriptionId;

	if ($token) {
	    $url = $this->STATUS_API . '/' . $this->packageName . '/subscriptions/' . $subid . '/purchases/' . $token . '?access_token=' . $ACCESS_TOKEN;
#echo $url;
	    $ctx = stream_context_create( array( 'http' => array('timeout' => 10))); // 10 sec timeout
	    $rawreturn = file_get_contents($url, 0, $ctx);
#var_dump($http_response_header);
	    $ret = json_decode($rawreturn);
	    if ($this->debug) print_r($ret);

	    if (isset($ret->validUntilTimestampMsec) && ($ret->validUntilTimestampMsec)) {
		return round($ret->validUntilTimestampMsec/1000);
	    } elseif (strpos($http_response_header[0],'503') !== false ) { // temp solution to fix google api 503 issue
		return time() + 15 * 60;
	    } else {
		$this->error_str .=  'ERROR: from api' . "\n";
	    }
	} else {
	    $this->error_str .= "missing parameters\n";
	}

	return false;
    }
}

?>
