<?php 

define(LOOPFUSE_LEAD_CAPTURE_PATH, '/webrecorder/post');

/**
 * Allow for editing webforms with SugarCRM connection information and modifying the
 * each webform to post to SugarCRM.
 */
function loopfusewebform_form_alter($form_id, &$form) {
	
	// handle webform client forms (instances of webforms that are submitted)	
	// webform names client forms with the pattern web_form_client_form_$nid, use this knowledge to
	// manipulate the forms that webform displays
	if ( ereg('^webform_client_form_', $form_id) ) {
		
		global $base_url;
		$node = $form['#parameters'][1];
				
		// only deal with this form if it is supposed to go to LoopFuse
		if ( empty($node->lf_form_id) ) {
			return ;
		}

		// change the action to submit directly to sugar
		$form['#action'] = loopfuse_get_base_url() . LOOPFUSE_LEAD_CAPTURE_PATH;	
		
		// flatten the submitted fields so that sugar can handle them	
		$form['submitted']['#tree'] = FALSE;
		
		// add the configured properties to set the lead source and the SugarCRM user
 		$form['cid'] = array(
	  	'#type' => 'hidden',
	    '#value' => loopfuse_get_account(),
	  );

    $form['formid'] = array(
      '#type' => 'hidden',
      '#value' => $node->lf_form_id,
    );

		// all leads coming from this form should be treated as new on the SugarCRM side
		$form['status'] = array(
      '#type' => 'hidden',
      '#value' => 'New',
    );
		
		// Provide both Opt-In and Opt-Out options to allow for different choices when mapping 
		// from LoopFuse to the CRM system
		if ( isset($form['submitted']['email_opt_in'])) {
			// add it to the submitted fieldset for consistency with when the user adds an 
			// Opt-Out field directly
			$form['submitted']['email_opt_out'] = array(
	      '#type' => 'hidden',
	      '#value' => 'yes',
	    );
		}

		// use the redirect/confirmation data from the original web form to tell SugarCRM where
		// to redirect the user this is the same logic that the client_form_submit function 
		// uses to determine whether or not to redirect
	  if (valid_url(trim($node->confirmation), true)) {
	    $redirect = trim($node->confirmation);
	  }
	  elseif (preg_match('/^internal:/', $node->confirmation)) {
	    $path = preg_replace('/^internal:/', $base_url .'/', $node->confirmation);
	    $redirect = trim($path);
	  }
	  else {
			// create an absolute URL for the SugarCRM lead capture page to send the user back to
	    $redirect = url('node/'. $node->nid .'/done', NULL, NULL, TRUE);
	  }
	
    $form['redirect'] = array(
      '#type' => 'hidden',
      '#value' => $redirect,
    );
	}
	
	// handle editing of webform nodes
	elseif ( $form_id == 'webform_node_form' ) {		
	
		  /* Collapse the email info on the page assuming that it is going to be a SugarCRM form */
		  $form['mailsettings']['#collapsed'] = TRUE;

		  /* Start LoopFuse Settings Form */
		  $loopfuse_form['loopfusesettings'] = array(
		    '#type' => 'fieldset',
		    '#title' => t('LoopFuse Integration Settings'),
		    '#collapsible' => TRUE,
		    '#collapsed' => FALSE,
		    '#weight' => -2,
		  );

		  $loopfuse_form['loopfusesettings']['lf_form_id'] = array(
		    '#type' => 'textfield',
		    '#title' => t('Form ID of the LoopFuse lead capture form to use'),
		    '#default_value' => empty($form['#node']->lf_form_id) ? '' : $form['#node']->lf_form_id,
		    '#description' => t('The LoopFuse Form ID configured to receive this lead.'),
		  );
		  /* End LoopFuse settings form */

		  // integrate the sugar form into the form
		  $pos = array_search('mailsettings', array_keys($form)) + 1;
		  $form = array_merge(array_slice($form, 0, $pos), $loopfuse_form, array_slice($form, $pos));
	
	}

}

/**
 * Intercept operations on the webform node to assure that the SugarCRM fields are tracked.
 */
function loopfusewebform_nodeapi(&$node, $op, $form = NULL, $page = NULL) {	
	if ( $node->type == 'webform') {
		switch ($op) {
			case 'insert':
			case 'update':
				if ( !empty($node->lf_form_id) ) {
					// store the LoopFuse configuration fields
					$result = db_query("DELETE FROM {loopfusewebform} where vid = %d", $node->vid);
					$result = db_query("INSERT INTO {loopfusewebform} (vid, lf_form_id) " .
    					 							 "VALUES (%d, '%s')", $node->vid, $node->lf_form_id);
				}
				break;
			case 'validate':
				if ( !empty($node->lf_form_id) ) {
					if (!preg_match('/^[[:xdigit:]]{8}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{12}$/', trim($node->lf_form_id))) {
						form_set_error('lf_form_id', t('The LoopFuse Form ID must be a valid LoopFuse Form ID of the form XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX'));
			  	}
				}
				break;	
			case 'load':
				$result = db_query("SELECT lf_form_id from {loopfusewebform} ".
			           					 "WHERE vid = %d", $node->vid); 
				// either their is 0 or 1, if we have one then add it to the node
				$row = db_fetch_array($result);
			  if ( !empty($row) ) {
					$node->lf_form_id = $row['lf_form_id'];
				}
				break;
		}
	}
}
