<?php

/*

  osCommRes, Services Online
  http://www.oscommres.com

  Copyright (c) 2005 osCommRes

  Released under the GNU General Public License
  
  Freeway eCommerce from ZacWare
http://www.zac-ware.com/freeway

Copyright 2007 ZacWare Pty. Ltd
*/
// Set flag that this is a parent file
	define( '_FEXEC', 1 );
	require('includes/application_top.php');
	$input_params=&$HTTP_SESSION_VARS["rep_params"];
	$action = (isset($HTTP_GET_VARS['action']) ? $HTTP_GET_VARS['action'] : '');
	$customer_ids=(isset($HTTP_GET_VARS['customer_ids']) ? $HTTP_GET_VARS['customer_ids'] : '0');
	if($customer_ids==0)
	$customer_ids=(isset($HTTP_POST_VARS['customer_ids']) ? $HTTP_POST_VARS['customer_ids'] : '0');
	$product_id=(isset($HTTP_GET_VARS['product_id']) ? $HTTP_GET_VARS['product_id'] : '');
	$params=(isset($HTTP_GET_VARS['params'])?$HTTP_GET_VARS['params']:'');
	//$cat_id=(isset($HTTP_GET_VARS['cat_id'])?$HTTP_GET_VARS['cat_id']:'');
		$cat_id=(isset($input_params['sel_category'])?$input_params['sel_category']:'');
	//$params=(isset($input_params['check_products'])?$input_params['check_products']:'');
	$params_array=split("_",$params);
	$id_flag=$params_array[0];
	$param_ids=$params_array[1];
	$sel_pids=$params_array[2];
		?>

	<?php if($product_id!="") // mail to Bacorderd customer
	{
		$customer_ids="";
		$swhere=(isset($HTTP_GET_VARS['swhere']) ? $HTTP_GET_VARS['swhere'] : '');
		$swhere=str_replace("\'","'",$swhere);
		$order_sql="select cus.customers_id from " .  TABLE_ORDERS . " o," . TABLE_CUSTOMERS . " cus," . TABLE_ORDERS_PRODUCTS . " ord where ord.orders_id=o.orders_id and o.customers_id=cus.customers_id and ord.products_type='P' and ord.orders_products_status=4  and o.orders_status=2 and ord.products_id=" . $product_id . $swhere;
		$customer_rec = tep_db_query($order_sql);
		while($rec = mysql_fetch_assoc($customer_rec)) {
			$customer_ids.=$rec["customers_id"] . ",";
		}
		if ($customer_ids!="")
			$customer_ids=substr($customer_ids,0,-1);
	} 
	$cus_sql2="";
	if($id_flag=="oid" && $param_ids!="")
		$cus_sql2="select distinct(o.customers_id) from " . TABLE_ORDERS . " o," . TABLE_ORDERS_PRODUCTS . " ord where ord.orders_id=o.orders_id and  ord.orders_products_id in(" . $param_ids . ")  and o.orders_status=2 " . $cuswhere;
	else if($id_flag=="pid" && $param_ids!="")
		$cus_sql2="select distinct(o.customers_id) from " . TABLE_ORDERS . " o," . TABLE_ORDERS_PRODUCTS . " ord where ord.orders_id=o.orders_id and ord.products_id in(" . $param_ids . ")  and o.orders_status=2 ";
	
	if($cus_sql2!="") // mail to Bacorderd customer
	{
		$customer_ids="";
		$customer_rec = tep_db_query($cus_sql2);
		while($rec = mysql_fetch_assoc($customer_rec)) {
			$customer_ids.=$rec["customers_id"] . ",";
		}
		if ($customer_ids!="")
			$customer_ids=substr($customer_ids,0,-1);
	}		
	if ( ($action == 'send_email_to_user') && $customer_ids!="" && !isset($HTTP_POST_VARS['back_x']) ) {
		$mail_query = tep_db_query("select customers_firstname, customers_lastname, customers_email_address, customers_password from " . TABLE_CUSTOMERS . " where customers_id in(" . $customer_ids . ")");
		$mail_sent_to = BACKORDERED_CUSTOMERS;
		$from = tep_db_prepare_input($HTTP_POST_VARS['from']);
		$subject = tep_db_prepare_input($HTTP_POST_VARS['subject']);
		$message = tep_db_prepare_input($HTTP_POST_VARS['message']);

		//Let's build a message object using the email class
		$mimemessage = new email(array('X-Mailer: osCommerce'));
		// add the message to the object
		tep_set_time_limit(1000);
		while ($mail = tep_db_fetch_array($mail_query)) {
			$message_detail=$message;
			$merge_details=array(	TEXT_FN=>$mail['customers_firstname'],
									TEXT_LN=>$mail['customers_lastname'],
									TEXT_SN=>STORE_NAME,
									TEXT_SM=>STORE_OWNER,
									TEXT_SE=>STORE_OWNER_EMAIL_ADDRESS,
									TEXT_LA=>tep_catalog_href_link(FILENAME_AUTOLOGIN,'email=' . $mail['customers_email_address'] . '&id=' . $mail['customers_password'])
								);
			while(list($key,$value)=each($merge_details))
				$message_detail=str_replace("%%" . $key  . "%%",$value,$message_detail);
	
			$message_text=strip_tags($message_detail,'<br>');
			$message_text=str_replace('<br>',chr(13) . chr(10),$message_text);
			$message_text=str_replace('<BR>',chr(13) . chr(10),$message_text);
			 //echo $mail['customers_email_address'];

			if (HTML_AREA_WYSIWYG_DISABLE_EMAIL == 'Disable') {
				$mimemessage->add_text($message_text);
			} else {
				$mimemessage->add_html($message_detail,$message_text);
			}
			$mimemessage->build_message();
			$mimemessage->send($mail['customers_firstname'] . ' ' . $mail['customers_lastname'], $mail['customers_email_address'], '', $from, $subject);
		} ?>
		<?php set_orders_products_status('4'); ?>
		<script>
		window.opener.doReport('1');
		window.close();
		
		</script>
		
	<?php  exit;} 

	if (isset($HTTP_POST_VARS['from'])) {
		$from_email=$HTTP_POST_VARS["from"];
	} else {
		$from_email=$HTTP_SESSION_VARS["login_email"];
	}
	function set_orders_products_status($status_flag)
	{
	global $param_ids,$id_flag;
	if($id_flag=='oid' && $param_ids!="") {
		tep_db_query("UPDATE " . TABLE_ORDERS_PRODUCTS . " set orders_products_status=" . $status_flag . " where orders_products_id in(" . $param_ids . ")");
		$asql="select orders_id,products_name from " . TABLE_ORDERS_PRODUCTS . " where orders_products_id in(" . $param_ids . ") and orders_products_status=". $status_flag . " order by orders_id";
	}
	else if($id_flag=="pid" && $param_ids!="") {
		tep_db_query("UPDATE " . TABLE_ORDERS_PRODUCTS . " set orders_products_status=" . $status_flag . " where products_id in(" . $param_ids . ") and orders_products_status<3");
		$asql="select orders_id,products_name from " . TABLE_ORDERS_PRODUCTS . " where products_id in(" . $param_ids . ") and orders_products_status=". $status_flag . " order by orders_id";
	}
	if($asql!="")
	{
	//============status history=========
	  $sql_res=tep_db_query($asql);
	  $prev_ord_id=0;
	  $product_names="";
	  while($row=tep_db_fetch_array($sql_res))
	  {
		if($prev_ord_id!=$row['orders_id'])
		{
			if($product_names!="")
			{
				$insert_array=array("orders_id"=>$prev_ord_id,
								"orders_status_id"=>4,
								"date_added"=>date("Y-m-d h:i:s"),
								"customer_notified"=>1,
								"comments"=>sprintf(TEXT_STATUS_HISTORY_PRODUCT_BACKORDER_COMMENTS,substr($product_names,0,-1)),
								"user_added"=> TEXT_ADMIN);
				tep_db_perform(TABLE_ORDERS_STATUS_HISTORY,$insert_array);
			}
			$product_names="";
			$prev_ord_id=$row['orders_id'];
		}
		$product_names.=$row['products_name'] . ",";
	  }
		if($product_names!="")
		{
			$insert_array=array("orders_id"=>$prev_ord_id,
							"orders_status_id"=>4,
							"date_added"=>date("Y-m-d h:i:s"),
							"customer_notified"=>1,
							"comments"=>sprintf(TEXT_STATUS_HISTORY_PRODUCT_BACKORDER_COMMENTS,substr($product_names,0,-1)),
							"user_added"=> TEXT_ADMIN);
			tep_db_perform(TABLE_ORDERS_STATUS_HISTORY,$insert_array);
		}
	}
}
?>
<!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">
<script language="javascript" src="includes/menu.js"></script>
<script type="text/javascript" src="htmlarea/htmlarea.js"></script>
<script type="text/javascript" src="htmlarea/editor.js"></script>
<script language="JavaScript" src="htmlarea/validation.js"></script>

