<?php
namespace JExtstore\Component\JRealtimeAnalytics\Administrator\View\Serverstats;
/** 
 * @package JREALTIMEANALYTICS::SERVERSTATS::administrator::components::com_jrealtimeanalytics
 * @subpackage views
 * @subpackage serverstats
 * @author Joomla! Extensions Store
 * @copyright (C) 2013 - Joomla! Extensions Store
 * @license GNU/GPLv2 http://www.gnu.org/licenses/gpl-2.0.html 
 */
defined ( '_JEXEC' ) or die ( 'Restricted access' );
use Joomla\CMS\Language\Text;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Component\ComponentHelper;
use JExtstore\Component\JRealtimeAnalytics\Administrator\Framework\Helpers\Toolbars as ToolbarHelper;
use JExtstore\Component\JRealtimeAnalytics\Administrator\Framework\View as JRealtimeView;

define ( 'VISITSPERPAGE', 0 );
define ( 'TOTALVISITEDPAGES', 1 );
define ( 'TOTALVISITEDPAGESPERUSER', 2 );
define ( 'TOTALVISITORS', 3 );
define ( 'MEDIUMVISITTIME', 4 );
define ( 'MEDIUMVISITEDPAGESPERSINGLEUSER', 5 );
define ( 'NUMUSERSGEOGROUPED', 6 );
define ( 'NUMUSERSBROWSERGROUPED', 7 );
define ( 'NUMUSERSOSGROUPED', 8 );
define ( 'LEAVEOFF_PAGES', 9 );
define ( 'LANDING_PAGES', 10 );
define ( 'REFERRALTRAFFIC', 11 );
define ( 'SEARCHEDPHRASE', 12 );
define ( 'TOTALVISITEDPAGESPERIPADDRESS', 13 );
define ( 'BOUNCERATE', 14 );
define ( 'TOTALUNIQUEVISITORS', 15 );
define ( 'NUMUSERSDEVICEGROUPED', 16 );

/**
 * Server stats view
 *
 * @package JREALTIMEANALYTICS::SERVERSTATS::administrator::components::com_jrealtimeanalytics
 * @subpackage views
 * @subpackage realstats
 * @since 1.0
 */
class HtmlView extends JRealtimeView {
	// Template view variables
	protected $data;
	protected $dates;
	protected $geotrans;
	protected $userid;
	protected $nocache;
	protected $lists;
	protected $livesite;
	protected $cparams;
	
	/**
	 * Add the page title and toolbar.
	 *
	 * @since	1.6
	 */
	protected function addDisplayToolbar() {
		$user = $this->app->getIdentity();
		
		ToolbarHelper::title( Text::_( 'COM_JREALTIME_SERVERSTATS_PANEL_HEADER' ), 'jrealtimeanalytics' );
		ToolbarHelper::custom('serverstats.displaycsv', 'download', 'download', 'COM_JREALTIME_EXPORTCSV', false);
		ToolbarHelper::custom('serverstats.displayxls', 'download', 'download', 'COM_JREALTIME_EXPORTXLS', false);
		ToolbarHelper::custom('serverstats.displaypdf', 'download', 'download', 'COM_JREALTIME_EXPORTPDF', false);
		
		if ($user->authorise('core.delete', 'com_jrealtimeanalytics') && $user->authorise('core.edit', 'com_jrealtimeanalytics')) {
			ToolbarHelper::custom('serverstats.deletePeriodEntity', 'delete', 'delete', 'COM_JREALTIME_CLEANPERIOD_CACHE', false);
			ToolbarHelper::custom('serverstats.deleteEntity', 'cancel', 'cancel', 'COM_JREALTIME_CLEANALL_CACHE', false);
		}

		if ((int)$this->cparams->get('ai_analysis_enabled', 0)) {
			ToolbarHelper::custom('serverstats.runaianalysis', 'wand', 'wand', 'COM_JREALTIME_AI_RUN_ANALYSIS', false);
		}
		ToolbarHelper::custom('cpanel.display', 'home', 'home', 'COM_JREALTIME_CPANEL', false);
	}
	
