<?php
/*
 *
 * @package		ARI Smart Content
 * @author		ARI Soft
 * @copyright	Copyright (c) 2011 www.ari-soft.com. All rights reserved
 * @license		GNU/GPL (http://www.gnu.org/copyleft/gpl.html)
 * 
 */

(defined('_JEXEC') && defined('ARI_FRAMEWORK_LOADED')) or die;

AriKernel::import('Joomla.Models.Model');
AriKernel::import('Joomla.Database.DBUtils');
AriKernel::import('Utils.ArrayHelper');

class AriSmartContentModelModules extends AriModel
{
	function getModuleTypes()
	{
		$db =& $this->getDBO();
		
		$query = AriDBUtils::getQuery();
		$query->select(
			array(
				'name AS Name',
				'element AS Type'
			)
		);
		$query->from('#__extensions E');
		$query->where('E.type = "module" AND E.element LIKE "mod_arismartcontent_%"');
		
		$db->setQuery((string)$query);
		$types = $db->loadObjectList();

		if ($db->getErrorNum())
		{
			JError::raiseError(
				500, 
				JText::sprintf(
					'COM_ARISMARTCONTENT_ERROR_SQL_QUERY', 
					__CLASS__ . '::' . __FUNCTION__ . '()', 
					$query, 
					$db->getErrorMsg()
				)
			);
			
			return null;
		}

		return $types;
	}
	
	function getModuleCount($moduleType, $filter)
	{
		$db =& $this->getDBO();

		$query = AriDBUtils::getQuery();
		$query->select('COUNT(*)');
		$query->from('#__modules');
		
		if ($moduleType)
			$query->where(
				sprintf(
					'module = %1$s',
					$db->Quote($moduleType)
				)
			);
		else
			$query->where(
				'module LIKE "mod_arismartcontent_%"'
			);

		$db->setQuery((string)$query);
		$count = $db->loadResult();

		if ($db->getErrorNum())
		{
			JError::raiseError(
				500, 
				JText::sprintf(
					'COM_ARISMARTCONTENT_ERROR_SQL_QUERY', 
					__CLASS__ . '::' . __FUNCTION__ . '()', 
					$query, 
					$db->getErrorMsg()
				)
			);
			
			return 0;
		}

		return $count;
	}
	
	function getModuleList($moduleType, $filter)
	{
		$db =& $this->getDBO();
		if (empty($filter))
			$filter = new AriDataFilter();

		$query = AriDBUtils::getQuery();
		$query->select(
			array(
				'M.id AS Id',
				'M.title AS Name',
				'M.module AS Type',
				'E.name AS TypeName'
			)
		);
		$query->from('#__modules M');
		$query->innerJoin('#__extensions E ON M.module = E.element');
		
		$query->where('M.published = 1');
		
		if ($moduleType)
			$query->where(
				sprintf(
					'module = %1$s',
					$db->Quote($moduleType)
				)
			);
		else
			$query->where(
				'module LIKE "mod_arismartcontent_%"'
			);
		
		if ($filter)
		{
			$query = $filter->applyToQuery($query);
		}

		$db->setQuery((string)$query, $filter->getConfigValue('startOffset'), $filter->getConfigValue('limit'));
		$modules = $db->loadObjectList();
		if ($db->getErrorNum())
		{
			JError::raiseError(
				500, 
				JText::sprintf(
					'COM_ARISMARTCONTENT_ERROR_SQL_QUERY', 
					__CLASS__ . '::' . __FUNCTION__ . '()', 
					$query, 
					$db->getErrorMsg()
				)
			);
			
			return null;
		}
		
		return $modules;
	}
}