<?php
/**
 * @version $Id$
 * @package    Contact_Enhanced
 * @subpackage Controllers
 * @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.controller');

class Contact_EnhancedsControllerMessages extends JController
{
	var $cid;
	var $_messageQueue	= array();

	function __construct()
	{
		parent::__construct();
		// Register Extra tasks
		$this->registerTask( 'add'  	, 	'edit' );
		$this->registerTask( 'unpublish', 	'publish');

		$this->cid = JRequest::getVar( 'cid', array(0), '', 'array' );
		JArrayHelper::toInteger($this->cid, array(0));
	}
	function _buildQuery()
	{
		$this->_query = 'UPDATE #__contact_enhanced_messages'
		. ' SET published = ' . (int) $this->publish
		. ' WHERE id IN ( '. $this->cids .' )'		
		;
		return $this->_query;     
	}
	function edit()
	{
		$this->view();
	}
	
	function view()
	{
		JRequest::setVar( 'view', 'message' );
		JRequest::setVar( 'layout', 'view'  );
		JRequest::setVar('hidemainmenu', 1);
		parent::display();
	}
	
	function reply()
	{
		JRequest::setVar( 'view', 'message' );
		JRequest::setVar( 'layout', 'reply'  );
		JRequest::setVar('hidemainmenu', 1);
		parent::display();
	}

	function cancel()
	{
		$msg = JText::_( 'Operation Cancelled' );
		$this->setRedirect( 'index.php?option=com_contact_enhanced&view=messages&controller=messages', $msg );
	}
	function publish()
	{
		$cid		= JRequest::getVar( 'cid', array(), '', 'array' );
		$this->publish	= ( $this->getTask() == 'publish' ? 1 : 0 );

		JArrayHelper::toInteger($cid);
		if (count( $cid ) < 1)
		{
			$action = $this->publish ? 'publish' : 'unpublish';
			JError::raiseError(500, JText::_( 'Select an item to' .$action, true ) );
		}

		$this->cids = implode( ',', $cid );

		$query = $this->_buildQuery();
		$db = &JFactory::getDBO();
		$db->setQuery($query);
		if (!$db->query())
		{
			JError::raiseError(500, $db->getErrorMsg() );
		}
		$link = 'index.php?option=com_contact_enhanced&view=messages&controller=messages';
		$this->setRedirect($link, $msg);
	}

	function saveMessage($returnType='redirect')
	{
		$date		=& JFactory::getDate();
		$user		=& JFactory::getUser();
		$post		= JRequest::get('post');
		$parent		= JRequest::getVar('parent');

		$cid		= JRequest::getVar( 'cid', array(0), 'post', 'array' );
		$post['id'] 	= (int) $cid[0];
		
		//new message
		if($post['id'] ==0){
			$post['replied_by']	= 0;
			$post['from_id']	= $user->id;
			$post['date']		= $date->toFormat();
		}

		$model = $this->getModel( 'Message' );
		if ( ($model->store($post)) ) {
			$msg = JText::_( 'Item Saved' );

			$row =& $model->getTable('message');
			$row->load($parent);

			if($parent AND isset($row->id)){
				 
				$row->reply_date	= $date->toMySQL();
				$row->replied_by	= $user->id;
				$model->store($row);
				
			}
			
			
			if($returnType == 'bool'){
				JApplication::enqueueMessage($msg,'message');
				return true;
			}
		} else {
			$msg = JText::_( 'Error Saving Item' );
			if($returnType == 'bool'){
				JApplication::enqueueMessage($msg,'error');
				return false;
			}
		}

		$link = 'index.php?option=com_Contact_Enhanced&view=Messages';
		$this->setRedirect( $link, $msg );
	}

	function remove()
	{
		$model = $this->getModel('Message');
		if(!$model->delete()) {
			$msg = JText::_( 'Error Deleting Item' );
		} else {
			$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );
			foreach($cids as $cid) {
				$msg .= JText::_( 'Item Deleted '.' : '.$cid );
			}			
		}

		$this->setRedirect( 'index.php?option=com_Contact_Enhanced&view=messages&controller=messages', $msg );
	}
	
	function send_email(){
		$this->saveMessage('bool');
		$subject	= JRequest::getVar('subject');
		$from_name	= JRequest::getVar('from_name');
		$from_email	= JRequest::getVar('from_email');
		$email_to	= JRequest::getVar('email_to');
		$email_cc	= JRequest::getVar('email_cc');
		$email_bcc	= JRequest::getVar('email_bcc');
		$message	= JRequest::getVar('message');
		
		jimport('joomla.mail.helper');
		$mail = JFactory::getMailer();
		$mail->setBody( $message);
		$mail->addRecipient($email_to );
		$mail->setSender( array( $from_email, $from_name ) );
		$mail->setSubject( $subject );
		if($email_cc){
			$mail->addCC($email_cc );
		}
		if($email_cc){
			$mail->addBCC($email_bcc );
		}

		
		if($mail->Send()){
			$msg=(JText::_( 'Thank you for your e-mail'));
		}else{
			JApplication::enqueueMessage(JText::_( 'Email not sent, please notify administrator'),'error');
			$msg=(JText::_( 'Email not sent, please notify administrator'));
		}
		
		if(JRequest::getVar('tmpl')){
			JRequest::setVar('tmpl','component');
			//return ;
			echo '<script>alert("'.$msg.'");window.parent.location.reload();</script>'; exit;
		}else{
			$this->setRedirect('index.php?option='.COMPONENT_FOLDER.'&controller=messages',$msg);
		}
	
	}
	
	function saveCustomFields(){
		$catid			= JRequest::getVar('catid');
		$customFields	= cehelper::getCustomFields($catid);
		cehelper::getSubmitedFields($customFields);
		$id				= JRequest::getVar('cid');
		foreach($customFields as $cf){
			$field	=& JTable::getInstance('messagefields', 'Table');
			// sanitise id field
			$field->id = (int) JRequest::getVar('cf_'.$cf->id.'_id');
			$field->message_id	= $id[0];
			$field->field_id	= $cf->id;
			$field->field_type	= $cf->type;
			$field->value		= $cf->getMySQLOutput();
			$field->modified	= 1;
			
			
			if (!$field->store()) {
				JError::raiseError(500, $field->getError() );
			}
			//echo '<pre>'; print_r($customFields); echo '</pre>'; //exit;
		}
		$this->setRedirect('index.php?option='.COMPONENT_FOLDER.'&controller=messages&view=messages', JText::_( 'Item Saved' ));
	} 

	function exportToCSV(){
		$model			= $this->getModel('Messages');
		$rows			= $model->getDataToExport();
		$catid			= JRequest::getVar('filter_catid');
		$customFields	= cehelper::getCustomFields($catid);
		$db				= &JFactory::getDBO();
		
		require_once(JPATH_COMPONENT.DS.'helpers'.DS.'csvhandler.php');
		$csv	= new csvHandler();
		
		$headerLine		= array(
									JText::_('message_id'),		JText::_('parent'), 	JText::_('from_name')
								,	JText::_('from_email'),		JText::_('from_id'), 	JText::_('email_to')
								,	JText::_('email_cc'),		JText::_('email_bcc'), 	JText::_('subject')
								,	JText::_('contact_id'),		JText::_('category_id'),JText::_('date')
								,	JText::_('reply_date'),		JText::_('replied_by'),	JText::_('message')
								,	JText::_('user_ip'),		JText::_('status'),		JText::_('category_name')
								,	JText::_('contact_name'), 	JText::_('user_name'),	JText::_('username')
								,	JText::_('replies'),		JText::_('attachments')
							);
		
		$excludeVars	= array('subject','email','name','multiplefiles','recipient');
		foreach($customFields as $cf){
			if(!in_array($cf->type,$excludeVars)){
				$headerLine[]	= JText::_($cf->name); //JText::_($cf->name);
			}
		}
		//echo '<pre>'; print_r($customFields); exit;
		$csv->addRow($headerLine);
		
		foreach($rows AS $row){	
			//$line	= ceHelper::objectToArray($row);
			$line	= $row;
			$query	= 'SELECT mf.value, cf.name, cf.type,cf.id FROM #__contact_enhanced_message_fields mf '
					. 	' RIGHT OUTER JOIN #__contact_enhanced_cf cf ON cf.id = mf.field_id'
					. 	' WHERE message_id ='.$row['id']
					.	' ORDER BY cf.ordering ASC'
					;
			$db->setQuery($query);
			$recordedField		= $db->loadAssocList('id'); 
			//echo '<pre>'; print_r($recordedField); exit; 
			foreach($customFields as $cf){
				if(!in_array($cf->type,$excludeVars)){
					if(isset($recordedField[$cf->id]['value'])){
						$line[]	= ($recordedField[$cf->id]['value']); //JText::_($cf->name);	
					}else{
						$line[]	= '';
					}
				}
			}
			//echo '<pre>'; print_r($recordedField); exit;
			$csv->addRow($line);
		}
		//exit;
		echo $csv->render('contact_enhanced__'.date('Y-m-d_Hi').'.csv','UTF-8');
		//echo '<pre>'; print_r($recordedField); exit;
		exit;	
	}
	
	
}