</head>
<body  marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF">
<!-- 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['customer_ids']) ) {
    $mail_sent_to = TEXT_ALL_BACKORDERED_CUSTOMERS;
    $merge_details=array(TEXT_FN=>TEST_MAIL_FN,
                          TEXT_LN=>TEST_MAIL_LN,
			              TEXT_SN=>TEST_MAIL_SN,
    			          TEXT_SM=>TEST_MAIL_SM,
			              TEXT_SE=>TEST_MAIL_SE,
			              TEXT_LA=>TEST_MAIL_LA
			             );
   
    $message_text=$HTTP_POST_VARS['message'];
	while(list($key,$value)=each($merge_details))
       $message_text=str_replace("%%" . $key  . "%%",$value,$message_text);	
?>
          <tr><?php echo tep_draw_form('mail', FILENAME_MAIL_BACKORDER, 'action=send_email_to_user&cat_id=' . $cat_id .'&params=' . $params); ?>
            <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(STORE_OWNER_EMAIL_ADDRESS); ?></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>
              <tr>
                <td>
				<?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 tep_image_submit('button_back.gif', IMAGE_BACK, 'name="back"')  . '&nbsp;' . tep_image_submit('button_send_email.gif', IMAGE_SEND_EMAIL); 
						?>
						</td>
                    </tr>
                </table></td>
             </tr>
            </table></td>
          </form>
		</tr>
<?php
  } else {
?>
<script language="javascript">
	function AddField(){
	 var select_field;
	 var select_id;
	 if (document.mail.fields.selectedIndex<=-1) return;
	 select_id=document.mail.fields.options[document.mail.fields.selectedIndex].value;
	 if (select_id.length>2) return;
	 select_field="%%" + document.mail.fields.options[document.mail.fields.selectedIndex].innerHTML + "%%";
	 select_field=select_field.replace("&nbsp;&nbsp;","");
     editor.insertHTML(select_field);
	}
</script>
          <tr><?php echo tep_draw_form('mail', FILENAME_MAIL_BACKORDER, 'action=preview&cat_id=' . $cat_id . '&params=' . $params); ?>
            <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
    $fields_details=array(array('id'=>'TITLE_C','text'=>TEXT_TITLE_C),
                         array('id'=>'FN','text'=>'&nbsp;&nbsp;' . TEXT_FN),
                         array('id'=>'LN','text'=>'&nbsp;&nbsp;' . TEXT_LN),
					     array('id'=>'SN','text'=>'&nbsp;&nbsp;' . TEXT_SN),
    			   		 array('id'=>'SM','text'=>'&nbsp;&nbsp;' . TEXT_SM),
				         array('id'=>'SE','text'=>'&nbsp;&nbsp;' . TEXT_SE),
	  			         array('id'=>'LA','text'=>'&nbsp;&nbsp;' . TEXT_LA),
			       );
	echo tep_draw_hidden_field('customer_ids',$customer_ids);
?>
              <tr>
                <td class="main"><?php echo TEXT_FROM; ?></td>
                <td><?php echo tep_draw_input_field('from', STORE_OWNER_EMAIL_ADDRESS,'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','','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><table border=0 cellspacing="0" cellpadding="0" style="background:ButtonFace;"><tr><td><?php echo tep_draw_textarea_field('message', 'soft', '80', '24','','id="message"'); ?></td>
				     <td  style="background:ButtonFace;" valign=bottom align=center>
          <?php 
		       echo "<div class='main'><b>" . TEXT_MERGE_FIELDS . '</b></div><br>';
		       echo tep_draw_pull_down_menu('fields',$fields_details,'','style="height:' .((strpos($_SERVER['HTTP_USER_AGENT'],"MSIE")>0)?'224':'241') .'" size=15 ondblClick="AddField()"');
		  ?></td></tr></table></td>

<?php if (HTML_AREA_WYSIWYG_DISABLE_EMAIL == 'Enable') { ?>
           <script>initEditor('message');</script>
<?php }   ?>
          </script>
                
              </tr>
              <tr>
                <td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?></td>
              </tr>
              <tr>    
                <td colspan="2" align="right">
                 <?php 
				 		echo '<a href="javascript:window.close();">' . tep_image_button('button_cancel.gif',IMAGE_CANCEL) . '</a>&nbsp;';
						if($customer_ids!="") {
				 	   if (HTML_AREA_WYSIWYG_DISABLE_EMAIL == 'Enable'){ 
				 			echo tep_image_submit('button_send_email.gif', IMAGE_SEND_EMAIL, 'onClick="validate();return returnVal;"');
	                   } else {
    			            echo tep_image_submit('button_send_email.gif', IMAGE_SEND_EMAIL); 
					   }
					   }
				?>
                </td>
              </tr>
            </table></td>
          </form></tr>
<?php
  }
?>
<!-- body_text_eof //-->
        </table></td>
      </tr>
    </table></td>
  </tr>
</table>
</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
