<?php
/**
* @Copyright Copyright (C) 2010 Brent Laminack
* @license GNU/GPL http://www.gnu.org/copyleft/gpl.html
**/

// Set flag that this is a parent file since this is an ajax file and not directly tied to index.php
// yes, I know it's an awful lot of overhead. 

define( '_JEXEC', 1 );
define( 'DS', DIRECTORY_SEPARATOR );
$parts = explode( DS, dirname(__FILE__) );	

// pop up two levels to the real root
array_pop($parts);
array_pop($parts);
define( 'JPATH_BASE', implode( DS, $parts ) );

require_once ( JPATH_BASE . '/includes'.DS.'defines.php' );
require_once ( JPATH_BASE . '/includes'.DS.'framework.php' );

JDEBUG ? $_PROFILER->mark( 'afterLoad' ) : null;
$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();

// the work's all done here, getting the info and making the call to the MailChimp API
function send_to_mc(){
$email = isset($_POST['email'])?$_POST['email']:'';
$mid =  isset($_POST['mid'])?$_POST['mid']:'';
$first =  isset($_POST['first'])?$_POST['first']:'';
$last =  isset($_POST['last'])?$_POST['last']:'';
$ig =  isset($_POST['ig'])?$_POST['ig']:'';
$ig_struct = make_ig($ig);

global $mainframe;

        $db =& JFactory::getDBO();
	// Validation
	if(!$email){ 
		return "No email address provided"; 
	} 

	$query = "select params from #__modules where id = '$mid'";
        $db->setQuery( $query );
	if (null === ($raw_params = $db->loadResult())) {
                        JError::raiseWarning( 'SOME_ERROR_CODE', JText::_( 'Error Loading Params' ) . $db->getErrorMsg());
                        return false;
        }

	$params = new JParameter( $raw_params );
	$apikey = $params->get('mc_api_key');
	if(!$apikey){
		return("Couldn't find MailChimp API key");
	}

	// pull in the MailChimp API
	require_once('MCAPI.class.php');
	require_once('mod_mailchimp2_helper.php');
	$api = new MCAPI($apikey);
	$list = get_list($api, $params);

	if(!$list['id']){
		return 'Oops.. there don\'t appear any lists for you to subscribe to!';
	}

	$mergevars = $api->listMergeVars($list['id']);

	// finally! the Subscribe
	$merge_vars_togo = array();
	$err_tags = array();
	$err_names = array();
	foreach($mergevars as $mergevar){
		$tag = $mergevar['tag'];
		$err_tags[] = "/$tag/";
		$err_names[] = $mergevar['name'];
		if($tag == 'EMAIL') {
			continue;
		} else {
			if($_POST[$tag]){
				$merge_vars_togo[$tag]=$_POST[$tag];
			}
		}
	}
	if($ig_struct){
		$merge_vars_togo['GROUPINGS']=$ig_struct;
	}
	if(!count($merge_vars_togo)) {
		$merge_vars_togo = '';
	}
	if($api->listSubscribe($list['id'], $email, $merge_vars_togo) === true) {
		// It worked!	
		return 'Success! Check your email to confirm sign up.';
	} else {
		// An error ocurred, return error message	
		return 'Error: ' . preg_replace($err_tags, $err_names, $api->errorMessage);
	}
	
}

function make_ig($all_igs){

	/* need to end up with:
	Set Interest Groups by Grouping. 
	Each element in this array should be an array containing the "groups" parameter which contains 
	a comma delimited list of Interest Groups to add. 
	Commas in Interest Group names should be escaped with a backslash. ie, "," => "\," 
	and either an "id" or "name" parameter to specify the Grouping - get from listInterestGroupings()

	merge_vars = array ('GROUPINGS' => array('id'=> group_id1, 'groups'=>'ecommerce,marketing,joomla 1.8',
						'id'=> group_id2, 'groups'=>'male');
				.......
	*/

	$tmp=preg_replace('/,$/', '', $all_igs);

	$parts = explode(',', $tmp);

	$parts[] = 'mcig_0';	// end of file 

	$ret = array();

	$group = array();
	for($i = 0; $i<count($parts); $i++){
		$this_part = $parts[$i];
		if(preg_match('/^mcig_/', $this_part)){
			// finish previous array
			if($igs and $group_id){
				$group['id'] = $group_id;
				$igs = preg_replace('/,$/', '', $igs);
				$group['groups'] = $igs;
				$ret[] = $group;
				$group = array();
				$id = '';
				$igs = '';
			}
			$group_id = preg_replace('/^mcig_/', '', $this_part);
		} else {
			$igs .= $this_part . ',';
		}
	}
	return($ret);
}	// end of make_ig 

// If being called via ajax, autorun the function with email address and module id
if($_POST['ajax']){ echo send_to_mc(); }
?>
