<?php
namespace JExtstore\Component\JRealtimeAnalytics\Administrator\Table;
/**
 *
 * @package JREALTIMEANALYTICS::EVENTSTATS::administrator::components::com_jrealtimeanalytics
 * @subpackage tables
 * @author Joomla! Extensions Store
 * @copyright (C) 2014 - Joomla! Extensions Store
 * @license GNU/GPLv2 http://www.gnu.org/licenses/gpl-2.0.html
 */
// no direct access
defined ( '_JEXEC' ) or die ( 'Restricted access' );
use Joomla\Database\DatabaseInterface;
use Joomla\Database\DatabaseDriver;
use Joomla\Event\DispatcherInterface;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Factory;
use Joomla\Registry\Registry;
use Joomla\CMS\Table\Table;
use JExtstore\Component\JRealtimeAnalytics\Administrator\Framework\Exception\Exceptions;

/**
 * ORM Table for event entities
 *
 * @package JREALTIMEANALYTICS::EVENTSTATS::administrator::components::com_jrealtimeanalytics
 * @subpackage tables
 * @since 1.0
 */
class EventstatsTable extends Table {
	use Exceptions;
	
	/**
	 *
	 * @var object
	 */
	private $_validationParams = null;
	
	/**
	 * DatabaseInterface object.
	 * @protected DatabaseInterface Object
	 */
	protected $dbo;
	
	/**
	 *
	 * @var int
	 */
	public $id = 0;
	
	/**
	 *
	 * @var int
	 */
	public $catid = 0;
	
	/**
	 *
	 * @var string
	 */
	public $type = '';
	
	/**
	 *
	 * @var string
	 */
	public $name = '';
	
	/**
	 *
	 * @var string
	 */
	public $description = '';
	
	/**
	 *
	 * @var int
	 */
	public $hasgoal = 0;
	
	/**
	 *
	 * @var int
	 */
	public $goal_expectation = null;
	
	/**
	 *
	 * @var int
	 */
	public $goal_notification = 0;
	
	/**
	 *
	 * @var string
	 */
	public $goal_notification_emails = null;
	
	/**
	 *
	 * @var int
	 */
	public $checked_out = null;
	
	/**
	 *
	 * @var datetime
	 */
	public $checked_out_time = null;
	
	/**
	 *
	 * @var int
	 */
	public $published = 1;
	
	/**
	 *
	 * @var int
	 */
	public $ordering = 0;
	
	/**
	 *
	 * @var string
	 */
	public $params = '';
	
	/**
	 * Bind Table override
	 * @override
	 *
	 * @see Table::bind()
	 */
	public function bind($fromArray, $ignore = '', $saveTask = false, $sessionTask = false) {
		parent::bind ( $fromArray );
		
		// MySql strict mode primary key auto increment compliance
		if(!$this->id) {
			$this->id = 0;
		}
		
		if ($saveTask) {
			$registry = new Registry ();
			$registry->loadArray ( $this->params );
			// Swap for validation
			$this->_validationParams = $registry;
			
			$this->params = $registry->toString ();
			
			// Reset nullable fields
			if(!$this->description) {
				$this->description = null;
			}
			
			if(!$this->goal_expectation) {
				$this->goal_expectation = null;
			}
		}
		
		// Reset dyna params for event type if type changed
		if(Factory::getApplication()->getInput()->get('task') == 'eventstats.changeEntity') {
			$this->params = null;
		}
		
		// Manage complex attributes during session recovering bind/load
		if ($sessionTask) {
			$registry = new Registry ( $this->params );
			$this->params = $registry;
		}
		
		return true;
	}
	
	/**
	 * Load Table override
	 * @override
	 *
	 * @see Table::load()
	 */
	public function load($idEntity = null, $reset = true) {
		// If not $idEntity set return empty object
		if ($idEntity) {
			if (! parent::load ( $idEntity )) {
				return false;
			}
		}
		
		$registry = new Registry ($this->params);
		$this->params = $registry;
		
		return true;
	}
	
	/**
	 * Check Table override
	 * @override
	 *
	 * @see Table::check()
	 */
	public function check() {
		// Skip validation if event type is changing or is getting defined
		if(Factory::getApplication()->getInput()->get('task') == 'eventstats.changeEntity') {
			return true;
		}
		
		// Name required
		if (! $this->name) {
			$this->setException ( Text::_ ( 'COM_JREALTIME_VALIDATION_ERROR' ) );
			return false;
		}
		
		// Type of event required
		if (! $this->type) {
			$this->setException ( Text::_ ( 'COM_JREALTIME_VALIDATION_ERROR' ) );
			return false;
		}
		
		// Validation for viewurl/mintimeonpage track event type
		if($this->type == 'viewurl' || $this->type == 'mintimeonpage') {
			// Menu page item required if menupage mode chosen
			if ($this->_validationParams->get('viewtype') == 'menupage' && !$this->_validationParams->get('menupage')) {
				$this->setException ( Text::_('COM_JREALTIME_VALIDATION_ERROR' ) );
				return false;
			}
			
			// Link url required and to be valid
			if ($this->_validationParams->get('viewtype') == 'urlpage' && (!$this->_validationParams->get('urlpage') || !preg_match('/^https?:\/\/[^\s\/$.?#].[^\s]*$/iu', trim($this->_validationParams->get('urlpage'))))) {
				$this->setException ( Text::_('COM_JREALTIME_VALIDATION_ERROR_URL' ) );
				return false;
			}
		}
		
		return true;
	}
	
	/**
	 * Store Table override
	 * @override
	 *
	 * @see Table::store()
	 */
	public function store($updateNulls = true) {
		return parent::store($updateNulls);
	}
	
	/**
	 * Delete Table override
	 * @override
	 *
	 * @see Table::delete()
	 */
	public function delete($pk = null) {
		$eventDeleted = parent::delete($pk);

		if($eventDeleted) {
			// Delete reference table evemts track by foreign key
			$query = method_exists ( $this->dbo, 'createQuery' ) ? $this->dbo->createQuery () : $this->dbo->getQuery ( true );
			$query = $query->delete('#__realtimeanalytics_eventstats_track');
			$query->where('event_id = ' . (int)$pk);
			// Check for a database error.
			try {
				$this->dbo->setQuery($query);
				$this->dbo->execute();
			} catch(\Exception $e) {
				$eventDeleted = false;
			}
		}

		return $eventDeleted;
	}
	
	/**
	 * Class constructor
	 * @param DatabaseDriver $db DatabaseDriver object.
	 * @param DispatcherInterface  $dispatcher  Event dispatcher for this table
	 *
	 * return Object&
	 */
	public function __construct(DatabaseInterface $db, ?DispatcherInterface $dispatcher = null) {
		parent::__construct ( '#__realtimeanalytics_eventstats', 'id', $db, $dispatcher );
		
		$this->dbo = $db;
		
		// Support null values for datetime field
		$this->_supportNullValue = true;
	}
}