<?php

/*

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

  Copyright (c) 2005 osCommRes

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

Copyright 2007 ZacWare Pty. Ltd
*/
  require('includes/application_top.php');
  
  define(BOX_WIDTH1,'125');
	set_time_limit(10);
// get initial parameters
	$date_begin=isset($HTTP_POST_VARS['txt_start_date'])?tep_convert_date_raw($HTTP_POST_VARS['txt_start_date']):date('Y-m-d');
	$date_end=isset($HTTP_POST_VARS['txt_end_date'])?tep_convert_date_raw($HTTP_POST_VARS['txt_end_date']):'';
	$instructor=isset($HTTP_POST_VARS['sel_instructor'])?$HTTP_POST_VARS['sel_instructor']:-1;
	$location=isset($HTTP_POST_VARS['sel_location'])?$HTTP_POST_VARS['sel_location']:-1;
	$event=isset($HTTP_POST_VARS['sel_event'])?$HTTP_POST_VARS['sel_event']:-1;
	$page_size=isset($HTTP_POST_VARS['opt_page_size'])?$HTTP_POST_VARS['opt_page_size']:1;
	$post_action = isset($HTTP_POST_VARS['post_action'])?$HTTP_POST_VARS['post_action']:'';
	$company=isset($HTTP_POST_VARS['chk_company'])?true:false;
	$address=isset($HTTP_POST_VARS['chk_address'])?true:false;
	$country=isset($HTTP_POST_VARS['chk_country'])?true:false;
	$name_only=isset($HTTP_POST_VARS['chk_name_only'])?true:false;

	$instructors_array = array();
	$events_array = array();
	$locations_array=array();

	if ($date_end==""){
		$sql =  "select date_add('$date_begin', interval -(dayofmonth('$date_begin')-1) day) begin, date_add('$date_begin', interval (30-dayofmonth('$date_begin')) day) end";	
		$sql_result = tep_db_query($sql);
		$row = mysql_fetch_assoc($sql_result);
		$date_begin = $row["begin"];
		$date_end = $row["end"];
	}

	// check for default values
	if ($post_action=="") {
		$country=true;
	}	
	// get instructor names			
	$sql = "select a.admin_id admin_id, admin_firstname, admin_lastname  from events_instructors ei, admin a where ei.admin_id=a.admin_id order by admin_firstname,admin_lastname";
	$sql_result = tep_db_query($sql);
	$num_rows = tep_db_num_rows($sql_result);
	$instructors_array[]=array("id"=>-1,"text"=>TEXT_ALL_INSTRUCTORS);
	while($row=tep_db_fetch_array($sql_result)) {
		$instructors_array[]=array("id"=>$row["admin_id"],"text"=>$row["admin_firstname"]." ".$row["admin_lastname"]);
	}
	mysql_free_result($sql_result);
		
	// get location names
	$sql = "select distinct location_id, location_name from events,events_locations where location_id=events_location order by location_name";
	$sql_result = tep_db_query($sql);
	$locations_array[]=array("id"=>-1,"text"=>TEXT_ALL_LOCATIONS);
	while($row=tep_db_fetch_array($sql_result)) {
		$locations_array[]=array("id"=>$row["location_id"],"text"=>$row["location_name"]);
	}
	mysql_free_result($sql_result);

	// get the event details		
	$sql = "select e.events_id events_id, Events_name  events_name from events e, events_description ed where e.events_id = ed.events_id and ed.language_id='" . $languages_id . "' order by events_name";
	$sql_result = tep_db_query($sql);
	$events_array[]=array("id"=>-1,"text"=>TEXT_ALL_EVENTS);
	while($row=tep_db_fetch_array($sql_result)) {
		$events_array[]=array("id"=>$row["events_id"],"text"=>$row["events_name"]);
	}
	mysql_free_result($sql_result);
	
	$found_results=false;
	// build the output if needed
	if ($post_action!="") {
		$where = " ";
		if($instructor!="-1") {
			$where.= "and e.events_instructor='".$instructor."' ";
		} 
		if($location!="-1") {
			$where.= "and e.events_location='".$location."' ";
		}
		if($event!="-1") {
			$where.= "and e.events_id='".$event."' ";
		}
		// create the sql to fetch customer details for mailing labels
		$sql = "select e.events_id events_id, sessions_id, o.orders_id, o.customers_name customers_name, o.customers_city,
		o.customers_email_address customers_email_address, o.customers_state,o.customers_suburb,o.customers_country,o.customers_company,
		o.customers_telephone customers_telephone, o.customers_street_address,o.customers_fax,o.customers_postcode,
		e.events_instructor events_instructor, e.events_location events_location, ed.events_name events_name,
		start_date, time_format(e.events_start_time,'%h:%i %p') as start_time, events_type, waitlist_type, orders_status
		from events_sessions es, orders_products op, orders o, events e, events_description ed 
		where sessions_id = op.products_id and op.orders_id=o.orders_id and e.events_id=es.events_id 
		and products_type='E' and ed.events_id=e.events_id and (start_date>='$date_begin' and start_date<='$date_end')
		and (events_type='R') ".$where." and ed.language_id='" . $languages_id . "' group by o.customers_id order by customers_name";
		
		$sql_result=tep_db_query($sql);
		$num_rows=tep_db_num_rows($sql_result);
		if ($num_rows>0) $found_results=true;
	}
	if ($post_action=="") {
?>
<!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">
<style type="text/css">
	#pup {position:absolute; visibility:hidden; z-index:200; width:130; }
</style>
<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>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF">
<script language="JavaScript" src="includes/popup.js"></script>
<script language="JavaScript">
	var baby=new Array();
	baby[1]="";
	
	function showpopup(type)
	{
		var content_value="";
		if (type==2){
			content_value="<?php echo addslashes(stripslashes(TEXT_INFO2));?>";
		} else {
			content_value="<?php echo addslashes(stripslashes(TEXT_INFO1));?>";
		}
		content='<table border="0" cellspacing="0" cellpadding="4" class="tableArea" width="100%"><tr><td class="main">';
		content+=content_value;
		content+='</td></tr></table>';
		popwidth=250;
		baby[1]=content;
		if (baby[1]!="")
		{
			popup("1","#ffffff");
		}	
	}
	function validateForm(frm){
		var err="";
		if (frm.chk_name_only.checked){
			if (frm.chk_company.checked || frm.chk_address.checked || frm.chk_country.checked){
				err="<?php echo addslashes(stripslashes(ERR_NAME_SELECT));?>";
			}
		}
		if (err!="") {
			alert(err);
			return false;
		}
		return true;
	}
	function doReport(mode) {
		strStart = document.f.txt_start_date.value.split("-");
		startDate = new Date(strStart[0], strStart[1], strStart[2]);
	
		strEnd = document.f.txt_end_date.value.split("-");
		endDate = new Date(strEnd[0], strEnd[1], strEnd[2]);
	
		if(startDate.getTime()>endDate.getTime()) {
			alert("<?php echo REPORT_START_AFTER_END?>");
			return;
		}
		document.f.submit();
	}
</script>
<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_MAILING_LABELS ;?></td>	
		</tr>
        <tr>
		  	<TD>
			<?php 	echo tep_draw_form("f",FILENAME_MAILING_LABELS,"","post","target=_blank onSubmit='javascript:return validateForm(this);'");
					echo tep_draw_hidden_field("post_action","yes");
			?>
			<table border="0" cellspacing="3" cellpadding="2" class="formArea" width="100%">
				<tr>
					<td class="main" nowrap="true"><?php $_array=array('d','m','Y');  $replace_array=array('DD','MM','YYYY'); 	$date_format=str_replace($_array,$replace_array,EVENTS_DATE_FORMAT);?>
						<?php echo TEXT_START_DATE . '&nbsp;' . tep_draw_input_field("txt_start_date",format_date($date_begin),'maxlength="10" size="10"');?>
						<a href="javascript:show_calendar('f.txt_start_date',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>
						<?php echo '&nbsp;&nbsp;&nbsp;' . TEXT_END_DATE . '&nbsp;' . tep_draw_input_field("txt_end_date",format_date($date_end),'maxlength="10" size="10"');?>
						<a href="javascript:show_calendar('f.txt_end_date',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>
						<?php    
							echo '&nbsp;&nbsp;&nbsp;' . TEXT_INSTRUCTOR . '&nbsp;' . tep_draw_pull_down_menu("sel_instructor",$instructors_array,$instructor);
						?>
					</td>
					<td rowspan="2" valign="middle" align="right">
						<?php echo '<a href="javascript:doReport(1);">' . tep_image_button('button_report_search.gif', IMAGE_DISPLAY_LABELS) . '</a>'; ?>
					</td>
				</tr>
				<tr>
				<td class="main" nowrap="true">
					<?php 	echo TEXT_LOCATION . '&nbsp;' . tep_draw_pull_down_menu("sel_location",$locations_array,$location);
							echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' . TEXT_EVENT . '&nbsp;' . tep_draw_pull_down_menu("sel_event",$events_array,$event);
					?>
				</td>
			</tr>
			<tr>
				<td class="main" nowrap="true">
					<?php 
							echo TEXT_PAGE_SIZE . '&nbsp;' . tep_draw_radio_field("opt_page_size",1,($page_size==1?true:false)) . 
								'<span onMouseOver="javascript:showpopup(1);" onMouseOut="javascript:kill();">' . TEXT_PAGE1 . '</span>';
							echo '&nbsp;' . tep_draw_radio_field("opt_page_size",2,($page_size==2?true:false)) . 
								'<span onMouseOver="javascript:showpopup(2);" onMouseOut="javascript:kill();">' . TEXT_PAGE2 . '</span>';
					?>
				</td>
			</tr>
			<tr>
				<td class="main" nowrap="true">
					<?php
							echo TEXT_SHOW . '&nbsp;<span class="spanRow">' . tep_draw_checkbox_field('chk_company',1,$company) . TEXT_COMPANY;
							echo '&nbsp;&nbsp;' . tep_draw_checkbox_field('chk_address',1,$address) . TEXT_ADDRESS;
							echo '&nbsp;&nbsp;' . tep_draw_checkbox_field('chk_country',1,$country) . TEXT_COUNTRY . '</span>';
							echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' . '<span class="spanRow">' . tep_draw_checkbox_field('chk_name_only',1,$name_only) . TEXT_NAME_ONLY;
					?>
				</td>
				<td class="main" nowrap="true">
				</td>
			</tr>
			<!-- report content -->
		</table>
		</form>
	</TD>
	</tr>
</table>
</td>
</tr>
</table>
	<!-- footer //-->
	<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
	<!-- footer_eof //-->
</body>
</html>

<?php 
} else { // found results
  define('FPDF_FONTPATH','font/');
  require('includes/fpdf.php');
  
  define('PDF_ORIENTATION','P');

  	//  set initial PDF details
	if ($page_size==1) {
		$label_height=1.5;
		$label_width=2.5;
		$left_margin=0.28;
		$top_margin=0.63;
		$horizontal_pitch=2.6;
		$vertical_pitch=1.5;
		$no_columns=3;
		$row_height=($label_height-0.4)/6;
		$page_height=$vertical_pitch*7;
		$page_width=$horizontal_pitch*3;
	} else {
		$label_height=1.33;
		$label_width=4;
		$left_margin=0.16;
		$top_margin=0.83;
		$no_columns=2;
		$row_height=($label_height-0.4)/6;
		$horizontal_pitch=4.19;
		$vertical_pitch=1.33;
		$page_height=$vertical_pitch*9;
		$page_width=$horizontal_pitch*2;

	}		
  $font_name="Arial";
  $font_size=11;

	$pdf=new FPDF(PDF_ORIENTATION,"in",($page_size==2?"legal":"A4"));
	$pdf->AliasNbPages();
	$pdf->AddPage();
	$pdf->SetFont($font_name,'',$font_size);

	$cur_row=0;

	$labels=array();
	// prepare the details as row column pattern
	if ($found_results){
		while($row=tep_db_fetch_array($sql_result)){
			$label_data="";
			$fld_count=0;
			$label_data.=$row["customers_name"] . "\n" ;
			if (!$name_only) {// show only name other fields need to be not shown
				if ($company && $row["customers_company"]!="" && !is_null($row["customers_company"])) { // if the field is present and is checked for the selection
					$label_data.=$row["customers_company"] . "\n";
					$fld_count++;
				}
				if ($address && $row["customers_street_address"]!="" && !is_null($row["customers_street_address"])) {
					$label_data.=$row["customers_street_address"] . "\n";
					$fld_count++;
				}
				if ($row["customers_suburb"]!="" && !is_null($row["customers_suburb"])) {
					$label_data.=$row["customers_suburb"] . "\n";
					$fld_count++;
				}
				$label_data.=$row["customers_city"] . "\n" .
							$row["customers_state"] . " " . $row["customers_postcode"] . "\n";

				if ($country && $row["customers_country"]!="" && !is_null($row["customers_country"])) {
					$label_data.=$row["customers_country"] . "\n";
					$fld_count++;
				}
			}
			$labels[$cur_row]=$label_data;		
			$cur_row++;			
		}
	}

	if (sizeof($labels)>0){
		$cur_col=0;
		$cur_x=$left_margin;
		$cur_y=$top_margin;
			for ($icnt=0;$icnt<sizeof($labels);$icnt++){
				// if the total height go beyond page height
				if ($cur_y>$page_height){
					$cur_col++;
					if ($cur_col>=$no_columns){
						$pdf->AddPage();
						$cur_col=0;
						$cur_x=$left_margin;
						$cur_y=$top_margin;
					} else {
						$cur_x+=$horizontal_pitch;
						$cur_y=$top_margin;
					}
				}
				$label=split("\n",$labels[$icnt]);
				$label_x=$cur_x;
				$label_y=$cur_y+0.2;
				for($jcnt=0;$jcnt<sizeof($label);$jcnt++){
					$pdf->text($label_x,$label_y,$label[$jcnt]);
					$label_y+=$row_height;
				}
				$cur_y+=$vertical_pitch;
			}
	}
	if (file_exists(DIR_FS_CATALOG . "images/mailing_labels.pdf")){
		unlink(DIR_FS_CATALOG . "images/mailing_labels.pdf");
	}
	// output to pdf
	$pdf->output(DIR_FS_CATALOG . "images/mailing_labels.pdf");
	tep_redirect(DIR_WS_CATALOG . "images/mailing_labels.pdf");
}
require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>