<?

#echo $argv[1];


if(isset($argv[1])) {
	$webpropertyID = $argv[1];
} else {
	die();
}

/**
 * 1.Create and Execute a Real Time Report
 * An application can request real-time data by calling the get method on the Analytics service object.
 * The method requires an ids parameter which specifies from which view (profile) to retrieve data.
 * For example, the following code requests real-time data for view (profile) ID 56789.
 */

include('functions.php');

list($client_id,$client_secret,$token,$refreshtoken,$created,$viewID) = get_analytic_site_credentials($webpropertyID);

    require_once 'google-api-php-client-master/src/Google/autoload.php';
    session_start(); 

    // ********************************************************  //
    // Get these values from https://console.developers.google.com
    // Be sure to enable the Analytics API
    // ********************************************************    //
#    $client_id = '167087527944-59c54f48js8ifgolqolbqlddf187qrof.apps.googleusercontent.com';
#    $client_secret = 'IwkjqidCuKdspRGme_dPBBSX';
    $redirect_uri = 'http://webdev.fluffyduck.com.au/cdata/googleapitest.php';


    $client = new Google_Client();
    $client->setApplicationName("Client_Library_Examples");
    $client->setClientId($client_id);
    $client->setClientSecret($client_secret);
    $client->setRedirectUri($redirect_uri);
    $client->setScopes(array('https://www.googleapis.com/auth/analytics'));
    $client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
    $client->setAccessType('offline');   // Gets us our refreshtoken
    $client->setApprovalPrompt('force');


	// Check if token has expired or not
	if($client->isAccessTokenExpired()) {

		// if yes we need to update token with the refreshtoken var
		$client->refreshToken($refreshtoken);
		$newtoken = $client->getAccessToken();
#		print_r($newtoken);
#		echo '<br>Refreshed<br>';

	} else {

		// if token hasnt expired use previous token
		$client->setAccessToken($token);

	}

/*
    //For loging out.
    if ($_GET['logout'] == "1") {
        unset($_SESSION['token']);
       }


    // Step 2: The user accepted your access now you need to exchange it.
    if (isset($_GET['code'])) {

        $client->authenticate($_GET['code']);
        $_SESSION['token'] = $client->getAccessToken();
        $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
        header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
    }

    // Step 1:  The user has not authenticated we give them a link to login    
    if (!$client->getAccessToken() && !isset($_SESSION['token'])) {

        $authUrl = $client->createAuthUrl();

        print "<a class='login' href='$authUrl'>Connect Me!</a>";
        }


    // Step 3: We have access we can now create our service
    if (isset($_SESSION['token'])) {
        print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";

*/

        $analytics = new Google_Service_Analytics($client);


/****
START getproperties -
Following segment of code displays all the web properties linked to the analytics account thats been connected too
ViewID is the important element to use for retrieving further information.

This data shouldnt be required again, unless we need to mass import a bunch of new sites
*****/
/*
        // request user accounts
        $accounts = $analytics->management_accountSummaries->listManagementAccountSummaries();


        foreach ($accounts->getItems() as $item) {

		if($item['id'] != '58063757') { continue; }

                echo "<b>Account:</b> ",$item['name'], "  " , $item['id'], "<br /> \n";

                foreach($item->getWebProperties() as $wp) {
                        echo '-----<b>WebProperty:</b> ' ,$wp['name'], "  " , $wp['id'], "<br /> \n";
                        $views = $wp->getProfiles();
                        if (!is_null($views)) {
                                // note sometimes a web property does not have a profile / view

                                foreach($wp->getProfiles() as $view) {

                                        echo '----------<b>View:</b> ' ,$view['name'], "  " , $view['id'], "<br /> \n";
#echo "INSERT INTO webproperty (accountID,webname,webID,view,viewID) VALUES ('".$item['id']."','".$wp['name']."','".$wp['id']."','".$view['name']."','".$view['id']."');<br>";

                                }  // closes profile
                        }
                } // Closes web property

        } // closes account summaries
*/

/*****
END getproperties -
*****/

$optParams = array(
    'dimensions' => 'rt:medium');


