<?php

require_once("FormSmarts_OAuth.php");
require_once("FormSmarts_OAuth_Server.php");
require_once("FormSmarts.php");

$form = json_decode(file_get_contents("php://input"));

// Normalize response data for OAuth

$norm = new FormSmartsParameterNormalizer();
$norm_params = $norm->normalize($form);

// Authenticate request with OAuth 1.0

$server = new TestOAuthServer(new MockOAuthDataStore());
$hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
$server->add_signature_method($hmac_method);

try {
  $req = OAuthRequest::from_request(Null, Null, $parameters=$norm_params);
  list($consumer, $token) = $server->verify_request($req);
} catch (OAuthException $e) {
  die();
}

// We've established the request is really originating from FormSmarts.
// We can now start to do something useful...
// Note: Do NOT insert your own code before this line!

$fields = $form->{'fields'};

// 5th field is the opt-in checkbox
if ($fields[4]->{'field_value'} == 'no') die();

// Find email field

$email = '';
$fname = '';
$lname = '';

foreach($fields as $field) {
  if ($field->{'field_datatype'} == 'email') {
    $email = $field->{'field_value'};
  } elseif ($field->{'field_name'} == 'First Name') {
    $fname = $field->{'field_value'};
  } elseif ($field->{'field_name'} == 'Last Name') {
    $lname = $field->{'field_value'};
  }
}
if (! $email) die();

// Enter your MailChimp API key and list ID below:

$mailchimp_api_key = "";
$mailchimp_list_id = "";

// Prepare request
list(, $dc) = explode('-', $mailchimp_api_key);
$endpoint = 'https://'.$dc.'.api.mailchimp.com/2.0/lists/subscribe.php';
$data = array(
	      'apikey' => $mailchimp_api_key, 
	      'id' => $mailchimp_list_id, 
	      'email' => array('email' => $email)
	      );
if ($fname && $lname) $data['merge_vars '] = array('FNAME' => $fname, 'LNAME' => $lname);
$json_data = json_encode($data);
$options = array(
		 'http' => array(
				 'protocol_version' => 1.1,
				 'method' => 'POST',
				 'header' => "Content-type: application/json\r\n".
				             "Connection: close\r\n" .
				             "Content-length: " . strlen($json_data) . "\r\n",
				 'content' => $json_data,
				 ),
		 );

// Submit request to MailChimp
$context = stream_context_create($options);
$result = file_get_contents($endpoint, false, $context);

?>
