<?php
/*
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Main demo class to illustrate how to access all the values returned by
 * the Core Reporting API using the Google API PHP client library. The demo
 * both queries the API and returns the results as an HTML string.
 *
 * Note: The apiAnalyticsService parameter in the constructor accepts requires
 * an apiClient object to be instantiated. This all happens outside of this
 * class. This client must be configured to $apiClient->setUseObjects(true);
 * so that the library returns an object representation of the API response
 * instead of the default representation of associative arrays.
 * @author Nick Mihailovski <api.nickm@gmail.com>
 */
class CoreReportingApiReference {

  /** @var apiAnalyticsService $analytics */
  private $analytics;

  /**
   * The Url of the main controller. Used to properly handle
   * redirects and strip the URL of additional authorization
   * parameters.
   * @var string $controllerUrl
   */
  private $controllerUrl;

  /** @var string $error */
  private $error = null;

  /**
   * Constructor.
   * @param apiAnalyticsService $analytics The analytics service object to make
   *     requests to the API.
   * @param string $controllerUrl The Url for the main controller.
   */
  function __construct(&$anlaytics, $controllerUrl) {
    $this->analytics = $anlaytics;
    $this->controllerUrl;
  }


  /**
   * Returns a HTML string representation of all the data in this demo.
   * This method first queries the Core Reporting API with the provided
   * profiled ID. Then it formats and returns all the results as a string.
   * If any API errors occur, they are caught and set in $this->error.
   * @param string $tableId The value of the ids parameter in the
   *     Core Reporting API. This is the ga namespaced profile ID. It has the
   *     format of ga:xxxx where xxxx is the profile ID. You can get this
   *     value from the Management API. See the helloAnalytics.php example
   *     for details.
   * @return string The formatted results from the API.
   */
  function getHtmlOutput($tableId = null, $desde = null,$hasta = null,$limit = null) {

    if (isset($tableId)) {
      try {
        $results = $this->queryCoreReportingApi($tableId,$desde,$hasta,$limit);
        $output .= $this->getFormattedResults($results);

      } catch (Google_ServiceException $e) {
        $this->error = $e->getMessage();
      }
    }
    return $output;
  }

  /**
   * Queries the Core Reporting API for the top 25 organic search terms
   * ordered by visits. Because the table id comes from the query parameter
   * it needs to be URI decoded.
   * @param string $tableId The value of the ids parameter in the
   *     Core Reporting API. This is the ga namespaced profile ID. It has the
   *     format of ga:xxxx where xxxx is the profile ID. You can get this
   *     value from the Management API. See the helloAnalytics.php example
   *     for details.
   * @return GaData The results from the Core Reporting API.
   */
  private function queryCoreReportingApi($tableId,$desde,$hasta,$limit) {

    $optParams = array(
        'dimensions' => 'ga:exitPagePath',
        'metrics' => 'ga:visits,ga:timeOnSite',
        'sort' => '-ga:visits',
        'filters' => 'ga:medium==organic',
        'max-results' => $limit);

    $desdenew = strtotime($desde);
    $hastanew = strtotime($hasta);
    
    return $this->analytics->data_ga->get(
        urldecode($tableId),
        date( 'Y-m-d' , $desdenew ),
        date( 'Y-m-d' , $hastanew ),
        'ga:visits',
        $optParams);
  }

  /**
   * Returns the results from the API as a HTML formatted string.
   * @param GaData $results The results from the Core Reporting API.
   * @return string The formatted results.
   */
  private function getFormattedResults(&$results) {
    return implode('', array($this->getRows($results)));
  }

  private function getRows($results) {
    $table = '<h1>' . __('paginas mas visitadas', 'CuadroDeMando') . '</h1>';

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

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

      foreach ($results->getColumnHeaders() as $header) {
          switch( $header->getName() ) {
        		case 'ga:exitPagePath':
        			$table .=  '<th>' . __('url', 'CuadroDeMando') . '</th>';
        		break;
                case 'ga:visits':
                        $table .=  '<th>' . __('n visitas', 'CuadroDeMando') . '</th>';
                break;
                case 'ga:timeOnSite':
                        $table .=  '<th>' . __('tiempo medio de visitas', 'CuadroDeMando') . '</th>';
                break;
        	}
      }
      $table .= '</tr>';

      // Print table rows.
      foreach ($results->getRows() as $row) {
        $table .= '<tr>';
        $table .= '<td>' . htmlspecialchars($row[0], ENT_NOQUOTES) . '</td>';
        $table .= '<td>' . htmlspecialchars($row[1], ENT_NOQUOTES) . '</td>';
        
        $total_seconds = ($row[2] / $row[1]);
        $horas              = floor ( $total_seconds / 3600 );
        $minutes            = ( ( $total_seconds / 60 ) % 60 );
        $seconds            = ( $total_seconds % 60 );
        
        $time['horas']      = str_pad( $horas, 2, "0", STR_PAD_LEFT );
        $time['minutes']    = str_pad( $minutes, 2, "0", STR_PAD_LEFT );
        $time['seconds']    = str_pad( $seconds, 2, "0", STR_PAD_LEFT );
        
        $table .= '<td>' . implode( ':', $time ) . '</td>';
        
        $table .= '</tr>';
      }
      $table .= '</table>';

    } else {
      $table .= '<p>No results found.</p>';
    }

    return $table;
  }

 /**
  * @return string Any error that occurred.
  */
  function getError() {
    return $this->error;
  }
}

