<?php
require_once('modules/Iframeapp/Iframeapp.php');
class DispatchData {
  public $url;

  private function get_email_address_info($bean) {
    $sugar_email = '';
    $invalid_email = 0;
    $opt_out = 0;
    if (isset($bean->emailAddress->addresses)) {
      foreach( $bean->emailAddress->addresses as $item ) {
        if( $item['primary_address'] == 1 ) {
          $sugar_email = $item['email_address'];
          $invalid_email = $item['invalid_email'];
          $opt_out = $item['opt_out'];
          break;
        }
      }
    }
    return array($sugar_email, $invalid_email, $opt_out);
  }

  /**
   * The API URL will be the same scheme://host:port as the iframe URL, but the
   * endpoint will always be at /listener.php. Set the API URL endpint based on
   * the passed-in URL and return the query
   */
  private function set_url_and_get_query_string($iframe_src) {
    // parse_url($url,PHP_URL_PORT) will return nothing if no port is specified
    $port = parse_url($iframe_src, PHP_URL_PORT) ? ':' . parse_url($iframe_src, PHP_URL_PORT) : '';

    // set the URL based on parsed scheme, replacing path/query w/ listener.php
    $this->url = parse_url($iframe_src, PHP_URL_SCHEME)
      . '://'
      . parse_url($iframe_src, PHP_URL_HOST)
      . $port
      . '/listener.php';

    return parse_url($iframe_src, PHP_URL_QUERY);
  }

  public function ProcessMod($bean, $event, $arguments) {

    static $called_inbox25 = 0;
    $timestamp1 = strtotime('now') + date('Z');
    $action_type = 'Import';
    $mass_called = 0;

    // if we've already fired, exit now
    if($called_inbox25 == 1) {
      return TRUE;
    }

    if(isset($_REQUEST['__sugar_url']) && strpos($_REQUEST['__sugar_url'],'/MassUpdate')){
      $action_type = 'mass_update';
      $mass_called = 1;
    }

    if(
      (isset($_REQUEST['action']) && $_REQUEST['action'] == 'Step4' || $mass_called)
      && !$called_inbox25
    ) {
      $_SESSION['import_id'] = uniqid();
      $_SESSION['timestamp_inbox'] = $timestamp1;
      $called_inbox25 = 1;
      $GLOBALS['log']->debug($action_type . " Called by INBOX25:session_timestamp: " . $_SESSION['timestamp_inbox']);
      $postdata = array(
        'sugar_module' => $bean->module_dir,
        'sugar_id' => $bean->id,
        'action_type' => $action_type,
        'action_time' => $timestamp1,
        'import_id' =>$_SESSION['import_id'],
      );
      $ret = $this->sendData($postdata, '');
    }
    elseif($event == 'after_relationship_add' || $event == 'after_relationship_delete') {
      $called_inbox25 = 1;
      $postdata = array(
        'sugar_module' => $bean->module_dir,
        'sugar_id' => $bean->id,
        'action_type' => $event,
        'action_time' => $timestamp1,
      );
      $ret = $this->sendData($postdata, '');
    }
    elseif(isset($_REQUEST['action']) && $_REQUEST['action']=='Undo') {
      $postdata = array(
        'sugar_module' => $bean->module_dir,
        'sugar_id' => $bean->id,
        'action_type' => 'Undo_Import',
        'action_time' => $_SESSION['timestamp_inbox'],
        'import_id' => $_SESSION['import_id'],
      );
      $ret = $this->sendData($postdata, '');
    }
    else {
      $iframe_src = Iframeapp::get_config_url();
      if($iframe_src && Iframeapp::get_logic_hook_enabled()) {

        list($sugar_email, $invalid_email, $opt_out) = $this->get_email_address_info($bean);
        $query_string = $this->set_url_and_get_query_string($iframe_src);

        if($bean->deleted == 1) {
          $action_type = 'delete';
        }
        elseif(empty($bean->fetched_row)) {
          $action_type = 'add';
        }
        else {
          $action_type = 'edit';
        }

        $postdata = array(
          'sugar_module' => $bean->module_dir,
          'sugar_id' => $bean->id,
          'sugar_email' => $sugar_email,
          'invalid_email' => $invalid_email,
          'opt_out' => $opt_out,
          'action_type' => $action_type
        );

        $ret = $this->sendData($postdata, $query_string);
      }
    }
  }

  /**
   * called from the custom ImportController kept in custom/modules/Import/controller.php
   */
  public function set_undo($mod){
    $postdata = array(
      'sugar_module' => $mod,
      'sugar_id' => '',
      'action_type' => 'Undo_Import',
      'action_time' => $_SESSION['timestamp_inbox'],
      'import_id' => $_SESSION['import_id'],
    );
    $GLOBALS['log']->debug("Undo Called For INBOX25:session_timestamp: " . $_SESSION['timestamp_inbox']);
    $ret = $this->sendData($postdata, '');
  }

  public function ProcessRel($bean, $event, $arguments) {
    $iframe_src = Iframeapp::get_config_url();
    if($iframe_src && Iframeapp::get_logic_hook_enabled()) {
      list($sugar_email, $invalid_email, $opt_out) = $this->get_email_address_info($bean);
      $query_string = $this->set_url_and_get_query_string($iframe_src);

      $postdata = array(
        'sugar_module' => $arguments['module'],
        'sugar_id' => $arguments['id'],
        'sugar_email' => $sugar_email,
        'invalid_email' => $invalid_email,
        'opt_out' => $opt_out,
        'action_type' => 'rel',
      );
      $ret = $this->sendData($postdata,$query_string);
    }
  }

  public function ProcessDelRel($bean, $event, $arguments) {
    $iframe_src = Iframeapp::get_config_url();
    if($iframe_src) {
      $query_string = $this->set_url_and_get_query_string($iframe_src);
      $postdata = array(
        'sugar_module' => $arguments['module'],
        'sugar_id' => $arguments['id'],
        'action_type' => 'rel'
      );
      $ret = $this->sendData($postdata,$query_string);
    }
  }

  private function sendData($postdata, $query_string) {

    // build the query string if we didn't get one
    if(empty($query_string)) {
      $iframe_src = Iframeapp::get_config_url();
      if($iframe_src && Iframeapp::get_logic_hook_enabled()) {
        $query_string = $this->set_url_and_get_query_string($iframe_src);
      }
    }

    foreach( $postdata as $fldname=>$fldval ) {
      $query_string .= '&' . $fldname . '=' . $fldval;
    }

    $ch = curl_init($this->url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    $return_data = curl_exec($ch);
    curl_close($ch);
    return $return_data;
  }
}