	/**
	 * Default display delle stats
	 * 
	 * @access public
	 * @return void
	 */
	public function display($tpl = 'main') {
		$doc = $this->app->getDocument();
		$this->loadJQuery($doc);
		$this->loadJQueryUI($doc); // Required for calendar feature
		$this->loadBootstrap($doc);
		$this->loadJQVMap($doc);
		$this->loadJQFancybox($doc);
		$this->cparams = $this->getModel()->getComponentParams();
		
		$doc->getWebAssetManager()->registerAndUseScript ( 'jrealtime.tablesorter', 'administrator/components/com_jrealtimeanalytics/js/libraries/tablesorter/jquery.tablesorter.js', [], [], ['jquery']);
		$doc->getWebAssetManager()->registerAndUseScript ( 'jrealtime.serverstats', 'administrator/components/com_jrealtimeanalytics/js/serverstats.js', [], [], ['jquery']);
		
		$doc->getWebAssetManager()->addInlineScript("
			var jrealtimeIpAddressServerStatsEndpoint = '" . Uri::root() . 'administrator/index.php?option=com_jrealtimeanalytics&task=serverstats.fetchIpinfo&format=raw' . "';
			var jrealtimeBackendHostInfo = " . $this->cparams->get('backend_host_info', 0) . ";
			var jrealtimeStatsCalendarFormat = '" . $this->cparams->get('stats_calendar_type', 'date') . "';
			var jrealtimeAIAnalysisAjaxEndpoint = '" . Uri::root() . "administrator/index.php?option=com_jrealtimeanalytics&task=ajaxserver.display&format=json';
			var jrealtimeAIAnalysisCsrfToken = '" . $this->app->getFormToken() . "';
			Joomla.submitbutton = function(pressbutton) {
				if (pressbutton == 'serverstats.runaianalysis') {
					if (window.JRealtimeServerstats && typeof window.JRealtimeServerstats.runAIAnalysis === 'function') {
						window.JRealtimeServerstats.runAIAnalysis();
					}
					return false;
				}
				Joomla.submitform( pressbutton );
				if (pressbutton == 'serverstats.displaypdf' ||
					pressbutton == 'serverstats.displayxls' ||
					pressbutton == 'serverstats.displaycsv') {
					jQuery('#adminForm input[name=task]').val('serverstats.display');
				}
				return true;
			}
		");
		
		// Get stats data
		$model = $this->getModel();
		
		$statsData = $model->getData();
		$lists = $model->getLists();
		$geoTranslations = $model->getGeoTranslations();
		// Inject js translations
		$translations = array('COM_JREALTIME_STATS_DETAILS',
							  'COM_JREALTIME_VISUALMAP',
							  'COM_JREALTIME_NUMRESULTS',
							  'COM_JREALTIME_DELETE_SERVERSTATS_PERIOD_CACHE',
							  'COM_JREALTIME_DELETE_SERVERSTATS_ALL_CACHE',
							  'COM_JREALTIME_AI_ANALYSIS_REQUEST_FAILED'
		);
		$this->injectJsTranslations($translations, $doc);
		$doc->getWebAssetManager()->addInlineScript ( 'var jrealtimeGeoMapData = ' . json_encode ( $statsData[NUMUSERSGEOGROUPED]['clientside'] ) . ';' );
		$doc->getWebAssetManager()->addInlineScript ( 'var jrealtimeGeolocationService = "' . $this->getModel()->getComponentParams()->get('backend_geolocation_service', 'geoiplookup') . '";' );
		$doc->getWebAssetManager()->addInlineStyle ( 'div.popover.bs-popover-right{min-height:71px}' );
		
		// Enqueue user message se nel periodo selezionato non ci sono pagine visitate AKA statistiche da mostrare
		if(!$statsData[TOTALVISITEDPAGES]) {
			$this->app->enqueueMessage(Text::_('COM_JREALTIME_NO_STATS_IN_PERIOD'));
		}
		
		// Set reference in template
		$dates = array('start'=>$this->getModel()->getState('fromPeriodOriginal'), 'to'=>$this->getModel()->getState('toPeriodOriginal')); 
		$this->data = $statsData;
		$this->dates = $dates;
		$this->geotrans = $geoTranslations;
		$this->userid = $this->user->id;
		$this->nocache = '?time=' . time();
		$this->lists = $lists;
		$this->livesite = Uri::root();
		
		// Aggiunta toolbar
		$this->addDisplayToolbar();
		
		// Some exceptions have been triggered
		if(empty($statsData)) {
			return false;
		}
		
		// Set timezone if required
		if($this->cparams->get('offset_type', 'joomla') == 'joomla') {
			$jConfig = $this->app->getConfig();
			date_default_timezone_set($jConfig->get('offset', 'UTC'));
			// Fix for the new Date by logger date_default_timezone_set to UTC, reset always timezone
			if(property_exists('\Joomla\CMS\Date\Date', 'stz')) {
				$reflection = new \ReflectionProperty('\Joomla\CMS\Date\Date', 'stz');
				if (\PHP_VERSION_ID < 80100) {
					$reflection->setAccessible(true);
				}
				$reflection->setValue(null, null);
			}
		}
		
		parent::display($tpl);
	}
	
	/**
	 * Show entity details richiesto per visite utente e pagine
	 * 
	 * @access public
	 * @param Object& $detailData
	 * @param string $tpl detailType
	 * @return void 
	 */
	public function showEntity(&$detailData, $tpl) { 
		$doc = $this->app->getDocument();
		$this->loadJQuery($doc);
		$this->loadJQueryUI($doc); // Required for draggable feature
		$this->loadBootstrap($doc);
		$doc->getWebAssetManager()->addInlineStyle('body.contentpane.component{height:95%;padding-top:10px;}');
		$doc->getWebAssetManager()->registerAndUseScript ( 'jrealtime.tablesorter', 'administrator/components/com_jrealtimeanalytics/js/libraries/tablesorter/jquery.tablesorter.js', [], [], ['jquery']);
		
		$doc->getWebAssetManager()->addInlineScript("
						jQuery(function($) {
							$('table.table-striped').tablesorter({
								cssHeader : ''
							});
						});
					");
		
		// Add scripting for flow tpl feature
		if($tpl == 'flow') {
			$doc->getWebAssetManager()->registerAndUseScript ( 'jrealtime.gojs', 'administrator/components/com_jrealtimeanalytics/js/libraries/gojs/go.js', [], [], ['jquery']);
			$doc->getWebAssetManager()->registerAndUseScript ( 'jrealtime.flow', 'administrator/components/com_jrealtimeanalytics/js/flow.js', [], [], ['jquery', 'jrealtime.gojs']);
		}
		
		$this->detailData = $detailData;
		$this->cparams = ComponentHelper::getParams('com_jrealtimeanalytics');
		$this->daemonRefresh = $this->cparams->get('daemonrefresh', 2);
		$this->livesite = Uri::root();
		
		parent::display($tpl);
	}
}