<?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');
  tep_get_last_access_file();
  require(DIR_WS_FUNCTIONS . 'subscription_tree.php');
  define('FPDF_FONTPATH','font/');
  define(BOX_WIDTH1,'125');

	// get initial parameters, check the session for previous settings
	if (isset($HTTP_GET_VARS["return"]) && isset($HTTP_SESSION_VARS["rep_params"])){
		$input_params=&$HTTP_SESSION_VARS["rep_params"];
	} else {
		$input_params=&$HTTP_POST_VARS;
		if (isset($input_params["post_action"])){
			tep_set_session_value("rep_params",$HTTP_POST_VARS);
			$GLOBALS["rep_params"]["post_action"]="screen";
		} else {
			tep_set_session_value("rep_params",array());
		}
	}
	// get start date,end date, subscription 

	$date_begin = (isset($input_params["txt_date_begin"])?tep_convert_date_raw($input_params["txt_date_begin"]):getServerDate());
	$date_end = (isset($input_params["txt_date_end"])?tep_convert_date_raw($input_params["txt_date_end"]):'');
	$subscription=(isset($input_params["cbo_subscription"])?$input_params["cbo_subscription"]:-1);
	$post_action=(isset($input_params["post_action"])?$input_params["post_action"]:'');

	$post_paid_image=(isset($input_params["post_paid_image"])?$input_params["post_paid_image"]:DIR_FS_DOCUMENT_ROOT . "images/postage_paid.jpg");
	$logo_image=(isset($input_params["logo_image"])?$input_params["logo_image"]:DIR_FS_DOCUMENT_ROOT . 'images/' . COMPANY_LOGO);
	$bottom_image=(isset($input_params["bottom_image"])?$input_params["bottom_image"]:DIR_FS_DOCUMENT_ROOT . "images/osCommRes.png");
	// Default $date_begin to current date
	// default $date_end to next week
	if ($date_end==""){
		$res = tep_db_query("SELECT date_add('" . $date_begin . "',INTERVAL 7 day)");	
		$row = mysql_fetch_array($res);
		$date_end = $row[0];
	}

	//form the query	
	$found_results=false;
		$where = " ";
		$where_status = " ";
		//$where.=" and ((date_format(o.date_purchased,'%Y-%m-%d')>='" . $date_begin . "'" . " and date_format(o.date_purchased,'%Y-%m-%d')<='" . $date_end . "') OR " . " (date_format(date_add(o.date_purchased,interval su.subscription_period day),'%Y-%m-%d')>='" . $date_begin . "'" .  "and date_format(date_add(o.date_purchased,interval su.subscription_period day),'%Y-%m-%d')<='" . $date_end . "'))";
		$where.="and os.start_date!=0
				and (((date_format(os.start_date,'%Y-%m-%d')>='" . $date_begin . "') and (date_format(os.finish_date,'%Y-%m-%d')<='" . $date_end . "'))
				or ((date_format(os.start_date,'%Y-%m-%d')<='" . $date_begin . "') and (date_format(os.finish_date,'%Y-%m-%d')>='" . $date_begin . "'))
				or ((date_format(os.start_date,'%Y-%m-%d')<='" . $date_end . "') and (date_format(os.finish_date,'%Y-%m-%d')>='" . $date_end . "'))
				or ((date_format(os.start_date,'%Y-%m-%d')<='" . $date_begin . "') and (date_format(os.finish_date,'%Y-%m-%d')>='" . $date_end . "')))";
		
		if($subscription!="-1") {
			$where.= " and su.subscription_id='".$subscription."' ";
		}
		// create the query for fetching registered subscribers
		$sql = "select op.products_name,su.subscription_packing_slip,o.customers_name,o.customers_street_address,o.customers_city,o.customers_postcode,o.customers_state,o.customers_country,o.delivery_street_address, " . 
				"o.delivery_city,o.delivery_postcode,o.delivery_state,o.delivery_country ,o.customers_suburb,o.delivery_suburb from " .
		TABLE_CUSTOMERS . " c, " . TABLE_ORDERS . " o, " . TABLE_SUBSCRIPTIONS . " su, " . TABLE_ORDERS_PRODUCTS . " op," . TABLE_ORDERS_SUBSCRIPTIONS . " os where os.products_id=op.products_id and os.orders_id=o.orders_id and su.subscription_id=op.products_id and op.orders_id=o.orders_id " 
		. " and op.orders_products_status>1 and op.orders_products_status<5 and  o.customers_id=c.customers_id and op.products_type='S' " . $where. "  order by customers_name";
		
		$sql_temp=$sql;
		$sql_query=tep_db_query($sql);
		$upload_ws_dir = HTTP_SERVER . DIR_WS_TEMPLATES.DEFAULT_TEMPLATE .'/images';
		$i=0;
		
		// output to pdf file if needed
		$report_filename=sprintf("reports_packing_slip_%s_%s",$login_id,time());
		$use_slip=true;		
		if (tep_db_num_rows($sql_query)>0) $found_results=true;
		if ($post_action=="pdf"){
			require('includes/fpdf.php');
			generate_pdf();
			tep_redirect(DIR_WS_CATALOG . "images/".$report_filename.".pdf");
			return;
		}
		tep_delete_temp_files("reports_packing_slip_" . $login_id);
	  require(DIR_WS_INCLUDES . 'date_format_js.php');
