<?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!

// Find email field

$email = '';
$fields = $form->{'fields'};
foreach($fields as $field) {
  if ($field->{'field_datatype'} == 'email') {
    $email = $field->{'field_value'};
    break;
  }
}
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 = json_encode(array(
	      'apikey' => $mailchimp_api_key, 
	      'id' => $mailchimp_list_id, 
	      'email' => array('email' => $email)
	      ));
$options = array(
		 'http' => array(
				 'protocol_version' => 1.1,
				 'method' => 'POST',
				 'header' => "Content-type: application/json\r\n".
				             "Connection: close\r\n" .
				             "Content-length: " . strlen($data) . "\r\n",
				 'content' => $data,
				 ),
		 );

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

?>
