<?php

// Implementation of hook_help()
function mailbuild_help($section) {
  switch ($section) {
    case 'admin/modules#description':
      $output = t('Create mailbuild.com email subscription form');
      break;
  }
  return $output;
}

// Implementation of hook_menu()
function mailbuild_menu($may_cache){
  if($may_cache){
    $items[] = array(
      'path' => 'mailbuild',
      'title' => t('mailbuild confirmation'),
      'callback' => 'mailbuild_page',
      'access' => user_access('access content'),
      'type' => MENU_CALLBACK);   
    $items[] = array(
      'path' => 'mailbuild/soap',
      'title' => t('mailbuild soap subscription'),
      'callback' => 'mailbuild_soap_form',
      'access' => user_access('access content'),
      'type' => MENU_CALLBACK);   
  }
  return $items;
}

function mailbuild_page($action = ''){
  switch($action){
    case 'signup':
      $title = 'Newsletter Signup';
      $action = variable_get('mailbuild_form_action', '');
      $name = variable_get('mailbuild_form_name', '');
      $email = variable_get('mailbuild_form_email', '');
      $body = variable_get('mailbuild_signup_text', '')
            . theme('mailbuild_form',$action,$name,$email);
      break;
    case 'subscribed':
      $title = variable_get('mailbuild_subscribed_title', 'Thank You');
      $body = variable_get('mailbuild_subscribed_body', '<p><strong>You have just been sent an email to confirm your email address.</strong></p><p>Please click on the link in this email to confirm your subscription.</p>');
      break;
    case 'confirmed':
      $title = variable_get('mailbuild_confirmed_title', 'Thank You');
      $body = variable_get('mailbuild_confirmed_body', '<p>Your subscription has been confirmed and you have been added to our list. You will hear from us soon.</p>');
      break;
    default:
      return drupal_not_found();
  }
  
  drupal_set_title($title);
  return $body;
}

// Implementation of hook_block().
function mailbuild_block($op = 'list', $delta = 1, $edit = array()) {
  global $user;

  $suffix = $delta ? '_' . $delta : '';
  
  switch ($op) {
    case 'list':
      for($i = 0; $i < variable_get('mailbuild_blocks', 1); $i++){
        $blocks[$i]['info'] = t('Mailbuild Signup Form') . ' (' .$i .')';
      }
      
      return $blocks;
    break;
    
    case 'configure':
      $form['mailbuild_form_title'.$suffix] = array(
        '#type' => 'textfield',
        '#title' => t('Block Title'),
        '#default_value' => variable_get('mailbuild_form_title'.$suffix,t('Newsletter Signup')),
      ); 
      $form['mailbuild_form_text'.$suffix] = array(
        '#type' => 'textarea',
        '#title' => t('Form text'),
        '#default_value' => variable_get('mailbuild_form_text'.$suffix,''),
      ); 
      $form['mailbuild_form_action'.$suffix] = array(
        '#type' => 'textfield',
        '#title' => t('Action'),
        '#default_value' => variable_get('mailbuild_form_action'.$suffix, ''),
      );
      $form['mailbuild_form_name'.$suffix] = array(
        '#type' => 'textfield',
        '#title' => t('Name Field'),
        '#default_value' => variable_get('mailbuild_form_name'.$suffix, ''),
      );
      $form['mailbuild_form_email'.$suffix] = array(
        '#type' => 'textfield',
        '#title' => t('Email Field'),
        '#default_value' => variable_get('mailbuild_form_email'.$suffix, ''),
      );
      return $form;
      
    case 'save':
      $vars = array(
        'mailbuild_form_title',
        'mailbuild_form_text',
        'mailbuild_form_action',
        'mailbuild_form_name',
        'mailbuild_form_email',
      );
      foreach($vars as $var){
        variable_set($var . $suffix, $edit[$var.$suffix]);
      }  
      break;
      
    case 'view':
      $action = variable_get('mailbuild_form_action'.$suffix, '');
      $name = variable_get('mailbuild_form_name'.$suffix, '');
      $email = variable_get('mailbuild_form_email'.$suffix, '');
      $text = variable_get('mailbuild_form_text'.$suffix, '');
      $title = variable_get('mailbuild_form_title'.$suffix,t('Newsletter Signup'));
      if($title != '<none>'){
        $block['subject'] = $title;
      }
      $block['content'] = theme('mailbuild_block_form',$action,$name,$email,$text);
      return $block; 
    break;
  }
}
  
