<?php

/*
osCommRes, Services Oline 
http://www.oscommres.com 
Copyright (c) 2005 osCommRes 

Freeway eCommerce 
http://www.zac-ware.com/freeway 
Copyright (c) 2007 ZacWare

Released under the GNU General Public License
*/
// Set flag that this is a parent file
	define( '_FEXEC', 1 );
	require('includes/application_top.php');
	require('includes/classes/order.php');
	require('includes/classes/currencies.php');
	$action = (isset($HTTP_POST_VARS['template_action']) ? tep_db_prepare_input($HTTP_POST_VARS['template_action']) : '');

	$select_template=(isset($HTTP_POST_VARS['template_id']) ? (int)$HTTP_POST_VARS['template_id'] :0);

	switch($action){
		case 'download':
		case 'print':
			$from = tep_db_prepare_input($HTTP_POST_VARS['from']);
			$subject = tep_db_prepare_input($HTTP_POST_VARS['subject']);

			$size=((int)$HTTP_POST_VARS["template_page_size"]==1)?600:500;
			$format=tep_db_prepare_input($HTTP_POST_VARS["template_page_format"]);
			$content="<html><body><%replace%></body></html>";
			
			$email_address=(isset($HTTP_POST_VARS["customers_email_address"])?tep_db_prepare_input($HTTP_POST_VARS["customers_email_address"]):'');
			$order_ids=(isset($HTTP_POST_VARS["search_ids"])?tep_db_prepare_input($HTTP_POST_VARS["search_ids"]):'');
			$message_content="";
						
			if ($email_address!="") {
			
				$customers_email_address = join("','",tep_db_prepare_input($email_address));

				$customer_query = tep_db_query("select c.customers_firstname, c.customers_lastname, c.customers_email_address, c.customers_password,c.customers_dob,c.customers_telephone,c.customers_fax, " .
												"a.entry_street_address,a.entry_city,a.entry_suburb,a.entry_postcode,a.entry_state,a.entry_country_id,a.entry_zone_id from " . TABLE_CUSTOMERS . " c, " .  TABLE_ADDRESS_BOOK . " a where c.customers_email_address in ('" . $customers_email_address . "') and c.customers_default_address_id=a.address_book_id");

				$merge_details=array();
				
				while($mail = tep_db_fetch_array($customer_query)){
					$message = tep_db_prepare_input($HTTP_POST_VARS['template_text']);

					if ($format=="txt"){
						$message=strip_tags($message,'<br>');
						$message=str_replace('<br>',chr(13) . chr(10),$message);
						$message=str_replace('<BR>',chr(13) . chr(10),$message);
					} else {
						$message="<table border='0' cellspacing=0 cellpadding=0 width='100%'><tr><td>" . $message . "<td></tr></table>";
					}
					$message_content.=$message . "\n";
				}
			} else if ($order_ids!=""){
				$fetch_orders=split(",",$order_ids);
				$merge_details=array();
				$currencies=new currencies();
				for ($icnt=0;$icnt<sizeof($fetch_orders);$icnt++){
					$message_content.="<table border=0 cellspacing=0 cellpadding=0 width='100%'><tr><td>";

					$products_ordered="";
					$order=new order($fetch_orders[$icnt],true);  
					$merge_details=array();
					$merge_details[ORDR_NO]=$fetch_orders[$icnt];
					$merge_details[ORDR_OL]=tep_catalog_href_link(FILENAME_ACCOUNT_HISTORY_INFO, 'order_id=' . $fetch_orders[$icnt], 'SSL', false);
					$merge_details[ORDR_OP]=strftime(DATE_FORMAT_LONG);
					$merge_details[ORDR_OM]=tep_db_output($order->info['comments']);
	
					$merge_details[ORDR_PO]=$products_ordered;
					$order_totals_str="";
					for ($i=0, $n=sizeof($order->totals); $i<$n; $i++) {
						$order_totals_str .= $order->totals[$i]['title'] . ' ' . $order->totals[$i]['text']  .  "<br>";
					}
					
					$merge_details[ORDR_OT]=$order_totals_str;
		
					$customer_query=tep_db_query("SELECT customers_firstname,customers_lastname from " . TABLE_CUSTOMERS . " where customers_id='" . (int)$order->customer['id'] . "'");
					$customer_result=tep_db_fetch_array($customer_query);
				
					//customer details
					$merge_details[CUST_CF]=$customer_result['customers_firstname'];
					$merge_details[CUST_CL]=$customer_result['customers_lastname'];
					$merge_details[CUST_CM]=$order->customer['company'];
					$merge_details[CUST_CT]=$order->customer['street_address'];
					$merge_details[CUST_CS]=$order->customer['suburb'];
					$merge_details[CUST_CC]=$order->customer['city'];
					$merge_details[CUST_CP]=$order->customer['postcode'];
					$merge_details[CUST_CE]=$order->customer['state'];
					$merge_details[CUST_CU]=$order->customer['country'];
					$merge_details[CUST_CO]=$order->customer['telephone'];
					$merge_details[CUST_CA]=$order->customer['email_address'];
				
					//Billing details
					$merge_details[BILL_NA]=$order->billing['name'];
					$merge_details[BILL_CM]=$order->billing['company'];
					$merge_details[BILL_CT]=$order->billing['street_address'];
					$merge_details[BILL_CS]=$order->billing['suburb'];
					$merge_details[BILL_CC]=$order->billing['city'];
					$merge_details[BILL_CP]=$order->billing['postcode'];
					$merge_details[BILL_CE]=$order->billing['state'];
					$merge_details[BILL_CU]=$order->billing['country'];
		
					//delivery details
					$merge_details[DELI_NA]=$order->delivery['name'];
					$merge_details[DELI_CM]=$order->delivery['company'];
					$merge_details[DELI_CT]=$order->delivery['street_address'];
					$merge_details[DELI_CS]=$order->delivery['suburb'];
					$merge_details[DELI_CC]=$order->delivery['city'];
					$merge_details[DELI_CP]=$order->delivery['postcode'];
					$merge_details[DELI_CE]=$order->delivery['state'];
					$merge_details[DELI_CU]=$order->delivery['country'];
		
					$merge_details[ORDR_PM]= $order->info["payment_method"];
					$merge_details[ORDR_PF]="";
					
					$message = tep_db_prepare_input($HTTP_POST_VARS['template_text']);
					reset($merge_details);					
					while(list($key,$value)=each($merge_details))
						$message=str_replace("%%" . $key  . "%%",$value,$message);
					
					if ($format=="txt"){
						$message=strip_tags($message,'<br>');
						$message=str_replace('<br>',chr(13) . chr(10),$message);
						$message=str_replace('<BR>',chr(13) . chr(10),$message);
					} else {
						$message=$message . "</td></tr></table>";
					}
					$message_content.=$message . "\n";
				}
		}
		if (strtolower($format)=="txt"){
			header('Content-type: application/text');
			header('Content-Disposition: attachment; filename="letter.txt"');
		} else if (strtolower($format)=="doc") {
			header('Content-type: application/vnd.ms-word');
			header('Content-Disposition: attachment; filename="letter.doc"');
		}
		echo $message_content;
		return;
	}
  if (isset($HTTP_POST_VARS['from'])) {

	  $from_email=tep_db_prepare_input($HTTP_POST_VARS["from"]);
	} else {
	  $from_email=tep_db_prepare_input($HTTP_SESSION_VARS["login_email"]);
	}
