<?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) {
  header("HTTP/1.1 401 Unauthorized");  
  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();

// require Constant Contact SDK
require_once 'src/Ctct/autoload.php';

use Ctct\ConstantContact;
use Ctct\Components\Contacts\Contact;
use Ctct\Components\Contacts\ContactList;
use Ctct\Components\Contacts\EmailAddress;
use Ctct\Exceptions\CtctException;

// Enter your Constant Contact API key and OAuth Access Token below:
$constant_contact_api_key = "";
$constant_contact_access_token = "";

$cc = new ConstantContact($constant_contact_api_key);

// check if contact already exists
$response = $cc->getContactByEmail($constant_contact_access_token, $email);
if (empty($response->results)) {
  // get contact lists
  $contact_lists = $cc->getLists($constant_contact_access_token);
  // contact doesn't exist, create it
  $contact = new Contact();
  $contact->addEmail($email);
  $contact->addList($contact_lists[0]); // arbitrarilly using the first contact list returned
  $cc->addContact($constant_contact_access_token, $contact, false);
}
?>