function theme_mailbuild_form($action, $name, $email){
  return <<<FORM
<form action="$action" method="post">
  <div class="form-item">
    <label for="$name">Name:</label>
    <input type="text" name="$name" id="$name" class="form-text" />
  </div>
  <div class="form-item">
    <label for="$email">Email:</label>
    <input type="text" name="$email" id="$email" class="form-text" />
  </div>
  <input type="submit" value="Subscribe" class="form-submit" />
</form>
FORM;
}
  
function theme_mailbuild_block_form($action,$name,$email,$text){
  return <<<FORM
<p>$text</p>
<form action="$action" method="post">
  <div class="form-item">
    <label for="$name">Name:</label>
    <input type="text" name="$name" id="$name" class="form-text" />
  </div>
  <div class="form-item">
    <label for="$email">Email:</label>
    <input type="text" name="$email" id="$email" class="form-text" />
  </div>
  <input type="submit" value="Subscribe" class="form-submit" />
</form>
FORM;
}

function mailbuild_settings(){
  $form['mailbuild_blocks'] = array(
    '#type' => 'select',
    '#title' => t('Number of Blocks'),
    '#default_value' => variable_get('mailbuild_blocks', 1),
    '#options' => drupal_map_assoc(range(1, 10)),
  );
  $form['signup']['mailbuild_signup_text'] = array(
    '#type' => 'textarea', 
    '#title' => t('Sign up form text'), 
    '#default_value' => variable_get('mailbuild_signup_text', ''),
  );    
  $form['step1'] = array(
    '#type' => 'fieldset',
    '#title' => t('Initial Confirmation Page'),
    '#collapsible' => false,
    '#description' => '<p>This is the Initial Confirmation Page. It can be viewed '.l('here','mailbuild/subscribed').'</p>',
  );
  $form['step1']['mailbuild_subscribed_title'] = array(
    '#type' => 'textfield', 
    '#title' => t('Title'), 
    '#default_value' => variable_get('mailbuild_subscribed_title', 'Thank You'),
  );
  $form['step1']['mailbuild_subscribed_body'] = array(
    '#type' => 'textarea', 
    '#title' => t('Body'), 
    '#default_value' => variable_get('mailbuild_subscribed_body', '<p><strong>You have just been sent an email to confirm your email address.</strong></p><p>Please click on the link in this email to confirm your subscription.</p>'),
  );
  $form['step3'] = array(
    '#type' => 'fieldset',
    '#title' => t('Secondary Confirmation Page'),
    '#collapsible' => false,
    '#description' => '<p>This is the Initial Confirmation Page. It can be viewed '.l('here','mailbuild/subscribed').'</p>',
  );
  $form['step3']['mailbuild_confirmed_title'] = array(
    '#type' => 'textfield', 
    '#title' => t('Title'), 
    '#default_value' => variable_get('mailbuild_confirmed_title', 'Thank You'),
  );
  $form['step3']['mailbuild_confirmed_body'] = array(
    '#type' => 'textarea', 
    '#title' => t('Body'), 
    '#default_value' => variable_get('mailbuild_confirmed_body', '<p>Your subscription has been confirmed and you have been added to our list. You will hear from us soon.</p>'),
  );
  $form['form'] = array(
    '#type' => 'fieldset',
    '#title' => t('Form Settings'),
  );
  $form['form']['mailbuild_form_action'] = array(
    '#type' => 'textfield',
    '#title' => t('Action'),
    '#default_value' => variable_get('mailbuild_form_action', ''),
  );
  $form['form']['mailbuild_form_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name Field'),
    '#default_value' => variable_get('mailbuild_form_name', ''),
  );
  $form['form']['mailbuild_form_email'] = array(
    '#type' => 'textfield',
    '#title' => t('Email Field'),
    '#default_value' => variable_get('mailbuild_form_email', ''),
  );
  
  
  $form['api'] = array(
    '#type' => 'fieldset',
    '#title' => t('API Settings'),
  );
  $form['api']['mailbuild_sitename'] = array(
    '#type' => 'textfield',
    '#title' => t('Sitename'),
    '#default_value' => variable_get('mailbuild_sitename', ''),
  );
  $form['api']['mailbuild_apikey'] = array(
    '#type' => 'textfield',
    '#title' => t('API Key'),
    '#default_value' => variable_get('mailbuild_apikey', ''),
  );
  $form['api']['mailbuild_listid'] = array(
    '#type' => 'textfield',
    '#title' => t('List ID'),
    '#default_value' => variable_get('mailbuild_listid', ''),
  );
  return $form;
}

