<?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('includes/classes/pdfTable.php');
  require(DIR_WS_CLASSES . 'split_page_results_report.php');
  require(DIR_WS_FUNCTIONS . 'services_tree.php');
  define(BOX_WIDTH1,'125');

	// get initial parameters, first check the session for previous values
	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());
		}
	}
	$date=isset($input_params['txtDate'])?tep_convert_date_raw($input_params['txtDate']):date('Y-m-d');
	$view=isset($input_params['sel_view'])?$input_params['sel_view']:1;
	$location=isset($input_params['sel_location'])?$input_params['sel_location']:-1;
	$sel_service_type=isset($input_params['sel_service_type'])?$input_params['sel_service_type']:-1;
	$sel_resource=isset($input_params['sel_resource'])?$input_params['sel_resource']:-1;
	$post_action = isset($input_params['post_action'])?$input_params['post_action']:'';
	$output_pdf=isset($input_params['chk_output_pdf'])?true:false;
	$output_excel=isset($input_params['chk_output_excel'])?true:false;
	$page=isset($input_params['page'])?$input_params['page']:1;
	$date_begin = $date;
	$date_end = $date;	
	$days= date('t',strtotime($date));
	$display_header="";
	if ($post_action==""){
		$output_pdf=true;
		$post_action="screen";
	}	
	if($view==2) {
		$sql =  "select date_add('$date', interval -(dayofweek('$date')-1) day) begin, date_add('$date', interval (7-dayofweek('$date')) day) end";	
	} else if($view==3) {
		$sql =  "select date_add('$date', interval -(dayofmonth('$date')-1) day) begin, date_add('$date', interval ('$days'-dayofmonth('$date')) day) end";	
	}
	if($view==2 || $view==3) {
		$sql_result = tep_db_query($sql);
		$row = mysql_fetch_assoc($sql_result);
		$date_begin = $row["begin"];
		$date_end = $row["end"];	
	}
	// create the header for the pdf page
	$display_header=TEXT_DAY .  ":&nbsp;&nbsp;" . $date . "&nbsp;&nbsp;&nbsp;&nbsp;";
	if ($view==1) {
		$display_header.=TEXT_VIEW .  ":&nbsp;&nbsp;" . TEXT_DAY . "\t";
	} else if ($view==2){
		$display_header.=TEXT_VIEW .  ":&nbsp;&nbsp;" . TEXT_WEEK . "\t";
	} else {
		$display_header.=TEXT_VIEW .  ":&nbsp;&nbsp;" . TEXT_MONTH . "\t";
	}

	$services_provider_array = array();
	$locations_array=array();
	$view_array=array(array("id"=>1,"text"=>TEXT_DAY),array("id"=>2,"text"=>TEXT_WEEK),array("id"=>3,"text"=>TEXT_MONTH));

	
	// get resource names			
	$sql = "select r.resource_id resource_id, rd.resource_name  from " . TABLE_RESOURCES . " r, " . TABLE_RESOURCES_DESCRIPTION . " rd where r.resource_id=rd.resource_id  and rd.language_id='".(int)$languages_id."' order by resource_name";
	$sql_result = tep_db_query($sql);
	$num_rows = tep_db_num_rows($sql_result);
	$resources_array[]=array("id"=>-1,"text"=>TEXT_ALL_RESOURCE);
	while($row=tep_db_fetch_array($sql_result)) {
		$resources_array[]=array("id"=>$row["resource_id"],"text"=>$row["resource_name"]);
		if ($row["resource_id"]==$sel_resource){
			$display_header.=TEXT_RESOURCE  . ":&nbsp;&nbsp;" . $row["resource_name"] . "\t";
		}
	}
	mysql_free_result($sql_result);
	
	// get location names

	$sql = "select distinct se.service_location as service_location ,l.service_location_name as location_name,l.service_location_id as location_id from ". TABLE_SERVICES . " se," . TABLE_SERVICES_LOCATIONS ." l where l.service_location_id=se.service_location order by l.service_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["service_location"],"text"=>$row["location_name"]);
		if ($row["location_id"]==$location){
			$display_header.=TEXT_LOCATION  . ":&nbsp;&nbsp;" . $row["location_name"] . "\t";
		}
	}
	mysql_free_result($sql_result);
	
	// Service List
	
	$service_option="";
	$sql = "select se.service_id service_id, service_name  service_name from " . TABLE_SERVICES . " se," . TABLE_SERVICES_DESCRIPTION . " sed where se.service_id = sed.service_id and sed.language_id='" . $languages_id ."'" . SERVICES_CONDITION_STATUS . $service_option . "order by service_name";
	$sql_result = tep_db_query($sql);
	while($row=tep_db_fetch_array($sql_result)) {
		if ($row["service_id"]==$sel_service_type){
			$display_header.=TEXT_SERVICE  . ":&nbsp;&nbsp;" . $row["service_name"]."\t";
		}
	}
	mysql_free_result($sql_result);
	$found_results=false;
	// build the output if needed
	 $where = "";
	 	if($sel_service_type!="-1"){
			$where.= "and s.service_id='".$sel_service_type."' ";
		}else {
		 $display_header.=TEXT_SERVICE . ":&nbsp;&nbsp;" . TEXT_ALL_SERVICES ."\t";
		}
		if($sel_resource!="-1") {
			$where.= "and os.resource_id='".$sel_resource."' ";
		}else { 
		  $display_header .=TEXT_RESOURCE . ':&nbsp;&nbsp;' . TEXT_ALL_RESOURCE . "\t";
		} 
		if($location!="-1") {
			$where.= "and s.service_location='".$location."' ";
		}else {
		  $display_header.=TEXT_LOCATION . ":&nbsp;&nbsp;" . TEXT_ALL_LOCATIONS  ."\t";
		}
		// create the sql for fetching customer details
	$sql = "select s.service_id service_id,o.orders_id, o.customers_name customers_name,o.customers_id,
		o.customers_email_address customers_email_address, o.customers_suburb,o.customers_city,
		o.customers_telephone customers_telephone, o.customers_street_address,o.customers_fax,
		sd.service_name service_name,s.service_id,orders_status from " . TABLE_ORDERS_PRODUCTS . " op," . TABLE_ORDERS . " o," . TABLE_SERVICES . " s," . TABLE_SERVICES_DESCRIPTION . " sd," . TABLE_SERVICES_TO_SERVICES_RESOURCES ." sr," . TABLE_RESOURCES ." r," . TABLE_ORDERS_SERVICES ." os where  op.orders_id=o.orders_id and  o.orders_id=os.orders_id and products_type='V' and sd.service_id=s.service_id and op.products_id=s.service_id and sr.service_id=s.service_id and sr.service_resource_id=r.resource_id  and os.products_id=s.service_id and sd.language_id='" . $languages_id . "' " .$where." and os.start_date>='$date_begin' and os.start_date<='$date_end' group by o.customers_id order by customers_name desc";
	if ($post_action=="screen"){
		// split the report to multiple pages
		$query_split = new splitPageResultsReport($page, REPORT_MAX_ROWS_PAGE, $sql, $query_split_numrows);
	}
		
		$sql_result=tep_db_query($sql);
		$num_rows=tep_db_num_rows($sql_result);
		if ($num_rows>0) $found_results=true;

	$report_filename=sprintf("services_customer_details_%s_%s",$login_id,time());
	 
	// output to pdf
	if ($post_action=="pdf"){
		generate_pdf(); 
		tep_redirect(DIR_WS_CATALOG . "images/".$report_filename.".pdf");
		return;
	}

	// output to excel 
	if ($post_action=="excel"){
		generate_excel();
		tep_redirect(DIR_WS_CATALOG . "images/".$report_filename.".csv");
		return;
	}
	tep_delete_temp_files("services_customer_details_" . $login_id);
