<?php

//require_once("../../../../../../wp-config.php");
function storeAddress(){
	global $email, $fname, $lname, $wpdb, $fid, $MdlDb ;
	$res = $wpdb->get_results("SELECT * FROM ".$MdlDb->autoresponder." WHERE responder_id='1'");$res = $res[0];
	$responder_api_key = $res->responder_api_key;
	$data = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM ".$MdlDb->ar." WHERE frm_id = %d", $fid), 'ARRAY_A' );
   	$arr_mailchimp 	= maybe_unserialize( $data[0]['mailchimp'] );
	$responder_list_id = isset($arr_mailchimp['type_val'])?$arr_mailchimp['type_val']:'';
    $double_opt_in = isset($arr_mailchimp['double_optin']) ? $arr_mailchimp['double_optin'] : 0;
	if( $responder_list_id != '' ){
		// Validation

		$email = apply_filters('arf_set_email_for_mailchimp_from_outside',$email,$fid);

		if($email==""){ return "No email address provided"; }

		if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $email)) {
			return "Email address is invalid"; 
		}
		require_once('MCAPI.class.php');
		// grab an API Key from http://admin.mailchimp.com/account/api/
		$api = new MCAPI($responder_api_key);
		$api->useSecure(true);
		// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
		// Click the "settings" link for the list - the Unique Id is at the bottom of that page. 
		$list_id = $responder_list_id;
		$merge_vars = array('MERGE1'=>$fname, 'MERGE2'=>$lname,);

		$merge_vars = apply_filters('arf_mailchimp_additional_fields_from_outside',$merge_vars,$fid,$arr_mailchimp);

		$update_existing = apply_filters('arf_is_update_mailchimp_subscriber',false,$fid);

		if($api->listSubscribe($list_id, $email, $merge_vars,'html',$double_opt_in,$update_existing) === true) {
			//It worked!				
			//echo "ADDED SUCCESSFULLY"; exit;	
			return 'Success! Check your email to confirm sign up.';	
		}else{			
			// An error ocurred, return error message	
			return 'Error: ' . $api->errorMessage;
		}
	}
}
// If being called via ajax, autorun the function
storeAddress();
?>