function _mailbuild_webform_submit($form_values,$name_id,$email_id){
  $url = variable_get('mailbuild_form_action', '');
  $name = variable_get('mailbuild_form_name', 'mb-name');
  $email = variable_get('mailbuild_form_email', 'mb-email');
  $params = array(
    $name => (is_numeric($name_id)?$form_values['submitted'][$name_id]:$name_id),
    $email => $form_values['submitted'][$email_id],
  );
  $data = drupal_query_string_encode($params);
  $result = drupal_http_request($url.'?'.$data);
  
  if (($result->code == 200) || ($result->code==302 && $result->redirect_code==200)) {
    drupal_set_message(variable_get('mailbuild_subscribed_body', '<p><strong>You have just been sent an email to confirm your email address.</strong></p><p>Please click on the link in this email to confirm your subscription.</p>')); 
  }else{
    drupal_set_message('Error signing up for newsletter');
    //drupal_set_message('<pre>'.print_r($result,true).'</pre>');
  }
}

function mailbuild_subscribe($name, $email){
  $params = array(
    variable_get('mailbuild_form_name', 'mb-name') => $name,
    variable_get('mailbuild_form_email', 'mb-email') => $email,
  );
  $data = drupal_query_string_encode($params);
  $result = drupal_http_request(variable_get('mailbuild_form_action', '').'?'.$data);
  
  if (($result->code == 200) || ($result->code==302 && $result->redirect_code==200)) {
    drupal_set_message(variable_get('mailbuild_subscribed_body', '<p><strong>You have just been sent an email to confirm your email address.</strong></p><p>Please click on the link in this email to confirm your subscription.</p>'));
  }else{
    drupal_set_message('Error signing up for newsletter');
  }
}
  
function mailbuild_soap_form(){
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name')
  );
  $form['email'] = array(
    '#type' => 'textfield',
    '#title' => t('Email')
  );
  $form['sitename'] = array(
    '#type' => 'value',
    '#value' => variable_get('mailbuild_sitename',''),
  );
  $form['apikey'] = array(
    '#type' => 'value',
    '#value' => variable_get('mailbuild_apikey',''),
  ); 
  $form['listid'] = array(
    '#type' => 'value',
    '#value' => variable_get('mailbuild_listid',''),
  ); 
  
  $form[] = array(
    '#type' => 'submit',
    '#value' => 'Subscribe',
  );

  return drupal_get_form('mailbuild_soap_form', $form);
}

function _mailbuild_soap_form_submit($form_id, $form_values){
  $url = "http://{$form_values['sitename']}.createsend.com/api/api.asmx";
  
  $headers = array(
    'Content-Type' => 'text/xml; charset=utf-8',
    'SOAPAction'   => '"http://api.createsend.com/api/Subscriber.Add"',
  );
  
  $data = '<?xml version="1.0" encoding="utf-8"?>'
        . '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
        . ' xmlns:xsd="http://www.w3.org/2001/XMLSchema"'
        . ' xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'
        . '  <soap:Body>'
        . '    <Subscriber.Add xmlns="http://api.createsend.com/api/">'
        . '      <ApiKey>'.$form_values['apikey'].'</ApiKey>'
        . '      <ListID>'.$form_values['listid'].'</ListID>'
        . '      <Email>'.$form_values['email'].'</Email>'
        . '      <Name>'.$form_values['name'].'</Name>'
        . '    </Subscriber.Add>'
        . '  </soap:Body>'
        . '</soap:Envelope>';

  $result = drupal_http_request($url, $headers, 'POST', $data);
  
  drupal_set_message('<pre>'.htmlspecialchars(var_export($result,true)).'</pre>');
  drupal_set_message('<pre>'.$url.'</pre>');

  return('mailbuild/soap');
}

function mailbuild_soap_form_submit($form_id, $form_values){
  require_once('SOAP/Client.php');
  require_once(drupal_get_path('module','mailbuild').'/mailbuild_soap.inc');

  $url = "http://{$form_values['sitename']}.createsend.com/api/api.asmx";
  $service = new WebService_api_apiSoap($url);
  $result = $service->AddSubscriber($form_values['apikey'], $form_values['listid'], $form_values['email'], $form_values['name']);

  // Is result a PEAR_Error?
  if (get_class($result) == 'pear_error'){
    drupal_set_message($result->message,'error');
  }else{
    drupal_set_message('<pre>'.print_r($result,true).'</pre>');
  }

  return('mailbuild/soap');
}

