<?php

class BaseReportsController extends AppController {

	/** @inheritdoc No model. */
	public $uses = false;

	/** @inheritdoc */
	public $components = [ 'Api' ];

	# ~ Return results from Google analytics API  - - - - - - - - - - - - - - - - - #
	public function googleAnalytics($period = '1month') {

		# Get configuration
		$refreshToken = Configure::read('Website.google_api_refresh_token');
		$tableId = Configure::read('Website.google_api_table_id');

		# Read session for access token
		$access_token = CakeSession::read('access_token');
		$start_date = date('Y-m-d', strtotime('-' . $period));
		$end_date = date('Y-m-d');

		# Get access token for the first time on the page
		if (is_null($access_token)) {
			$token = getAccessToken(GA_CLIENT_ID, GA_CLIENT_SECRET, $refreshToken);
			$token = json_decode($token, true);
			$access_token = $token['access_token'];

			CakeSession::write('access_token', $access_token);
		}

		# Get results from google
		$result = curl("https://www.googleapis.com/analytics/v3/data/ga?access_token={$access_token}&ids={$tableId}&start-date={$start_date}&end-date={$end_date}&dimensions=ga:date&metrics=ga:users");
		$result = json_decode($result, true);

		# Get new access token if previous is expired
		if (!empty($result['error']['code'])) {

			$token = getAccessToken(GA_CLIENT_ID, GA_CLIENT_SECRET, $refreshToken);
			$token = json_decode($token, true);
			$access_token = $token['access_token'];

			CakeSession::write('access_token', $access_token);

			$result = curl("https://www.googleapis.com/analytics/v3/data/ga?access_token={$access_token}&ids={$tableId}&start-date={$start_date}&end-date={$end_date}&dimensions=ga:date&metrics=ga:users");
			$result = json_decode($result, true);
		}

		# Set the proper date
		$data = $result['rows'];
		foreach ($data as $i => $item) {
			$data[$i][0] = date('d.m.', strtotime($data[$i][0]));
			$data[$i][1] = (int) $data[$i][1];
		}

		# Output JSON
		$this->jsonWithHeader($result['profileInfo']['profileName'], [ 'Visitors' ], $data);
	}

	# ~ Return results for api reports - - - - - - - - - - - - - - - - - - - - - - #
	public function api($period = '1month', $group = null) {
		$period = $this->getPeriod($period);
		$result = [];
		$colors = [];
		$map = [];

		switch ($group) {
			case 'platform':
				$map = [ 'android' => 'Android', 'ios' => 'iOS', 'win' => 'Windows', 'web' => 'Website' ];
				$colors = [ 'android' => '#3c9749', 'ios' => '#9CA0A3', 'win' => '#2E8DEF', 'web' => '#B38ACD' ];
				break;

			case 'locale':
				$languages = Configure::read('Config.Languages');
				foreach ($languages as $locale => $language) {
					$map[$locale] = $language['Language']['title'];
					$colors[$locale] = !empty($language['Language']['color']) ? '#' . $language['Language']['color'] : null;
				}
				break;
		}

		# Set the group
		$field = $group ? $group : 'id';
		$group = $group ? 'date, ' . $group : 'date';

		# Get data for specific period and group
		$statsApis = ClassRegistry::init('StatsApi')->find('all', [
			'cache'      => false,
			'fields'     => [ 'SUM(count) as count', $field, 'date' ],
			'conditions' => [
				'platform NOT' => null,
				'StatsApi.date BETWEEN CURDATE() - INTERVAL ' . $period . ' AND CURDATE()' ],
			'group'      => $group,
			'order'      => 'date ASC'
		]);

		# Define empty set
		$count = __('Count');
		$columns = $field != 'id' ? array_unique(Set::extract("/StatsApi/{$field}", $statsApis)) : [ $field != 'id' ? $field : $count ];
		$pointer = strtotime("yesterday - {$period}");
		while (($pointer += DAY) < strtotime('today')) {
			foreach ($columns as $key) {
				$result[date('Y-m-d', $pointer)][$key] = 0;
			}
		}

		# Iterate over statistics
		foreach ($statsApis as $statsApi) {
			if (isset($result[$statsApi['StatsApi']['date']])) {
				$name = $field != 'id' ? $statsApi['StatsApi'][$field] : $count;
				$result[$statsApi['StatsApi']['date']][$name] = (int) $statsApi[0]['count'];
			}
		}

		# Pack result
		$data = [];
		foreach ($result as $date => $values) {
			$data[] = array_values(array_merge([ date('d.m.', strtotime($date)) ], $values));
		}

		# Output JSON
		$this->jsonWithHeader(null, $columns, $data, $map, $colors);
	}

	# ~ Print the JSON with header - - - - - - - - - - - - - - - - - - - - - - - - #
	public function jsonWithHeader($title = null, $header, $data, $nameMap = [], $colorMap = []) {
		$colors = [];

		# Humanize the output and add color
		foreach ($header as $i => $name) {
			$header[$i] = !empty($nameMap[$name]) ? $nameMap[$name] : $name;
			$colors[] = !empty($colorMap[$name]) ? $colorMap[$name] : ClassRegistry::init('Theme')->field('primary_color', true);
		}

		# Add date
		array_unshift($header, __('Date'));

		# Output
		header('Content-Type: application/json');
		echo json_encode([
			'title'  => $title,
			'colors' => array_values($colors),
			'data'   => array_merge([ $header ], $data)
		]);
		die;
	}

	# ~ Parse the supplied period into MySQL compatible interval - - - - - - - - - #
	protected function prepareGoogleAnalytics() {

		$API_KEY = 'AIzaSyB5bR2vRP-XD5i-KfCQYdd7XvR6fjgm-o4';
		$CLIENT_ID = '827000867711-roq9jl2g897q33ue7rpc7d3qsml8qmdr.apps.googleusercontent.com';
		$TABLE_ID = 'ga:39639883';

		$this->set('google', [ 'api_key' => $API_KEY, 'client_id' => $CLIENT_ID, 'table_id' => $TABLE_ID ]);

		/* if(Configure::read('Website.google_analytics')) {
			$this->set('google', Configure::read('Website.google_analytics'));
		} */
	}

	# ~ Parse the supplied period into MySQL compatible interval - - - - - - - - - #
	protected function getPeriod($period) {
		switch ($period) {
			case '1week':
				return ('1 WEEK');
			case '6months':
				return ('6 MONTH');
			case '1year':
				return ('1 YEAR');
			default:
				return ('1 MONTH');
		}
	}

}