?>
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html <?php echo HTML_PARAMS; ?>>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
<title><?php echo TITLE; ?></title>
<link rel="stylesheet" type="text/css" href="includes/stylesheet.css">
<?php if ($action=="repost") tep_redirect_post(FILENAME_ADMIN_LETTERS,'',$values);?>
<script type="text/javascript" src="htmlarea/htmlarea.js"></script>
<script type="text/javascript" src="htmlarea/editor.js"></script>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF">

<!-- header //-->
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
<!-- header_eof //-->

<!-- body //-->
<table border="0" width="100%" cellspacing="2" cellpadding="2">
	<tr> 
<!-- body_text //-->
		<td width="100%" valign="top">
		<table border="0" width="100%" cellspacing="0" cellpadding="0">
			<tr>
				<td width="100%">
				<table border="0" width="100%" cellspacing="0" cellpadding="0">
					<tr>
					<td class="pageHeading"><?php echo HEADING_TITLE; ?></td>
					<td class="pageHeading" align="right"><?php echo tep_draw_separator('pixel_trans.gif', HEADING_IMAGE_WIDTH, HEADING_IMAGE_HEIGHT); ?></td>
					</tr>
				</table>
				</td>
			</tr>
			<tr>
				<td>
				<table border="0" width="100%" cellspacing="0" cellpadding="2">
				<?php				  
					if ( ($action == 'preview') && isset($HTTP_POST_VARS['customers_email_address']) ) {
						switch ($HTTP_POST_VARS['customers_email_address']) {
							case '***':
								$mail_sent_to = TEXT_ALL_CUSTOMERS;
								break;
							case '**D':
								$mail_sent_to = TEXT_NEWSLETTER_CUSTOMERS;
								break;
							default:
								$mail_sent_to = tep_db_prepare_input($HTTP_POST_VARS['customers_email_address']);
							break;
						}
						$merge_details=array(	TEXT_FN=>TEST_MAIL_FN,
												TEXT_LN=>TEST_MAIL_LN,
												TEXT_SN=>TEST_MAIL_SN,
												TEXT_SM=>TEST_MAIL_SM,
											);
					    // event registeration
						$message_text=tep_db_prepare_input($HTTP_POST_VARS['message']);
						while(list($key,$value)=each($merge_details))
							$message_text=str_replace("%%" . $key  . "%%",$value,$message_text);
						echo tep_draw_form('mail', FILENAME_MAIL, 'action=send_email_to_user');
				?>
				<tr>
					<td>
					<table border="0" width="100%" cellpadding="0" cellspacing="2">
						<tr>
							<td><?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?></td>
						</tr>
						<tr>
							<td class="smallText"><b><?php echo TEXT_CUSTOMER; ?></b><br><?php echo $mail_sent_to; ?></td>
						</tr>
						<tr>
							<td><?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?></td>
						</tr>
						<tr>
							<td class="smallText"><b><?php echo TEXT_FROM; ?></b><br><?php echo htmlspecialchars(stripslashes($from_email)); ?></td>
						</tr>
						<tr>
							<td><?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?></td>
						</tr>
						<tr>
							<td class="smallText"><b><?php echo TEXT_SUBJECT; ?></b><br><?php echo htmlspecialchars(stripslashes($HTTP_POST_VARS['subject'])); ?></td>
						</tr>
						<tr>
							<td><?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?></td>
						</tr>
						<tr>
							<td class="smallText"><b><?php echo TEXT_MESSAGE; ?></b><br><?php if (HTML_AREA_WYSIWYG_DISABLE_EMAIL == 'Enable') { echo (stripslashes($message_text)); } else { echo htmlspecialchars(stripslashes($message_text)); } ?></td>
						</tr>
						<tr>
							<td><?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?></td>
						</tr>
						<?php
						/* Re-Post all POST'ed variables */
							reset($HTTP_POST_VARS);
							while (list($key, $value) = each($HTTP_POST_VARS)) {
								if (!is_array($HTTP_POST_VARS[$key])) {
									echo tep_draw_hidden_field($key, htmlspecialchars(stripslashes($value)));
								}
							}
						?>
						<tr>
							<td align="right"><?php echo '<a href="' . tep_href_link(FILENAME_MAIL) . '">' . tep_image_button('button_cancel.gif', IMAGE_CANCEL) . '</a> ' . tep_image_submit('button_send_email.gif', IMAGE_SEND_EMAIL); ?></td>
						</tr>
						</form>
					</table>
					</td>
				</tr>
			</table>
			</td>
		</tr>
<?php
	} else {
?>
		<tr><?php echo tep_draw_form('letter_content', FILENAME_ADMIN_LETTERS, '','post'); ?>
		<td>
			<table border="0" cellpadding="0" cellspacing="2">
			<tr>
				<td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?></td>
			</tr>
			<?php
			$customers = array();	//
			$customer_string="";	// select customer box
			$message_text="";		//message_text from database
						

			$select_orders=array();

			$search_ids=(isset($HTTP_POST_VARS['search_ids'])?(int)$HTTP_POST_VARS['search_ids']:'');
			if ($search_ids!=''){
				$search_orders=split(",",(int)$HTTP_POST_VARS['search_ids']);
				
				$order_query=tep_db_query("SELECT distinct(customers_name) from " . TABLE_ORDERS . " where orders_id in(" . (int)$HTTP_POST_VARS['search_ids'] . ")");
				
				while($order_result=tep_db_fetch_array($order_query)){
					$customer_string.=$order_result["customers_name"] . ",";
				}
				$customer_string=substr($customer_string,0,-1);
				$message_query=tep_db_query("SELECT message_text from " . TABLE_EMAIL_MESSAGES . " where message_type='TEM'");
				$message_result=tep_db_fetch_array($message_query);
				$message_text=$message_result["message_text"];
			} else {
				$select_customers=array();
				if (isset($HTTP_POST_VARS['customers_email_address'])){
					$select_customers=&$HTTP_POST_VARS['customers_email_address'];
				}
				$mail_query = tep_db_query("select customers_email_address, customers_firstname, customers_lastname from " . TABLE_CUSTOMERS . " order by customers_lastname");
	
				$customer_string='<select name="customers_email_address[]" size=6 multiple>';
				while($customers_values = tep_db_fetch_array($mail_query)) {
					$customer_string.='<option value="' . $customers_values['customers_email_address'] . '" ';
					if (in_array($customers_values['customers_email_address'],$select_customers)) $customer_string.=' selected ';
					$customer_string.='>' . $customers_values['customers_lastname'] . ', ' . $customers_values['customers_firstname'] . ' (' . $customers_values['customers_email_address'] . ')</option>';
				}
				$customer_string.="</select>";
			}
			?>
			<tr>
				<td class="main" valign="top"><?php echo TEXT_CUSTOMER; ?></td>
				<td valign="top"><?php echo $customer_string;?></td>
			</tr>
			<tr>
				<td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?></td>
			</tr>
			<tr>
				<td class="main"><?php echo TEXT_FROM; ?></td>
				<td><?php echo tep_draw_input_field('from', $from_email,'size=40'); ?></td>
			</tr>
			<tr>
				<td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?></td>
			</tr>
			<tr>
				<td class="main"><?php echo TEXT_SUBJECT; ?></td>
				<td><?php echo tep_draw_input_field('subject',(isset($HTTP_POST_VARS['subject'])?tep_db_prepare_input($HTTP_POST_VARS['subject']):''),'size=40'); ?></td>
			</tr>
			<tr>
				<td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?></td>
			</tr>
			<tr>
				<td valign="top" class="main"><?php echo TEXT_MESSAGE; ?></td>
				<td><?php echo tep_draw_textarea_field('template_text', 'soft', '80', '24',$message_text,false . 'id="template_text"'); ?></td>
				<?php if (HTML_AREA_WYSIWYG_DISABLE_EMAIL == 'Enable') { ?>
						<script>initEditor('template_text');</script>
				<?php }
				?>
			</tr>
				<tr>
					<td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?></td>
				</tr>
				<?php 
					$page_size=array(array('id'=>'LT','text'=>"A4 (21*297mm)"),
									array('id'=>'LE','text'=>"American Legal (8.5*11inches)"));

					$page_format=array(array('id'=>"HTM",'text'=>"Html files(*.html)"),
									array('id'=>"TXT",'text'=>"Text files(*.txt)"),
									array('id'=>"DOC",'text'=>"Word files(*.doc)"),
									);
				?>
				<tr>
					<td class="main"><?php echo TEXT_PAGE_SIZE;?></td>
					<td class="main"><?php echo tep_draw_pull_down_menu("template_page_size",$page_size,$tInfo->template_page_size);?></td>
				</tr>
				<tr>
					<td><?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?></td>
				</tr>
				<tr>
					<td class="main"><?php echo TEXT_PAGE_FORMAT;?></td>
					<td class="main"><?php echo tep_draw_pull_down_menu("template_page_format",$page_format,$tInfo->template_page_format);?></td>
				</tr>
				<tr>
	                <td colspan="2" align="right">
					<?php 
						echo '<input type="hidden" name="search_ids" value="' . $search_ids . '">';
						echo '<input type="hidden" name="template_action" value="download">';
						echo '<a href="' . tep_href_link(FILENAME_CUSTOMERS) . '">' . tep_image_button('button_cancel.gif',IMAGE_CANCEL) . '</a>';
						echo '&nbsp;' . tep_image_submit('button_download.gif',IMAGE_DOWNLOAD);
						//echo '&nbsp;<img src="' . DIR_WS_LANGUAGES . $language . '/images/buttons/button_admin_print.gif" alt="' . IMAGE_PRINT . '" onClick="set_process(\'print\',2)" style="cursor:hand">';
					?>
					</td>
				</tr>
				</form>
			</table>
		</td>
		
	</tr>
<?php
  }
?>
<!-- body_text_eof //-->
        </table></td>
      </tr>
    </table></td>
  </tr>
</table>
<!-- body_eof //-->

<!-- footer //-->
<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
<!-- footer_eof //-->
</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