?>
<!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>
<?php include(DIR_WS_INCLUDES."date_format_js.php")?>

<script language="JavaScript">
	function doReport(mode) {
		if (mode==3){
			document.f.post_action.value="excel"
			document.f.target="_blank";
		} else if (mode==2){
			document.f.post_action.value="pdf";
			document.f.target="_blank";
		} else {
			document.f.post_action.value="screen";
			document.f.target="_self";
		}
		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 height="5">
			<!--<td class="pageHeading"><?php //echo HEADING_CUSTOMER_DETAILS;?></td>!-->
		</tr>
        <tr >
		  	<TD>
			<?php 	echo tep_draw_form("f",FILANEME_SERVICES_CUSTOMER_DETAILS);
					echo tep_draw_hidden_field("post_action","screen");
			?>
			<table border="0" cellspacing="3" cellpadding="2" width="100%">
				<tr>
					<td>
					<table width="100%" border="0" cellpadding="0" cellspacing="0" class="searchArea">
						<tr height="20">
						<td align="left"><?php echo TEXT_DAY ;?></td><?php $_array=array('d','m','Y');  $replace_array=array('DD','MM','YYYY'); 	$date_format=str_replace($_array,$replace_array,EVENTS_DATE_FORMAT);?>
							<td align="left"><?php echo tep_draw_input_field("txtDate",format_date($date),'maxlength="10" size="10"');?>
							<a href="javascript:show_calendar('f.txtDate',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>
							<td align="left"><?php echo '&nbsp;&nbsp;'.TEXT_VIEW;?> </td>
							<td  align="left"><?php echo '&nbsp;' . tep_draw_pull_down_menu("sel_view",$view_array,$view);?></td>
							<td align="left"><?php echo TEXT_LOCATION . '&nbsp;&nbsp;' . tep_draw_pull_down_menu("sel_location",$locations_array,$location);?></td>

								<td valign="middle" align="right">
								<?php echo '<a href="javascript:doReport(1);">' . tep_image_button('button_report_search.gif', IMAGE_SEARCH_DETAILS) . '</a>'; ?>
							</td>
						</tr>
						<tr height="30">
						<td colspan="5">
								<?php 
								$all_service_array=array();
								$all_service_array = tep_get_service_array_single();
								if(sizeof($all_service_array)<=0) echo 'Services are not Available';
								else echo TEXT_SERVICE . '&nbsp;&nbsp;&nbsp;' . tep_draw_service_select_menu('sel_service_type',$all_service_array,$service_type,' id="sel_service_type"');
								echo '&nbsp;&nbsp;&nbsp;'.TEXT_RESOURCE . '&nbsp;' . tep_draw_pull_down_menu("sel_resource",$resources_array,$sel_resource);
								?>
							<td valign="middle" align="right">
								<?php echo '<a href="javascript:doReport(2);">' . tep_image_button('button_export_pdf.gif', IMG_EXPORT_PDF) . '</a>';?>
							</td>	
						</tr>
						<tr height="30">
							<td colspan="6" align="right">
								<?php echo '<a href="javascript:doReport(3);">' . tep_image_button('button_export_excel.gif', IMG_EXPORT_EXCEL) . '</a>';?>
							</td>
						</tr>
					</table>
					</TD>
				</tr>
				<!-- report content -->
			</table>
		</form>
		</td>
	</tr>
	<tr ><td class="cell_bg_report_header">&nbsp;</td></tr>
	<?php if ($found_results) { ?>
		<tr>
				<td>
				<table border="0" width="100%" cellspacing="0" cellpadding="2">
					<tr>
						<td class="smallText" align="left">
							<?php echo $query_split->display_links($query_split_numrows, REPORT_MAX_ROWS_PAGE, REPORT_MAX_LINKS_PAGE, $page,tep_get_report_params()); ?>&nbsp;
						</td>
					</tr>
				</table>
				</td>
		</tr>
	<tr>
		<td>
	   <table border="0" width="100%" cellspacing="1" cellpadding="1">
			<tr class='dataTableHeadingTitleRow'>
				<td class='dataTableHeadingTitleContent' width="30"><?php echo TEXT_ID;?></td>
				<td class='dataTableHeadingTitleContent'><?php echo TEXT_CLIENT;?></td>
				<td class='dataTableHeadingTitleContent'><?php echo TEXT_ADDRESS;?></td>
				<td class='dataTableHeadingTitleContent' width="130"><?php echo TEXT_PHONE;?></td>
				<td class='dataTableHeadingTitleContent' width="130"><?php echo TEXT_MOBILE;?></td>
				<td class='dataTableHeadingTitleContent' width="50"><?php echo TEXT_EMAIL;?></td>
			</tr>
			<tr height="10"></tr>
			<?php
					$i=1;
					mysql_data_seek($sql_result,0);
          			while($row = tep_db_fetch_array($sql_result)) {
						?>
                  <tr class='dataTableRow' height="20" onMouseOver="rowOverEffect(this)" onMouseOut="rowOutEffect(this)" onClick="javascript:location.href='<?php echo tep_href_link(FILENAME_CUSTOMERS,'cID=' . $row["customers_id"] . '&action=edit&return=rsc&type=ser');?>';">
					  <td class='dataTableContent' style="cursor:hand" valign="top"><?php echo $i?></td>
					  <td class='dataTableContent' style="cursor:hand" valign="top"><?php echo $row['customers_name'] //.'&nbsp;'. $row['service_name'] ?></td>
					  <td class='dataTableContent' style="cursor:hand" valign="top">
					  	<?php  	if ($row['customers_street_address']!="") echo $row['customers_street_address'] .'<br>';
								if ($row['customers_suburb']!="") echo $row['customers_suburb'] .'<br>';
								if ($row['customers_city']!="") echo $row['customers_city'] . '<br>';
								echo '<br>';
						?>
					  </td>
					  <td class='dataTableContent' style="cursor:hand" valign="top"><?php echo $row['customers_telephone']?></td>
					  <td class='dataTableContent' style="cursor:hand" valign="top"><?php echo $row['customers_fax']?></td>
					  <td class='dataTableContent' style="cursor:hand" align="center" valign="top"> <a href="mailto:<?php echo $row['customers_email_address']?>"><img src="images/icons/mail.gif" border="0"></a></td>

                  </tr>
			<?php 
						$i++;						
					}	
			?>
	</table>
	</TD>
	</tr>
	<?php 
		} 
		else{
				echo '<tr><td class="main" align="center">' . TEXT_NO_RECORDS_FOUND . '</td></tr>';
		}
	?>
</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_result,$display_header,$found_results,$report_filename;
		
		// set initial params
		$table=new pdfTable("A4","l");
		$table->left_margin=20;
		$table->top_margin=20;
		$table->right_margin=20;
		$table->bottom_margin=20;
		$table->pdfInit();
		
		// Add the styles
		$table->AddStyle("heading","color:#727272;bgcolor:#ffffff;font:Arial;size:18;style:B");
		$table->AddStyle("user","color:#000000;bgcolor:#f1f9fe;font:Arial;size:14;style:B;border-color:#7b9ebd");
		$table->AddStyle("subhead","color:#000000;bgcolor:#7b9ebd;font:Arial;size:10;style:B");
		$table->AddStyle("headrow","color:#000000;bgcolor:#C9C9C9;font:Arial;size:10;style:B");
		$table->AddStyle("row","color:#000000;bgcolor:#F0F1F1;font:Arial;size:10");
		$table->AddStyle("query","color:#000000;bgcolor:#FFFFFF;font:Arial;size:11");
		$table->AddStyle("subrow","color:#000000;bgcolor:#FFFFFF;font:Arial;size:10");
		$table->AddStyle("subrowhead","color:#000000;bgcolor:#FFFFFF;font:Arial;size:10;style:B");

		
		$table->headers["text"]=$display_header;
		$table->headers["style"]="query";
		$table->headers["height"]=12;
		$table->headers["width"]="100%";
		$table->headers["cols"]=4;

		//define the column width
		$widths[0]=$table->width*5/100;
		$widths[2]=$table->width*35/100;
		$widths[3]=$table->width*20/100;
		$widths[4]=$table->width*20/100;

		$widths[1]=$table->width-($widths[0]+$widths[2]+$widths[3]+$widths[4]);

		// create the table header columns
		$cols=array();
		$cols[]=array("text"=>TEXT_ID,"width"=>$widths[0],"align"=>"L","style"=>"headrow","valign"=>"M");
		$cols[]=array("text"=>TEXT_CLIENT,"width"=>$widths[1],"align"=>"L","style"=>"headrow","valign"=>"M");
		$cols[]=array("text"=>TEXT_ADDRESS,"width"=>$widths[2],"align"=>"L","style"=>"headrow","valign"=>"M");
		$cols[]=array("text"=>TEXT_PHONE,"width"=>$widths[3],"align"=>"L","style"=>"headrow","valign"=>"M");
		$cols[]=array("text"=>TEXT_MOBILE,"width"=>$widths[4],"align"=>"L","style"=>"headrow","valign"=>"M");
		$table->tableheaders["text"]=$cols;
		$i=1;
		unset($cols);
		if ($found_results){
		mysql_data_seek($sql_result,0);
		// output the content
		while($row = tep_db_fetch_array($sql_result)) {
			$cols=array();
			$address="";
			if ($row['customers_street_address']!="") {
				$address.=$row['customers_street_address'] ."\n";
			}
			if ($row['customers_suburb']!="") {
				$address.=$row['customers_suburb'] ."\n";
			}
			if ($row['customers_city']!="") {
				$address.=$row['customers_city'] . '\n';
			}
			$address=substr($address,0,-2);
			$cols[]=array("text"=>$i,"width"=>$widths[0],"align"=>"L","style"=>"row","valign"=>"M");
			$cols[]=array("text"=>$row['customers_name'],"width"=>$widths[1],"align"=>"L","style"=>"row","valign"=>"M");
			$cols[]=array("text"=>$address,"width"=>$widths[2],"align"=>"L","style"=>"row","valign"=>"M");
			$cols[]=array("text"=>$row['customers_telephone'],"width"=>$widths[3],"align"=>"L","style"=>"row","valign"=>"M");
			$cols[]=array("text"=>$row['customers_fax'],"width"=>$widths[4],"align"=>"L","style"=>"row","valign"=>"M");
			$table->OutputRowMultiple($cols,15);
			unset($cols);
			$i++;						
		}
		} else {
			$cols[]=array("text"=>TEXT_NO_RECORDS_FOUND,"width"=>"100%","align"=>"C","style"=>"subrow","valign"=>"M");
			$table->OutputRow($cols,15);
			unset($cols);
		}
		//create the pdf
		$table->Render($report_filename.".pdf");
	}
	function generate_excel(){
		global $sql_result,$found_results,$report_filename;
		$result="";
		$i=1;
		$result.=TEXT_ID . "," . TEXT_CLIENT . "," . TEXT_ADDRESS . "," . TEXT_SUBURB . "," . TEXT_CITY . "," .
				TEXT_PHONE . "," . TEXT_MOBILE . "\n";
		if ($found_results){
			mysql_data_seek($sql_result,0);
		while($row = tep_db_fetch_array($sql_result)) {
			$cols=array();
			$address="";
			$height=0;
			$result.=$i . ",\"" .$row['customers_name']. "\",\"" . $row['customers_street_address'] . "\",\"" .
					$row['customers_suburb'] . "\",\"" .$row['customers_city'] . "\",\"" . $row['customers_telephone']  . "\",\"" .
					$row['customers_fax'] . "\"\n";
			$i++;						
		}
		} else {
			$result.=TEXT_NO_RECORDS_FOUND . "\n";
		}
		tep_write_text_file($report_filename.".csv",$result);
	}
?>