?>
<!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 language="javascript" src="includes/general.js"></script>
<script language="JavaScript" src="includes/date-picker.js"></script>
<script language="JavaScript">
	function showCustomerDetails(id){
		location.href="<?php echo tep_href_link(FILENAME_CUSTOMERS);?>"+"?action=edit&cID="+id+"&return=sud";
	}
	function doReport(mode){
		var begin_date_time = 0;
		var end_date_time = 0;
		var error_result = "";
		if(document.f.txt_date_begin.value==""){
			error_result+="* <?php echo ERR_SUBSCRIPTION_START_DATE;?>\n";
		} else if(document.f.txt_date_begin.value!=""){
			var date_error = true;
			if((document.f.txt_date_begin.value).indexOf("-")!=-1){
				date_error = isValidDate(date_format(document.f.txt_date_begin.value,'','Y-m-d'));
			} else {
				date_error = false;
			}
			if(!(date_error)){
				error_result+="* <?php echo ERR_SUBSCRIPTION_START_DATE;?>\n";
			}
		}
		if(document.f.txt_date_end.value==""){
			error_result+="* <?php echo ERR_SUBSCRIPTION_FINISH_DATE;?>\n";
		} else if(document.f.txt_date_begin.value != ""){
			var date_error = true;
			if((document.f.txt_date_end.value).indexOf("-")!=-1){
				date_error = isValidDate(date_format(document.f.txt_date_end.value,'','Y-m-d'));
			} else {
				date_error = false;
			}
			if(!(date_error)){
				error_result+="* <?php echo ERR_SUBSCRIPTION_FINISH_DATE;?>\n";
			}else{
				 begin_date_time = date_format(document.f.txt_date_begin.value,'','',true).getTime();
				 end_date_time = date_format(document.f.txt_date_end.value,'','',true).getTime();
			}
		}
		if(begin_date_time>end_date_time){
			error_result+="* <?php echo ERR_SUBSCRIPTION_BEGIN_DATE_EXCEED_END_DATE;?>\n";
		}
		if (error_result!=""){
		   alert(error_result);
		}else{
			if (mode==2){
				document.f.post_action.value="pdf";
				document.f.target="_blank";
			}
			document.f.submit();
		}
	}
