<?php
/**
 * @version $Id$
 * @package    Contact_Enhanced
 * @subpackage Models
 * @author     Douglas Machado {@link http://ideal.fok.com.br}
 * @author     Created on 04-Dec-09
 * @license		GNU/GPL, see license.txt
 * Contact Enhanced  is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses. */

//-- No direct access
defined('_JEXEC') or die('=;)');

jimport('joomla.application.component.model');

class Contact_EnhancedsModelMessages extends JModel
{
	var $_data;
	var $_total = null;
	var $_pagination = null;

	function __construct()
	{
		parent::__construct();
		global $mainframe, $option;
		$this->filter_order_Dir	= $mainframe->getUserStateFromRequest( $option.'.filter_order_Dir', 'filter_order_Dir', 'asc', 'word' );
		//_ECR_MAT_ORDERING_MODAL1_
		$this->filter_order	= $mainframe->getUserStateFromRequest( $option.'.filter_order', 'filter_order',	'm.date', 'cmd' );
		
		$this->search		= $mainframe->getUserStateFromRequest( "$option.search", 'search', '', 'string' );
		$this->search		= JString::strtolower( $this->search );
		
		$this->filter_catid	= $mainframe->getUserStateFromRequest( $option.'.filter_catid', 'filter_catid',	'', 'cmd' );

		$limit		= $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart	= $mainframe->getUserStateFromRequest( $option.'.limitstart', 'limitstart', 0, 'int' );
		$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);
	}
	
	function _buildQuery()
	{
		$where = array();

		if ($this->search)
		{
			$where[] = 'LOWER(m.message) LIKE \'%'. $this->search. '%\' '
						. ' OR LOWER(m.subject) LIKE \'%'. $this->search. '%\''
						;
		}
		if($this->filter_catid){
			$where[] = 'category_id = '. $this->_db->quote($this->filter_catid)
						;
		}
		$where[]	= 'm.parent= 0';
		$where =( count($where) ) ? ' WHERE ' . implode( ' AND ', $where ) : '';
		$orderby = '';
		
		
		if (($this->filter_order) && ($this->filter_order_Dir))
		{
			$orderby 	= ' ORDER BY '. $this->filter_order .' '. $this->filter_order_Dir;
		}

		$this->_query = ' SELECT m.*, cat.title AS category_name, ced.name AS contact_name, u.name AS user_name, u.username '
							. ', (SELECT COUNT(mc.id) FROM #__contact_enhanced_messages as mc WHERE mc.parent = m.id) AS replies '
							. ', (SELECT mf.value FROM #__contact_enhanced_message_fields as mf WHERE message_id=m.id AND mf.field_type = '.$this->_db->Quote('multiplefiles').' LIMIT 1) AS attachments '
						. ' FROM #__contact_enhanced_messages m'
						. ' INNER JOIN #__contact_enhanced_details ced ON ced.id = m.contact_id '
						. ' INNER JOIN #__categories cat ON cat.id = m.category_id '
						. ' LEFT JOIN #__users u ON u.id = m.from_id '
						
						. $where
						. $orderby
						;
        	
		return $this->_query;	
	}
	

	function getData() 
	{
 		if (empty($this->_data))
 		{
			$query = $this->_buildQuery();
 	    	$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
		}
	
		//echo '<pre>'; print_r($this->_db->getQuery()); exit;
		return $this->_data;
	}	

	function getList()
	{
		// table ordering
		$lists['order_Dir']	= $this->filter_order_Dir;
		$lists['order']		= $this->filter_order;

		// search filter
		$lists['search']= $this->search;
		
		$lists['catid'] = JHTML::_('list.category',  'filter_catid', 'com_contact_enhanced_details', intval( $this->filter_catid ) );
		
		return $lists;
	}

	function getTotal()
	{
		// Load the content if it doesn't already exist
		if (empty($this->_total))
		{
			$query = $this->_buildQuery();
			$this->_total = $this->_getListCount($query);	
		}
		
		return $this->_total;
	}

	function getPagination()
	{
		// Load the content if it doesn't already exist
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination($this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
		}
		
		return $this->_pagination;
	}
	
	function getDataToExport() 
	{
		$query = $this->_buildQuery();
		$this->_db->setQuery($query);
     	$this->_data = $this->_db->loadAssocList();

		//echo '<pre>'; print_r($this->_db->getQuery()); exit;
		/*for($i=0;$i < count($this->_data); $i++){
			$query	= 'SELECT * FROM #__contact_enhanced_message_fields '
					. 	' WHERE message_id ='.$this->_data[$i]->id
				//	.	' ORDER BY ordering '
						;
			
			$this->_data[$i]->cf	 =  $this->_getList($query);

		}*/
		//echo '<pre>'; print_r($this->_data); exit;
		return $this->_data;
	}	
}// class
