<?php
namespace JExtstore\Component\JRealtimeAnalytics\Administrator\Model;
/**
 *
 * @package JREALTIMEANALYTICS::EVENTSTATS::administrator::components::com_jrealtimeanalytics
 * @subpackage models
 * @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\HTML\HTMLHelper;
use JExtstore\Component\JRealtimeAnalytics\Administrator\Framework\Model as JRealtimeModel;
use JExtstore\Component\JRealtimeAnalytics\Administrator\Framework\Exception as JRealtimeException;
use JExtstore\Component\JRealtimeAnalytics\Administrator\Framework\Html\Categories as JRealtimeHtmlCategories;
use JExtstore\Component\JRealtimeAnalytics\Administrator\Framework\Helpers\Html as JRealtimeHelpersHtml;

/**
 * Sources model concrete implementation <<testable_behavior>>
 *
 * @package JREALTIMEANALYTICS::EVENTSTATS::administrator::components::com_jrealtimeanalytics
 * @subpackage models
 * @since 1.0
 */
class CategoriesModel extends JRealtimeModel {
	/**
	 * Records query result set
	 *
	 * @access private
	 * @var Object[]
	 */
	private $records;
	
	/**
	 * Build list entities query
	 *
	 * @access protected
	 * @return string
	 */
	protected function buildListQuery() {
		// WHERE
		$where = array ();
		$whereString = null;
		$orderString = null;
		
		$where [] = "s.parent_id > 0";
		// STATE FILTER
		if ($filter_state = $this->state->get ( 'state' )) {
			if ($filter_state == 'P') {
				$where [] = 's.published = 1';
			} else if ($filter_state == 'U') {
				$where [] = 's.published = 0';
			}
		}
		
		// TYPE FILTER
		if ($this->state->get ( 'type' )) {
			$where [] = "s.type = " . $this->dbInstance->quote ( $this->state->get ( 'type' ) );
		}
		
		// TEXT FILTER
		if ($this->state->get ( 'searchword' )) {
			$where [] = "s.title LIKE " . $this->dbInstance->quote("%" . $this->state->get ( 'searchword' ) . "%");
		}
		
		if (count ( $where )) {
			$whereString = "\n WHERE " . implode ( "\n AND ", $where );
		}
		
		// ORDERBY
		if ($this->state->get ( 'order' )) {
			$orderString = "\n ORDER BY " . $this->state->get ( 'order' ) . " ";
		}
		
		// ORDERDIR
		if ($this->state->get ( 'order_dir' )) {
			$orderString .= $this->state->get ( 'order_dir' );
		}
		
		$query = "SELECT s.*, u.name AS editor" . 
				 "\n FROM #__realtimeanalytics_categories AS s" . 
				 "\n LEFT JOIN #__users AS u" . 
				 "\n ON s.checked_out = u.id" . 
				 $whereString . 
				 $orderString;
		return $query;
	}
	
	/**
	 * Storing entity by ORM table
	 *
	 * @access public
	 * @param bool $updateNulls
	 * @return mixed
	 */
	public function storeEntity($updateNulls = true) {
		return parent::storeEntity($updateNulls);
	}
	
	/**
	 * Return select lists used as filter for listEntities
	 *
	 * @access public
	 * @return array
	 */
	public function getFilters(): array {
		$filters = [];
		$filters ['state'] = HTMLHelper::_ ( 'grid.state', $this->getState ( 'state' ) );
		
		$datasourceTypes = [];
		$datasourceTypes [] = HTMLHelper::_ ( 'select.option', null, Text::_ ( 'COM_JREALTIME' ) );
		$datasourceTypes [] = HTMLHelper::_ ( 'select.option', 'user', Text::_ ( 'COM_JREALTIME' ) );
		$datasourceTypes [] = HTMLHelper::_ ( 'select.option', 'menu', Text::_ ( 'COM_JREALTIME' ) );
		$datasourceTypes [] = HTMLHelper::_ ( 'select.option', 'content', Text::_ ( 'COM_JREALTIME' ) );
		$filters ['type'] = HTMLHelper::_ ( 'select.genericlist', $datasourceTypes, 'filter_type', 'onchange="Joomla.submitform();"', 'value', 'text', $this->getState ( 'type' ) );
		
		return $filters;
	}
	
	/**
	 * Return select lists used as filter for editEntity
	 *
	 * @access public
	 * @param Object $record        	
	 * @return array
	 */
	public function getLists($record = null): array {
		$lists = [];
		// Grid states
		$lists ['published'] = JRealtimeHelpersHtml::booleanlist( 'published', null, $record->published );
		
		$categories = JRealtimeHtmlCategories::getOptions(false, $record->id);
		$lists['categories'] = HTMLHelper::_('select.genericlist', $categories, 'parent_id', 'class="inputbox form-select"', 'value', 'text', $record->parent_id);
		
		return $lists;
	}
	
	/**
	 * Delete entity
	 *
	 * @param array $ids
	 * @access public
	 * @return bool
	 */
	public function deleteEntity($ids): bool {
		$table = $this->getTable ($this->getName(), 'Administrator');
	
		// Ciclo su ogni entity da cancellare
		if (is_array ( $ids ) && count ( $ids )) {
			foreach ( $ids as $id ) {
				try {
					if (! $table->load ( $id )) {
						continue;
					}
					if (! $table->delete ( $id )) {
						throw new JRealtimeException ( $table->getException (), 'error' );
					}
					// Only if table supports ordering
					if (property_exists ( $table, 'ordering' )) {
						$table->reorder ();
					}
				} catch ( JRealtimeException $e ) {
					$this->setException ( $e );
					return false;
				} catch ( \Exception $e ) {
					$jrealtimeException = new JRealtimeException ( $e->getMessage (), 'error' );
					$this->setException ( $jrealtimeException );
					return false;
				}
			}
		}
	
		return true;
	}
}