<?php
namespace JExtstore\Component\JRealtimeAnalytics\Administrator\View\Eventstats;
/**
 * @package JREALTIMEANALYTICS::EVENTSTATS::administrator::components::com_jrealtimeanalytics
 * @subpackage views
 * @subpackage eventstats
 * @author Joomla! Extensions Store
 * @copyright (C) 2014 - 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\Pagination\Pagination;
use Joomla\Filter\OutputFilter;
use JExtstore\Component\JRealtimeAnalytics\Administrator\Framework\Helpers\Toolbars as ToolbarHelper;
use JExtstore\Component\JRealtimeAnalytics\Administrator\Framework\View as JRealtimeView;

/**
 * @package JREALTIMEANALYTICS::EVENTSTATS::administrator::components::com_jrealtimeanalytics
 * @subpackage views
 * @subpackage eventstats
 * @since 1.0
 */
class HtmlView extends JRealtimeView {
	// Template view variables
	protected $dates;
	protected $pagination;
	protected $searchword;
	protected $lists;
	protected $orders;
	protected $items;
	protected $eventDetails;
	protected $record;
	protected $cparams;
	protected $livesite;
	
	/**
	 * Add the page title and toolbar.
	 *
	 * @since	1.6
	 */
	protected function addEditEntityToolbar() {
		$user		= $this->app->getIdentity();
		$userId		= $user->id;
		$isNew		= ($this->record->id == 0);
		$checkedOut	= !($this->record->checked_out == 0 || $this->record->checked_out == $userId);
		$toolbarHelperTitle = $isNew ? 'COM_JREALTIME_EVENT_NEW' : 'COM_JREALTIME_EVENT_EDIT';
	
		$doc = $this->app->getDocument();
		ToolbarHelper::title( Text::_( $toolbarHelperTitle ), 'jrealtimeanalytics' );
	
		if ($isNew)  {
			// For new records, check the create permission.
			if ($isNew && ($user->authorise('core.create', 'com_jrealtimeanalytics'))) {
				ToolbarHelper::apply( 'eventstats.applyEntity', 'JAPPLY');
				ToolbarHelper::save( 'eventstats.saveEntity', 'JSAVE');
				ToolbarHelper::save2new( 'eventstats.saveEntity2New');
			}
		} else {
			// Can't save the record if it's checked out.
			if (!$checkedOut) {
				// Since it's an existing record, check the edit permission, or fall back to edit own if the owner.
				if ($user->authorise('core.edit', 'com_jrealtimeanalytics')) {
					ToolbarHelper::apply( 'eventstats.applyEntity', 'JAPPLY');
					ToolbarHelper::save( 'eventstats.saveEntity', 'JSAVE');
					ToolbarHelper::save2new( 'eventstats.saveEntity2New');
					ToolbarHelper::custom('eventstats.showEntitycsv', 'download', 'download', 'COM_JREALTIME_EXPORTCSV', false);
					ToolbarHelper::custom('eventstats.showEntityxls', 'download', 'download', 'COM_JREALTIME_EXPORTXLS', false);
					ToolbarHelper::custom('eventstats.showEntitypdf', 'download', 'download', 'COM_JREALTIME_EXPORTPDF', false);
				}
			}
		}
			
		ToolbarHelper::custom('eventstats.cancelEntity', 'cancel', 'cancel', 'JCANCEL', false);
	}
	
	
	/**
	 * Add the page title and toolbar.
	 *
	 * @since	1.6
	 */
	protected function addDisplayToolbar() {
		$user = $this->app->getIdentity();
		ToolbarHelper::title( Text::_( 'COM_JREALTIME_EVENTS_LIST' ), 'jrealtimeanalytics' );
		// Access check.
		if ($user->authorise('core.create', 'com_jrealtimeanalytics')) {
			ToolbarHelper::addNew('eventstats.editEntity', 'COM_JREALTIME_ADD_EVENT');
		}
	
		if ($user->authorise('core.edit', 'com_jrealtimeanalytics')) {
			ToolbarHelper::editList('eventstats.editEntity', 'COM_JREALTIME_EDIT_EVENT');
			ToolbarHelper::custom( 'eventstats.copyEntity', 'copy', 'copy', 'COM_JREALTIME_DUPLICATE_EVENT' );
		}
	
		if ($user->authorise('core.delete', 'com_jrealtimeanalytics') && $user->authorise('core.edit', 'com_jrealtimeanalytics')) {
			ToolbarHelper::custom( 'eventstats.resetEntity', 'trash', 'trash', 'COM_JREALTIME_RESET_EVENT' );
			ToolbarHelper::deleteList(Text::_('COM_JREALTIME_DELETE_EVENT'), 'eventstats.deleteEntity');
		}
			
		ToolbarHelper::custom('eventstats.showCategories', 'folder', 'folder', 'COM_JREALTIME_CATEGORIES', false);
		ToolbarHelper::custom('cpanel.display', 'home', 'home', 'COM_JREALTIME_CPANEL', false);
	}
	