// Cycle through sites enabled for recording and retrieve data
try {

	$ga = "ga:".$viewID;

  $results = $analytics->data_realtime->get(
      $ga,
      'rt:activeUsers',
      $optParams);

#  printReportInfo($results);
#  printQueryInfo($results);
#  printProfileInfo($results);
#  printColumnHeaders($results);
#  printDataTable($results);
#	printTotalsForAllResults($results);

##
 getActiveUsers($results);
##

  // Success. 
} catch (apiServiceException $e) {
  // Handle API service exceptions.
  $error = $e->getMessage();
}

#printRealtimeReport($results);
/**
 * 2. Print out the Real-Time Data
 * The components of the report can be printed out as follows:
 */

function printRealtimeReport($results) {
#  printReportInfo($results);
#  printQueryInfo($results);
#  printProfileInfo($results);
#  printColumnHeaders($results);
#  printDataTable($results);
  printTotalsForAllResults($results);
}

function printDataTable(&$results) {
  if (count($results->getRows()) > 0) {
    $table .= '<table>';

    // Print headers.
    $table .= '<tr>';

    foreach ($results->getColumnHeaders() as $header) {
      $table .= '<th>' . $header->name . '</th>';
    }
    $table .= '</tr>';

    // Print table rows.
    foreach ($results->getRows() as $row) {
      $table .= '<tr>';
        foreach ($row as $cell) {
          $table .= '<td>'
                 . htmlspecialchars($cell, ENT_NOQUOTES)
                 . '</td>';
        }
      $table .= '</tr>';
    }
    $table .= '</table>';

  } else {
    $table .= '<p>No Results Found.</p>';
  }
  print $table;
}

function printColumnHeaders(&$results) {
  $html = '';
  $headers = $results->getColumnHeaders();

  foreach ($headers as $header) {
    $html .= <<<HTML
<pre>
Column Name       = {$header->getName()}
Column Type       = {$header->getColumnType()}
Column Data Type  = {$header->getDataType()}
</pre>
HTML;
  }
  print $html;
}

function printQueryInfo(&$results) {
  $query = $results->getQuery();
  $html = <<<HTML
<pre>
Ids         = {$query->getIds()}
Metrics     = {$query->getMetrics()}
Dimensions  = {$query->getDimensions()}
Sort        = {$query->getSort()}
Filters     = {$query->getFilters()}
</pre>
HTML;

  print $html;
}

function printProfileInfo(&$results) {
  $profileInfo = $results->getProfileInfo();

  $html = <<<HTML
<pre>
Account ID               = {$profileInfo->getAccountId()}
Web Property ID          = {$profileInfo->getWebPropertyId()}
Internal Web Property ID = {$profileInfo->getInternalWebPropertyId()}
Profile ID               = {$profileInfo->getProfileId()}
Profile Name             = {$profileInfo->getProfileName()}
Table ID                 = {$profileInfo->getTableId()}
</pre>
HTML;

  print $html;
}

function printReportInfo(&$results) {
  $html = <<<HTML
  <pre>
Kind                  = {$results->getKind()}
ID                    = {$results->getId()}
Self Link             = {$results->getSelfLink()}
Total Results         = {$results->getTotalResults()}
</pre>
HTML;

  print $html;
}

function printTotalsForAllResults(&$results) {
  $totals = $results->getTotalsForAllResults();

  $profileInfo = $results->getProfileInfo();

  $html .= "<table border=1><tr><td><b>".$profileInfo->getProfileId()."</b></td>";
  foreach ($totals as $metricName => $metricTotal) {
    $html .= "<td>$metricName</td>";
    $html .= "<td>$metricTotal</td></tr></table><br><br>";
  }

  print $html;
}

/***
	Get activeUsers + record activeUsers to DB
***/
function getActiveUsers(&$results) {

	$totals = $results->getTotalsForAllResults();
	$profileInfo = $results->getProfileInfo();

	$viewID = $profileInfo->getProfileId();
	$users = $totals['rt:activeUsers'];	

#print_r($users."\n");
	record_activeusers($viewID,$users);
#	threshold_monitoring($viewID);
}


?>
