<?php

class Model_Cms_Stats extends Pampa_Db_Table {

  protected $_name = "cms_stats";
  protected $startDate;
  protected $endDate;

  /**
   * @var apiClient
   */
  protected $google;


  public function init(){
    require_once 'Google/apiClient.php';
    require_once 'contrib/apiAnalyticsService.php';

    $this->google = new apiClient();
    $this->google->setApplicationName('Pampa Analytics');

    // Visit //code.google.com/apis/console?api=analytics to generate your
    // client id, client secret, and to register your redirect uri.
    $siteConfig = Zend_Registry::get("_site_config");

    $this->google->setClientId($siteConfig->google_client_id);
    $this->google->setClientSecret($siteConfig->google_client_secret);
    $this->google->setRedirectUri(BASE_URL."cms/cms_stats");
    $this->google->setDeveloperKey($siteConfig->google_developer_key);
    $this->google->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));

    // Magic. Returns objects from the Analytics Service instead of associative arrays.
    $this->google->setUseObjects(true);
    parent::init();
  }

  private function getLastDay($month = '', $year = '') {
    if (empty($month)) {
      $month = date('m');
    }
    if (empty($year)) {
      $year = date('Y');
    }
    $result = strtotime("{$year}-{$month}-01");
    $result = strtotime('-1 second', strtotime('+1 month', $result));
    return date('Y-m-d', $result);
  }

  public function auth($code)
  {
    $this->google->authenticate();
    $_SESSION['token'] = $this->google->getAccessToken();
  }
  public function teste($month = null, $year = null)
  {
    $this->startDate = ((is_null($month))? date('Y-m-01'): $year.'-'.$month.'-01');
    $this->endDate = ((is_null($month))? date('Y-m-t'): $this->getLastDay($month, $year));


    if (isset($_SESSION['token'])) {
      $this->google->setAccessToken($_SESSION['token']);
    }

    if (!$this->google->getAccessToken())
    {
      $authUrl = $this->google->createAuthUrl();
      return $authUrl;
      //print "<a class='login' href='$authUrl'>Connect Me!</a>";

    } else {
      $analytics = new apiAnalyticsService($this->google);
      return $this->_runMainDemo($analytics);
    }

  }

  private function _getFirstprofileId(&$analytics) {
    $accounts = $analytics->management_accounts->listManagementAccounts();

    if (count($accounts->getItems()) > 0) {
      $items = $accounts->getItems();
      $firstAccountId = $items[0]->getId();

      $webproperties = $analytics->management_webproperties
        ->listManagementWebproperties($firstAccountId);

      if (count($webproperties->getItems()) > 0) {
        $items = $webproperties->getItems();
        $firstWebpropertyId = $items[0]->getId();

        $profiles = $analytics->management_profiles
          ->listManagementProfiles($firstAccountId, $firstWebpropertyId);

        if (count($profiles->getItems()) > 0) {
          $items = $profiles->getItems();
          return $items[0]->getId();

        } else {
          throw new Exception('No profiles found for this user.');
        }
      } else {
        throw new Exception('No webproperties found for this user.');
      }
    } else {
      throw new Exception('No accounts found for this user.');
    }
  }

  private function _getResults(&$analytics, $profileId) {
//$  ids, $start_date, $end_date, $metrics, $optParams = array()
    return $analytics->data_ga->get(
      'ga:' . $profileId, // ids
      $this->startDate, // start date
      $this->endDate, // end date
      'ga:visits,ga:pageviews', // metrics
      array(
        'dimensions'=>'ga:day,ga:visitorType',
        'sort'=>'ga:day') // params
    );
  }

  private function _runMainDemo(&$analytics) {
    $return = new stdClass();
    $return->error = FALSE;
    $return->message = '';

    try {
      // Step 2. Get the user's first profile ID.
      $profileId = $this->_getFirstProfileId($analytics);

      if (isset($profileId)) {

        // Step 3. Query the Core Reporting API.
        $return = $this->_getResults($analytics, $profileId);
      }

    } catch (apiServiceException $e) {
      $return->error = TRUE;
      $return->message = 'There was an API error : ' . $e->getCode() . ' : ' . $e->getMessage();
    }
    catch (Exception $e) {
      $return->error = TRUE;
      $return->message = print 'There wan a general error : ' . $e->getMessage();
    }
    return $return;
  }


  public function adminList($filters) {
    // start the select
    $select = $this->select();

    $zendPaginator = Zend_Paginator::factory($select);
    $zendPaginator->setCurrentPageNumber($filters['p']);
    $zendPaginator->setItemCountPerPage($filters['t']);

    return $zendPaginator;
  }

}