<?/*
Copyright (C) 2003 Media Net Link, Inc. Danville, CA 94526 USA

This file is part of AthenaRMS.

AthenaRMS is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

AthenaRMS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/?>
<?php
  require_once 'db.php';
  require_once 'person.php';
  require_once 'ticket.php';
  require_once 'comment.php';
  require_once 'config.php';
  require_once 'crypt.php';
  require_once 'crm.php';
  require_once 'attribute_display.php';
  require_once 'email.php';
  require_once 'template.php';
  require_once 'server_functions.php';

  globalize_request_keys('subject', 'email', 'first_name', 'company',
    'last_name', 'work_phone', 'afile', 'comments', 'title', 'source_id',
    'problem_id', 'atts');

  $person = new Person ();
  $ticket = new Ticket ();
  $comment = new Comment ();
  $config = new Config ();
  $crypt = new Crypt ();
  $crm = new Crm ();

  $crm_id = $crm->CRM_ID_By_Host_Path ();

  $errors = array ();
  $fatal_error = 0;
  
  if (!$crm_id) {
    $errors[] = 
      "Unable to determine client, please use the provided email address.";
    error_out ();
  }

  $PERSON_FIELDS = array (
    'first_name',
    'last_name',
    'title',
    'company',
    'email',
    'work_phone',
  );

  $TICKET_FIELDS = array (
      'source_id',
      'problem_id',
      'crm_id',
      'subject',
  );

  $crm_rec = $crm->Select_by_CRM_ID ($crm_id);

  global $REMOTE_USER_CRM_ID;
  $REMOTE_USER_CRM_ID = $crm_id;

  $template = new Template ($dbi);

  if ($comments or $subject) {
 
    ## create person
    $add = array ('updated_by' => 'new feedback');
  
    foreach ($PERSON_FIELDS as $set) {
      $add[$set] = $$set;
    }
  
    $person_id = $person->Add ($add);
    if (!$person_id) {
      $errors[] = "Error adding new person: ".$person->error;
      error_out();
    }

    $add_ticket = array (
      'user_person_id' => $person_id,
    );
  
    foreach ($TICKET_FIELDS as $set) {
      $add_ticket[$set] = $$set;
    }
  
    foreach (array(
      'http_user_agent' => 'browser',
      'http_referer' => 'referring_url',
      'remote_addr' => 'remote_host',
      'account_id' => 0,
      'info1' => 0,
      'info2' => 0,
    ) as $k => $v) {
      if (!$v) $v = $k;

      if (isset($$k)) $add_ticket[$v] = $$k;
      else {
	$k = strtoupper($k);
	if (isset($$k)) $add_ticket[$v] = $$k;
	else {
	  if (array_key_exists($k, $_SERVER)) $add_ticket[$v] = $_SERVER[$k];
	}
      }
    }
  
    ## create ticket
    list ($ok, $ticket_id, $map_id) = $ticket->Add_Both ($add_ticket);

    ## create comment
    if ($ok) {
      $attv = new Attribute_Value ($dbi);
      if ($atts) $attv->add_cleared_att_vals ($ticket_id, $atts);
  
      $comment_id = $comment->Add (array (
        'comments' => $comments,
        'person_id' => $person_id,
        'ticket_id' => $ticket_id,
        'updated_by' => $person_id,
      ));

      if (!$comment_id) {
	$errors[] = "Error adding comment: ".$comment->error;
	$errors[] = "deleting person $person_id, ticket $ticket_id";
	if (!$ticket->Delete($ticket_id)) {
	  $errors[] = "Error deleting ticket $ticket_id: ".$ticket->error;
	}
        if (!$person->Delete($person_id)) {
	  $errors[] = "Error deleting person $person_id: ".$person->error;
	}
	error_out();
      }
    } else {
      ## Something bad happened creating ticket
      $errors[] = "Error creating new ticket: ".$ticket->error;
      $person->Delete($person_id);
      error_out();
    }

    ## save attachments
    if ($_FILES) {
      foreach ($_FILES as $f) {
        if (is_uploaded_file ($f['tmp_name'])) {
          $file = '';
          $fp = fopen ($f['tmp_name'], 'r');
          while (!feof ($fp)) {
            $file .= fread ($fp, 1000000);
          }
          fclose ($fp);
    
          unlink ($f['tmp_name']);
    
          if (!$comment->Save_Attachment ($comment_id, basename($f['name']), 
	      $f['type'], "new ticket - $person_id", $file)) {
            $errors[] = $comment->error;
	    if (!$comment->Delete($comment_id)) {
		$errors[] = "Error deleting comment: ".$comment->error;
	    }
	    if (!$ticket->Delete($ticket_id)) {
		$errors[] = "Error deleting ticket: ".$ticket->error;
	    }
	    if (!$person->Delete($person_id)) {
		$errors[] = "Error deleting person: ".$person->error;
	    }
	    error_out();
          }
        }
      }
    }

    $enc_ticket = $crypt->encrypt ($ticket_id);
    $url = $config->Users_URL($enc_ticket);

    $email_error = 0;

    ## try to email the results if something failed
    if (!$person_id or !$ticket_id or !$comment_id or count($errors)) {

      foreach ($PERSON_FIELDS as $param) {
        $email_txt .= $param.': '.$$param."\n";
      }
  
      foreach ($add_ticket as $k => $v) {
        $email_txt .= "$k: $v\n";
      }

      $email_txt .= "comments:\n$comments\n";

      $errors[] = "There was an error saving your feedback, it has been mailed to the support group -- pid $person_id tid $ticket_id cid $comment_id.";

      if ($athena_admin) {
	if (!mail ($athena_admin, 'Failed Feedback', $email_txt)) {
	  $errors[] = "To make matters worse, I was unable to send that email, please send email to __address_here__ or try again later.  Sorry for the inconvenience.";
	  $email_error = 1;
	}
      } else {
	$errors[] = "However, I could not send that email because no Athena admin was specified in athena.conf.";
	$email_error = 1;
      }
    }

    ## records were created or an email was sent at this point
    if (!$email_error) {

      if ($email and !$config->Value('no_new_ticket_user_confirmation')) {
        $emailo = new Email ();

        if ($emailo->Valid($email)) {

          $domain = $config->Get ('email_domain');

          $from_enc = $crypt->encrypt ($ticket_id.'|'.$person_id).'@'.$domain;
          $from_enc = '"'.$config->Get ('Email Sig')."\" <$from_enc>";

          include $template->load ('user_new_ticket_email_confirmation.php');

          $ok = $emailo->Send_Msg ($email, $subject, $mail_msg, $from_enc);

          if (!$ok) $errors[] = 'unable to send confirmation email.';
        }
      }

      ## check for 3rd party page to redirect to
      if ($redir_url = $crm_rec->Get ('confirmation_url')) {
        ob_clean ();
        header ("Location: $redir_url");
        exit;
      }

      require_once 'template.php';

      $template = new Template ($dbi);

      include $template->load ('confirm.php');

      return;
  
    }

  } else {
    $errors[] = 'neither comment or subject specified and one is required.';
  }

  if (count($errors)) error_out ();

  include $template->load ('input_form.php');


  function error_out () {
    global $errors;

    print "<pre>";
    print "<font size=\"+1\">submit.php debug</font>\nErrored out:\n";
    print_r($errors);
    print "</pre>";exit;

    if ($error_url = $_REQUEST[error_url]) {
      $dec_url = implode ('error_txt=', $errors);
  
      ## resend all get/post info
      foreach ($_REQUEST as $k => $v) {
        $dec_url .= "&$k=".rawurlencode($v);
      }

      header ("Location: $error_url?error_txt=$dec_url");
      exit;
    }
  
    #global $template;
    $template = new Template;
    global $crm_rec;

    include $template->load ('input_form.php');

    exit;
  }
?>
