<?/*
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 'ticket.php';
  require_once 'person.php';
  require_once 'comment.php';
  require_once 'crypt.php';
  require_once 'config.php';
  require_once 'email.php';
  require_once 'server_functions.php';

  globalize_request_keys('action', 'ticket_id', 'comment_count',
    'send_old_comments', 'query_id', 'template_id', 'to', 'subject',
    'comments', 'send_internal', 'send_user', 'send_support', 'send_other',
    'message_log', 'cc', 'bcc');

  if ($action == 'Cancel') {
    redirect("../ticket/edit_ticket?ticket_id=$ticket_id&query_id=$query_id",1);
    exit;
  }

  $email = new Email ();
  $ticket_p = new Ticket ();
  $person_p = new Person ();
  $comment = new Comment ();
  $crypt = new Crypt ();
  $config = new Config ();

  $enc_tid = $crypt->encrypt ($ticket_id);
  $domain = $config->Get ('email_domain');
  $return_email = $enc_tid.'@'.$domain;

  $errors = array ();
  $to_pid = array();

  $send = 0;
  $close = 0;
  $INTERNAL = 'Y';

  $ticket = $ticket_p->Info_by_Ticket_ID ($ticket_id);
  $user_person_id = $ticket->Get ('user_person_id');

  $comment_id_list = $comment->List_By_Ticket_CRM ($ticket_id);
  $total_comments = count($comment_id_list);

  if (!$comment_count) $comment_count = $total_comments;

  $person = $person_p->Info_by_Person_ID ($user_person_id);
  $user_email = strtolower( $person->Get('email') );

  if (ereg('Send',$action)) {
    $send = 1;
    if ($action == 'Send and Close') $close = 1;
  }

  if ($send and !$comments) {
    $errors[] = "You clicked send but don't have any text.";

  } elseif ($send and ($comment_count != $total_comments)) {
    $errors[] = "Someone has modified this ticket from underneath you.  If you wish to continue hit the back button, copy your text, then hit back again and click the email button.  Now paste in your text once more.";

  } elseif ($send) {

    $support_persons = $person_p->List_By('',2);

    $to_addresses = array();
    $cc_addresses = array();
    $bcc_addresses = array();
    $all_addresses = array();

    foreach (preg_split ('/(,|;)/', $to) as $addy) {
      if (!$addy) continue;
      $to_addresses[] = $addy;
      $all_addresses[] = $addy;
    }

    foreach (preg_split ('/(,|;)/', $cc) as $addy) {
      if (!$addy) continue;
      $cc_addresses[] = $addy;
      $all_addresses[] = $addy;
    }

    foreach (preg_split ('/(,|;)/', $bcc) as $addy) {
      if (!$addy) continue;
      $bcc_addresses[] = $addy;
      $all_addresses[] = $addy;
    }

    if (!count($all_addresses)) $errors[] = 'No emails specified';

    foreach ($all_addresses as $addy) {
      list ($e, $n) = $addy;
      if (!$e) $errors[] = "Invalid email ($addy)";
    }

    ## if we are sending to 1 person lets see if they have a person_id
    ## so we can identify the email as specifically to them so when they
    ## reply we are 99% sure it was from them

    if (count($all_addresses) == 1) {
      $single_addy = strtolower($all_addresses[0]);

      if ($user_email == $single_addy) {
        $from_individual = $user_person_id;
        $INTERNAL = 'N';

      } else {
        foreach ($support_persons as $rec) {
          if (strtolower($rec['email']) == $single_addy) {
            $from_individual = $rec['person_id'];
            break;
          }
        }
      }
    }


    ## if any address anywhere has the ticket submitter's address the comment
    ## is not internal

    if ($INTERNAL == 'Y') {
      foreach ($all_addresses as $addy) {
        if ($user_email == strtolower($addy)) {
          $INTERNAL = 'N';
          break;
        }
      }
    }

    if (!count($errors)) {
      $ret_cid = $comment->Add (array (
        'comments' => $comments,
        'person_id' => $REMOTE_USER,
        'updated_by' => $REMOTE_USER,
        'ticket_id' => $ticket_id,
        'internal' => $INTERNAL,
      ));

      if ($ret_cid and $close) {
       $ticket->Set ('status', 'Closed');
       $ticket->Update ();
      }

      if ($from_individual) {
        $enc_tid_pid = $crypt->encrypt ($ticket_id.'|'.$from_individual);
        $return_email = $enc_tid_pid.'@'.$domain;
      }

      $header_ary = array ();
    
      $header_ary[] = "From: \"".$config->Get ('Email Sig')."\" <$return_email>";
      $header_ary[] = "Reply-To: \"".$config->Get ('Email Sig')."\" <$return_email>";
      $header_ary[] = "Return-Path: \"".$config->Get ('Email Sig')."\" <$return_email>";

      if ($cc) $header_ary[] = "Cc: ".implode(', ', $cc_addresses);
      if ($bcc) $header_ary[] = "Bcc: ".implode(', ', $bcc_addresses);
      if (!$subject) $subject = "Support Ticket $ticket_id";

      $mail_txt = "$comments\n$message_log";

      if ($INTERNAL == 'Y') {
	foreach (array('Status', 'Problem', 'Browser', 'Source') as $s) {
	  $mail_txt .= "\n\n$s: ".$ticket->Get (strtolower($s))."\n";
	}

	$mail_txt .= "Account ID: ".$ticket->Get ('account_id')."\n";
	$mail_txt .= "Extra Info: ".$ticket->Get ('info1')."\n";
	$mail_txt .= "Extra Info: ".$ticket->Get ('info2')."\n";
	$mail_txt .= "First Name: ".$person->Get ('first_name')."\n";
	$mail_txt .= "Last Name: ".$person->Get ('last_name')."\n";
	$mail_txt .= "Company: ".$person->Get ('company')."\n";
	$mail_txt .= "Phone: ".$person->Get ('work_phone')."\n";
	$mail_txt .= "Email: ".$person->Get ('email')."\n";
      }

      if (mail ($to, $subject, $mail_txt, join ("\n", $header_ary))) {
        $url = redirect ("../ticket/edit_ticket?ticket_id=$ticket_id&query_id=$query_id", 1, 1);
        header ("Location: $url");
        return;
      } else {
        $joined_headers = join('\n',$header_ary);
        $errors[] = "Something went wrong sending the mail message.  Function call was mail('$to', '$subject', [mail text omitted], '$joined_headers')";
      }
    }
  }
    
  require_once 'dd.php';

  $sess_info = '?'.session_name().'='.session_id();
?>

<script type="text/javascript">
<!--
  function openit(sURL){
newwindow=open(sURL,"rlrpopupnav","width=420,height=240,directories=no,location=no,menubar=no,scrollbars=yes,status=no,toolbar=no,resizable=no,left=10%,top=10%,screenX=10%,screenY=10%");
}
//-->
</script>

<form name="email_form" action="<?php print $_SERVER['PHP_SELF']; ?>" method="post">

<?php
  foreach (array (
    'ticket_id',
    'send_old_comments',
    'query_id',
    'template_id',
  ) as $set) {
    print '<input type="hidden" name="'.$set.'" value="'.$$set.'" />'."\n";
  }
?>
<div class="athenatitleshadow">Compose Email<div class="athenatitle">Compose Email</div></div>
<br />
<table class='emailbox' cellpadding="4" border="0" cellspacing="0" width="100%">
<tr>
<td colspan='2' nowrap="nowrap" class="ftremail">

<table cellpadding="0" border="0" cellspacing="0">
<tr>
<td valign='middle'><input type="submit" name="action" class="btn-on" value="Send and Close" />&nbsp;&nbsp;</td>
<td valign='middle'><input type="submit" name="action" class="btn-off" value="Send without Closing" />&nbsp;&nbsp;</td>
<td valign='middle'><input type="submit" name="action" class="btn-off" value="Cancel" /></td>
</tr>
</table>

</td>
</tr>

<?php

  if (!$to) $to = $user_email;
  if (!$subject) $subject = "Support Ticket $ticket_id";

  print <<<EOF

<tr bgcolor="#eeeeee">
  <td class='textsm'></td>
  <td valign="bottom" class='textsm'><font class='addresseslnk'><a href="javascript:openit('address_book_popup.php$sess_info','address_book')" class='nobold'>Insert addresses</a> from Address Book</font></td>
</tr>
<tr bgcolor="#eeeeee">
  <td align='right' valign="middle" class='atextmed'><a href="javascript:openit('address_book_popup.php$sess_info','address_book')">To:</a></td>
  <td><input type="text" class='textsm' name="to" size='40' style="width:45em" value="$to"/></td>
</tr>
<tr bgcolor="#eeeeee">
  <td align='right' valign="middle" class='emailpad'><a class='atextmed' href="javascript:openit('address_book_popup.php$sess_info','address_book')">Cc:</a></td>
  <td class='emailpad'>

<table cellpadding="0" border="0" cellspacing="0">
<tr>
<td nowrap="nowrap"><input type="text" class='textsm' name="cc" size='17' style="width:20em" /></td>
<td class='atextmed' valign="middle">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:openit('address_book_popup.php$sess_info','address_book')">Bcc:</a>&nbsp;&nbsp;</td>
<td><input class='textsm' type="text" name="bcc" size='17' style="width:20em" /></td>
</tr>
</table>

  </td>
</tr>

<tr bgcolor="#eeeeee">
  <td align='right' class='email'><b class='atextmed'>Subject:<b></td>
  <td class='email'><input class='textsm' type="subject" name="subject" size='40' style="width:45em" value="$subject"/></td>
</tr>

<tr bgcolor="#dddddd">
<td class='emailtxtboxtop' valign='top' align='right' class='atextbig'><b class='atextmed'>Message:<b>
</td>
<td class='emailtxtboxtop'>

<input type="hidden" name="comment_count" value="$comment_count" />
<textarea name="comments" cols="80" rows="7" class="emailtxtboxtop" wrap="soft">
$comments
EOF;

  if (!$comments) {
    $name = $person->Get ('last_name');

    if ($more_name = $person->Get ('first_name')) $name = $more_name.' '.$name;

    print "Dear $name,\n\n";

    if ($template_id) {
      require_once 'template.php';
      $template = new Template ();
      $template->Get_Info ($template_id);
      print $template->Get ('template_text');
    }

    print "\n\nSincerely,\n\n";

    $email_sig = $config->Get ('Email Sig');
    $ext_sig = $config->Get ('extended_email_sig');

    if ($email_sig) print "$email_sig\n\n";
    if ($ext_sig) print "$ext_sig\n\n";

    $url = $config->Users_URL($enc_tid);

    print "\n\nTo review the status of your ticket, or if you have any further questions,\ncomments, or problems, please visit the following web address:\n$url\n";

  }
?>

</textarea>
</td></tr>
<tr bgcolor='#dddddd'>

<?php
  $comment_type = array();
  if ($send_internal) $comment_type[] = 'internal';
  if ($send_user) $comment_type[] = 'user';
  if ($send_support) $comment_type[] = 'support';
  if ($send_other) $comment_type[] = 'other';

  if (!$message_log && count($comment_type)) {
?>

<td class='emailtxtboxbottom' valign='top' align='right'><b class='atextmed'>Comments:<b></td>
<td class='emailtxtboxbottom'>
<textarea name="message_log" cols="80" rows="7" class="emailtxtboxbottom" wrap="soft">
<?php
    print $email->Make_Eyecatch()."\n\n";
  
    for ($i=$total_comments-1; $i>=0; $i--) {
      $a = $comment_id_list[$i];
  
      ## Here's where we prune out unwanted commentary.
      ## I think this ought to be a function.
      if ($a['internal'] == 'Y') {
        $ctype = 'internal';
      } elseif ($a['person_id'] == $user_person_id) {
        $ctype = 'user';
      } elseif (!$a['is_in_crm']) {
        $ctype = 'other';
      } else {
        $ctype = 'support';
      }
 
      if (!in_array($ctype,$comment_type)) continue;
  
      print 'On '.$a['created_date'].' ';
  
      if ($a['person_id'] == $a['user_person_id']) {
        print $a['first_name'].' '.$a['last_name'];
      } else {
        print $config->Get ('Email Sig');
      }
  
      print " wrote:\n".$a['comments']."\n\n";
    }
    print "</textarea>\n";
  }


  if (count($errors)) {
    foreach ($errors as $e) {
      print "<font class=\"errors\">$e</font><br />\n";
    }
  }

?>
 </td>
</tr>

<tr>
<td colspan='2' nowrap="nowrap" class="ftremail">

<table cellpadding="0" border="0" cellspacing="0">
<tr>
  <td valign='middle'><input type="submit" name="action" class="btn-on" value="Send and Close" />&nbsp;&nbsp;</td>
  <td valign='middle'><input type="submit" name="action" class="btn-off" value="Send without Closing" />&nbsp;&nbsp;</td>
  <td valign='middle'><input type="submit" name="action" class="btn-off" value="Cancel" /></td>
</tr>
</table>

</td>
</tr>

</table>

</form>

