<?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\Table\Table;
use Joomla\CMS\Table\Nested as TableNested;
use Joomla\CMS\Access\Rules as AccessRules;
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 CategoriesTable extends TableNested {
	use Exceptions;
	
	/**
	 * DatabaseInterface object.
	 * @protected DatabaseInterface Object
	 */
	protected $dbo;
	/**
	 *
	 * @var int
	 */
	public $id = 0;
	
	/**
	 *
	 * @var int
	 */
	public $asset_id = 0;
	
	/**
	 *
	 * @var string
	 */
	public $parent_id = 0;
	
	/**
	 *
	 * @var string
	 */
	public $lft = 0;
	
	/**
	 *
	 * @var string
	 */
	public $rgt = 0;
	
	/**
	 *
	 * @var int
	 */
	public $level = 1;
	
	/**
	 *
	 * @var string
	 */
	public $path = '';
	
	/**
	 *
	 * @var string
	 */
	public $title = '';
	
	/**
	 *
	 * @var string
	 */
	public $alias = '';
	
	/**
	 *
	 * @var string
	 */
	public $description = '';
	
	/**
	 *
	 * @var int
	 */
	public $published = 1;
	
	/**
	 *
	 * @var int
	 */
	public $checked_out = null;
	
	/**
	 *
	 * @var datetime
	 */
	public $checked_out_time = null;
	
	/**
	 * Method to compute the default name of the asset.
	 * The default name is in the form table_name.id
	 * where id is the value of the primary key of the table.
	 *
	 * @return string
	 *
	 * @since 11.1
	 */
	protected function _getAssetName() {
		$k = $this->_tbl_key;
		
		return 'com_jrealtimeanalytics.category.' . ( int ) $this->$k;
	}
	
	/**
	 * Method to return the title to use for the asset table.
	 *
	 * @return string
	 *
	 * @since 11.1
	 */
	protected function _getAssetTitle() {
		return $this->title;
	}
	
	/**
	 * Get the parent asset id for the record
	 *
	 * @param Table $table
	 *        	A Table object for the asset parent.
	 * @param integer $id
	 *        	The id for the asset
	 *        	
	 * @return integer The id of the asset's parent
	 *        
	 * @since 11.1
	 */
	protected function _getAssetParentId(?Table $table = null, $id = null) {
		$assetId = null;
		
		// This is a category under a category.
		if ($this->parent_id > 1) {
			// Build the query to get the asset id for the parent category.
			$query = method_exists ( $this->dbo, 'createQuery' ) ? $this->dbo->createQuery () : $this->dbo->getQuery ( true );
			$query->select ( $this->dbo->quoteName ( 'asset_id' ) )
				  ->from ( $this->dbo->quoteName ( '#__realtimeanalytics_categories' ) )
				  ->where ( $this->dbo->quoteName ( 'id' ) . ' = ' . $this->parent_id );
			
			// Get the asset id from the database.
			$this->dbo->setQuery ( $query );
			
			if ($result = $this->dbo->loadResult ()) {
				$assetId = ( int ) $result;
			}
		} elseif ($assetId === null) { // This is a category that needs to parent with the extension.
			// Build the query to get the asset id for the parent category.
			$query = method_exists ( $this->dbo, 'createQuery' ) ? $this->dbo->createQuery () : $this->dbo->getQuery ( true );
			$query->select ( $this->dbo->quoteName ( 'id' ) )
				  ->from ( $this->dbo->quoteName ( '#__assets' ) )
				  ->where ( $this->dbo->quoteName ( 'name' ) . ' = ' . $this->dbo->quote ( 'com_jrealtimeanalytics') );
			
			// Get the asset id from the database.
			$this->dbo->setQuery ( $query );
			
			if ($result = $this->dbo->loadResult ()) {
				$assetId = ( int ) $result;
			}
		}
		
		// Return the asset id.
		if ($assetId) {
			return $assetId;
		} else {
			return parent::_getAssetParentId ( $table, $id );
		}
	}
	
	/**
	 * Override check function
	 *
	 * @return boolean
	 *
	 * @see Table::check()
	 * @since 11.1
	 */
	public function check() {
		// Check for a title.
		if (trim ( $this->title ) == '') {
			$this->setException ( Text::_ ( 'JLIB_DATABASE_ERROR_MUSTCONTAIN_A_TITLE_CATEGORY' ) );
			
			return false;
		}
		
		return true;
	}
	
	/**
	 * Overloaded bind function.
	 *
	 * @param array $array
	 *        	named array
	 * @param string $ignore
	 *        	An optional array or space separated list of properties
	 *        	to ignore while binding.
	 *        	
	 * @return mixed Null if operation was satisfactory, otherwise returns an error
	 *        
	 * @see Table::bind()
	 * @since 11.1
	 */
	public function bind($array, $ignore = '') {
		parent::bind ( $array, $ignore );
		
		// MySql strict mode primary key auto increment compliance
		if(!$this->id) {
			$this->id = 0;
		}
		
		// Bind the rules.
		if (isset ( $array ['rules'] ) && is_array ( $array ['rules'] )) {
			$rules = new AccessRules ( $array ['rules'] );
			$this->setRules ( $rules );
		}
		
		// Set the new parent id if parent id not matched OR while New/Save as Copy .
		if (!empty($array['haschanged']) || !$this->id) {
			$this->setLocation ( $array ['parent_id'], 'last-child' );
		}
		
		return true;
	}
	
	/**
	 * Overridden Table::store to set created/modified and user id.
	 *
	 * @param boolean $updateNulls
	 *        	True to update fields even if they are null.
	 *        	
	 * @return boolean True on success.
	 *        
	 * @since 11.1
	 */
	public function store($updateNulls = false) {
		return parent::store ( $updateNulls );
	}
	
	/**
	 * 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_categories', 'id', $db, $dispatcher );
		
		$this->dbo = $db;
		
		// Support null values for datetime field
		$this->_supportNullValue = true;
	}
}