</script>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF">
<div id="spiffycalendar" class="text"></div>
	<!-- 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% align=left valign="top">
		<table border="0" width="100%" cellspacing="0" cellpadding="2">
			<!--<tr>
				<td class="pageHeading"><?php //echo HEADING_SUBSCRIPTION_DETAILS;?></td>	
			<tr>!-->
			<tr ><td class="cell_bg_report_header">&nbsp;</td></tr>
			<?php echo tep_draw_form("f",FILENAME_PACKING_SLIP); ?>
			<input type="hidden" name="post_action" value="screen"/>
			<!-- form -->
			<tr>
				<td>
				<table border="0" cellspacing="3" cellpadding="2" width="100%">
					<tr>
						<td>
						<table border="0" cellspacing="3" cellpadding="2" class="searchArea">
					<tr>
						<td nowrap class="main">
							<?php echo TEXT_START_DATE;?>
						</td>
						<td><?php $_array=array('d','m','Y');  $replace_array=array('DD','MM','YYYY'); 	$date_format=str_replace($_array,$replace_array,EVENTS_DATE_FORMAT);?>
							<?php echo tep_draw_input_field("txt_date_begin",format_date($date_begin),"size=10",false,'text',false); ?>
							<a href="javascript:show_calendar('f.txt_date_begin',null,null,'<?php echo $date_format;?>');"
							onmouseover="window.status='Date Picker';return true;"
							onmouseout="window.status='';return true;"><img border="none" src="images/icon_calendar.gif"/>  
							</a>
						</td>
					</tr>
					<tr>
						<td nowrap>
							<?php echo TEXT_END_DATE;?>
						</td>
						<td>
						<?php
							echo tep_draw_input_field("txt_date_end",format_date($date_end),"size=10",false,'text',false);
						?>
						<a href="javascript:show_calendar('f.txt_date_end',null,null,'<?php echo $date_format;?>');"
						onmouseover="window.status='Date Picker';return true;"
						onmouseout="window.status='';return true;"><img border="none" src="images/icon_calendar.gif"/>  
						</a>
						</td>
					</tr>
					<tr>
						<td>
							<?php echo TEXT_SUBSCRIPTION;
							?>
						</td>
						<td>
						<?php
							$all_subscriptions_array=array();
							$all_subscriptions_array = tep_get_subscription_array_single();
							if(sizeof($all_subscriptions_array)<=0) echo 'Subscriptions are not Available';
							else echo tep_draw_subscription_select_menu('cbo_subscription',$all_subscriptions_array,$subscription_id,' id="cbo_subscription"');
						?>
						</td>
					</tr>
					<tr>
						<td nowrap="true">
							<?php echo 	TEXT_LOGO_IMAGE;
										
							?>
						</td>
						<td>
							<?php echo tep_draw_input_field("logo_image",DIR_WS_ADMIN . DIR_WS_IMAGES . "osCommRes_logo.png",'size=80');?>
						</td>
					</tr>
					<tr>
						<td nowrap="true">
							<?php echo TEXT_POSTAGE_PAID_IMAGE;
							?>
						</td>
						<td>
						<?php echo tep_draw_input_field("post_paid_image",DIR_WS_ADMIN . DIR_WS_IMAGES . "post_paid.jpg",'size=80');?>
						</td>
					</tr>
					<tr>
						<td nowrap="true">
							<?php echo TEXT_BOTTOM_IMAGE;
							?>
						</td>
						<td>
						<?php echo tep_draw_input_field("bottom_image",DIR_WS_ADMIN . DIR_WS_IMAGES,'size=80');?>
						</td>
					</tr>
					<tr>
						<td>
							<?php echo '<a href="javascript:doReport(2);">' . tep_image_button('button_export_pdf.gif', IMG_EXPORT_PDF) . '</a>';?>
						</td>
					</tr>
					<!-- report content -->
					</table>
					</td>
					</tr>
				</table>
				</td>
			</tr>
			</form>
			<tr>
				<td><?php echo tep_draw_separator('pixel_trans.gif',1,10);?></td>
			</tr>
<?php 
				$i=0;
				if ($i==1 && $found_results){
				?>
					<tr>
						<td>
						<table border="0" width="100%" cellspacing="1" cellpadding="1">
							<?php $replace_array=array();
								while($result=tep_db_fetch_array($sql_query))
									{
										$replace_array=array(
											TEXT_SUB_CF=>$result['customers_name'],
											TEXT_SUB_DA=>$result['customers_street_address'] .'<br>' . ($result['customers_suburb']!=""?$result['customers_suburb'] . '<br>':'') . $result['customers_city'] .  ', ' . $result['customers_postcode'] . '<br>' . $result['customers_state'] . ', ' . $result['customers_country'],
											TEXT_SUB_UN=>$result['customers_name'] . '<br>' . $result['delivery_street_address'] . '<br>' . ($result['delivery_suburb']!=""?$result['delivery_suburb'] . '<br>':'') . $result['delivery_city'] .  ', ' . $result['delivery_postcode'] . '<br>' . $result['delivery_state'] . ', ' . $result['delivery_country'],
											TEXT_SUB_LO=>tep_image($upload_ws_dir.'/'.COMPANY_LOGO,STORE_NAME)  . '<br>' ,
											TEXT_SUB_FO=>tep_image($upload_ws_dir.'/'.COMPANY_LOGO,STORE_NAME)
										);
									reset($replace_array);
									$mail_content=str_replace("\n","<br>",$result['subscription_packing_slip']);
							       while (list($key, $value) = each($replace_array))
								    {
								    	$mail_content=eregi_replace("%%" . $key  . "%%",$value,$mail_content);
									}?>
							<tr>
								<td class="main">
									<?php  echo $mail_content;?>
							    </td>
							</tr>
							<?php } ?>
					  </table>
				</TD>
			</tr>
			<?php	} // if $found_results
			?>
	</table>
	</td>
</tr>
</table>	
	<!-- footer //-->
	<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
	<!-- footer_eof //-->