	/**
	 * Default display listEntities
	 *        	
	 * @access public
	 * @param string $tpl
	 * @return void
	 */
	public function display($tpl = null) {
		// Get main records
		$rows = $this->get ( 'Data' );
		$lists = $this->get ( 'Filters' );
		$total = $this->get ( 'Total' );
		
		$doc = $this->app->getDocument();
		$this->loadJQuery($doc);
		$this->loadJQueryUI($doc); // Required for calendar feature
		$this->loadBootstrap($doc);
		$doc->getWebAssetManager()->registerAndUseStyle ( 'jrealtime.eventstats', 'administrator/components/com_jrealtimeanalytics/css/eventstats.css');
		
		$doc->getWebAssetManager()->addInlineStyle('@media (max-width: 1200px) and (min-width: 768px) { body.admin.com_jrealtimeanalytics { min-width: 1200px; }}
													@media (max-width: 640px) { body.admin.com_jrealtimeanalytics { min-width: 640px; }}');
		$doc->getWebAssetManager()->addInlineScript('jQuery(function($){$("input[data-role=calendar]").datepicker({dateFormat:"yy-mm-dd",firstDay:1}).prev("span").on("click",function(){$(this).datepicker("show");});});');
		
		// Inject js translations
		$translations = array('COM_JREALTIME_RESET_EVENT_MSG');
		$this->injectJsTranslations($translations, $doc);
		
		$doc->getWebAssetManager()->addInlineScript("
					document.addEventListener('DOMContentLoaded', function(){
						if(typeof(COM_JREALTIME_RESET_EVENT_MSG) !== 'undefined') {
							document.querySelector('#toolbar-trash').setAttribute('confirm-message', COM_JREALTIME_RESET_EVENT_MSG);
						}
					});
				");
		
		$orders = array ();
		$orders ['order'] = $this->getModel ()->getState ( 'order' );
		$orders ['order_Dir'] = $this->getModel ()->getState ( 'order_dir' );
		// Pagination view object model state populated
		$pagination = new Pagination ( $total, $this->getModel ()->getState ( 'limitstart' ), $this->getModel ()->getState ( 'limit' ) );
		
		$dates = array('start'=>$this->getModel()->getState('fromPeriod'), 'to'=>$this->getModel()->getState('toPeriod'));
		$this->dates = $dates;
		$this->user = $this->app->getIdentity ();
		$this->pagination = $pagination;
		$this->searchword = $this->getModel ()->getState ( 'searchword' );
		$this->lists = $lists;
		$this->orders = $orders;
		$this->items = $rows;
		$this->option = $this->getModel ()->getState ( 'option' );
		
		// Aggiunta toolbar
		$this->addDisplayToolbar();
		
		parent::display ( 'list' );
	}
	
	/**
	 * Edit entity view
	 *
	 * @access public
	 * @param Object& $row the item to edit
	 * @return void
	 */
	public function editEntity($row) {
		// Sanitize HTML Object2Form
		OutputFilter::objectHTMLSafe( $row );
		
		// Load JS Client App dependencies
		$doc = $this->app->getDocument();
		$base = Uri::root();
		$this->loadJQuery($doc);
		$this->loadBootstrap($doc);
		$this->loadValidation($doc);
		$doc->getWebAssetManager()->registerAndUseStyle ( 'jrealtime.eventstats', 'administrator/components/com_jrealtimeanalytics/css/eventstats.css');
		
		// Load specific JS App
		$doc->getWebAssetManager()->registerAndUseScript ( 'jrealtime.eventstats', 'administrator/components/com_jrealtimeanalytics/js/eventstats.js', [], [], ['jquery']);
		$doc->getWebAssetManager()->registerAndUseScript ( 'jrealtime.tablesorter', 'administrator/components/com_jrealtimeanalytics/js/libraries/tablesorter/jquery.tablesorter.js', [], [], ['jquery']);
		
		// Inject js translations
		$translations = array('COM_JREALTIME_NUMRESULTS');
		$this->injectJsTranslations($translations, $doc);
		
		$doc->getWebAssetManager()->addInlineScript("
					jQuery(function($){
						$('table.table-striped').tablesorter({ 
							cssHeader: ''
						});
					});
					
					Joomla.submitbutton = function(pressbutton) {
						if(!jQuery.fn.validation) {
							jQuery.extend(jQuery.fn, jrealtimejQueryBackup.fn);
						}
						jQuery('#adminForm').validation();
				
						if (pressbutton == 'eventstats.cancelEntity') {
							jQuery('#adminForm').off();
							Joomla.submitform( pressbutton );
							return true;
						}
				
						if(jQuery('#adminForm').validate()) {
							Joomla.submitform( pressbutton );
							return true;
						}
						return false;
					}
				");
		
		$lists = $this->getModel()->getLists($row);
		$this->eventDetails = $this->getModel()->getEventDetails($row->id);
		$this->record = $row;
		$this->lists = $lists;
		$this->cparams = $this->getModel()->getComponentParams();
		$this->livesite = Uri::root();
		
		// Aggiunta toolbar
		$this->addEditEntityToolbar();
		
		// 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 ( 'edit' );
	}
	
	/**
	 * Edit entity view
	 *
	 * @access public
	 * @param Object& $row the item to edit
	 * @return void
	 */
	public function showEntity($row, $tpl) {
		$this->eventDetails = $this->getModel()->getEventDetails($row->id);
		$this->record = $row;
		$this->cparams = $this->getModel()->getComponentParams();
	
		parent::display ( $tpl );
	}
}