</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); 
// function to create pdf content
	function generate_pdf(){
		global $sql_query,$found_results,$upload_ws_dir,$post_paid_image,$logo_image,$use_slip,$bottom_image,$login_id,$report_filename;
		$output_content="";
		$replace_array=array();
		// set page setup to a4 landscape
		$pdf=new FPDF("P","mm","A4");
		// get sender address
		$address=split("\n",TEXT_SENDER . "\n" . STORE_NAME_ADDRESS);
		$pdf->SetTextColor(0,0,0);
		$unit=72/25.4;
		$page_height=841.89/$unit;
		$page_width=595.28/$unit;
		$pdf->SetDrawColor(0,0,0);

		if (file_exists($logo_image)){
			$info_logo=getimagesize($logo_image);
			$info_logo[0]=$info_logo[0]/$unit;
			$info_logo[1]=$info_logo[1]/$unit;
		}
		if (file_exists($bottom_image)){
			$info_bottom=getimagesize($bottom_image);
			$info_bottom[0]=$info_bottom[0]/$unit;
			$info_bottom[1]=$info_bottom[1]/$unit;
		}

		if ($found_results){
			while($result=tep_db_fetch_array($sql_query))
			{
				$pdf->AddPage();
				$pos=8;
	
				//print image
				if (isset($info_logo)){
					$pdf->Image($logo_image,10,$pos);
					$pos+=$info_logo[1]+5;
				}

				// print the address
				for($icnt=0;$icnt<count($address);$icnt++){
					if ($icnt==0){
						$pdf->SetFont('Arial','B',12);
					} else {
						$pdf->SetFont('Arial','',12);
					}
					$pdf->Text(10,$pos,$address[$icnt]);
					$pos+=5;
				}

				// print shipping_address
				if ($use_slip && $result["subscription_packing_slip"]!=""){
					// if need to use subscription_packing_slip details
					if ($result["delivery_name"]!=""){
						$replace_array=array(DELI_NA=>$result["delivery_name"],
											DELI_CT=>$result["delivery_street_address"],
											DELI_CC=>$result["delivery_city"],
											DELI_CE=>$result["delivery_state"],
											DELI_CP=>$result["delivery_postcode"],
											DELI_CU=>$result["delivery_country"],
												);
					} else {
						$replace_array=array(DELI_NA=>$result["customers_name"],
											DELI_CT=>$result["customers_street_address"],
											DELI_CC=>$result["customers_city"],
											DELI_CE=>$result["customers_state"],
											DELI_CP=>$result["customers_postcode"],
											DELI_CU=>$result["customers_country"],
											);
					}
					$mes_content=$result["subscription_packing_slip"];
					// replace the merge details
					while (list($key, $value) = each($replace_array))
						$mes_content=eregi_replace("%%" . $key  . "%%",$value . "",$mes_content);
					$shipping_address=split("\n",$mes_content);
				} else {
					if ($result["delivery_name"]!=""){
						$shipping_address=array(	$result["delivery_name"],$result["delivery_street_address"],
													$result["delivery_city"],
													$result["delivery_state"] . " " . $result["delivery_postcode"],
													$result["delivery_country"]
												);
					} else {
						$shipping_address=array(	$result["customers_name"],$result["customers_street_address"],
													$result["customers_city"],
													$result["customers_state"] . " " . $result["customers_postcode"],
													$result["customers_country"]
												);
					}
				}
				$temp_width=0;
				$shipping_width=0;
				$shipping_height=0;
				// calculate width and height to print
				for($icnt=0;$icnt<count($shipping_address);$icnt++){
					$temp_width=$pdf->GetStringWidth($shipping_address[$icnt]);
					if ($temp_width>$shipping_width) $shipping_width=$temp_width;
					$shipping_height+=6;
				}
				$box_width=$shipping_width+50;
				$box_height=$shipping_height+10;
				$box_left=($page_width-$box_width)/2;
				$box_top=($page_height-$box_height)/2;
	
	
				
				$pdf->Rect($box_left,$box_top,$box_width,$box_height);
				$pos=$box_top+(($box_height-$shipping_height)/2)+6;
				$pdf->SetFont('Arial','B',14);
				for($icnt=0;$icnt<count($shipping_address);$icnt++){
					$pdf->Text($box_left+13,$pos,$shipping_address[$icnt]);
					$pos+=6;
				}
				
				if (file_exists($post_paid_image)){
					$pdf->Image($post_paid_image,$page_width-60,8,50);
				}
				if (isset($info_bottom)){
					$pdf->Image($bottom_image,($page_width*25/100),($page_height-$info_bottom[1]-20));
				}
			}
		} else {
			$pdf->AddPage();
			$pdf->SetFont('Arial','B',12);
			$pdf->Text(90,30,TEXT_NO_RECORDS_FOUND);
		}
		$pdf->output(DIR_FS_CATALOG . "images/".$report_filename.".pdf");
	}
	// function to create excel data
?>


