<?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/currencies.php');
  require(DIR_WS_CLASSES . 'split_page_results_report.php');
  require('includes/classes/pdfTable.php');
  define(BOX_WIDTH1,'125');
  // get initial parameters, first check 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"])){
			if ($input_params["post_action"]!="serviceresource"){
				tep_set_session_value("rep_params",$HTTP_POST_VARS);
				$GLOBALS["rep_params"]["post_action"]="screen";
			}
		} else {
			tep_set_session_value("rep_params",array());
		}
	}

	$date_begin=isset($input_params['txt_start_date'])?tep_convert_date_raw($input_params['txt_start_date']):getServerDate();
	$date_end=isset($input_params['txt_end_date'])?tep_convert_date_raw($input_params['txt_end_date']):'';
	$resource=isset($input_params['sel_resource'])?$input_params['sel_resource']:-1;
	$summary_view=isset($input_params['chk_summary'])?true:false;
	$post_action = isset($input_params['post_action'])?$input_params['post_action']:'';
	$page = isset($input_params['page'])?$input_params['page']:1;
	$currencies=new currencies();
	$display_header="";
	if ($post_action==""){
		$post_action="screen";
	}
	if ($date_end==""){
		$sql =  "select date_add('$date_begin', interval 1 month) end";	
		$sql_result = tep_db_query($sql);
		$row = mysql_fetch_assoc($sql_result);
		$date_end = $row["end"];	
	}
	$display_header.=TEXT_START_DATE  . ":&nbsp;" . format_date($date_begin) . "\t";
	$display_header.=TEXT_END_DATE  . ":&nbsp;" . format_date($date_end) ."\t";
	if ($summary_view){
		$display_header.=TEXT_VIEW . ":&nbsp;" . TEXT_SUMMARY;
	} else {
		$display_header.=TEXT_VIEW . ":&nbsp;" . TEXT_DETAIL;
	}
	// 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 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_RESOURCES);
	while($row=tep_db_fetch_array($sql_result)) {
		$resources_array[]=array("id"=>$row["resource_id"],"text"=>$row["resource_name"]);
	}
	mysql_free_result($sql_result);
	$found_results=false;
	$where = " ";
	$db_result=array();
	$num_rows=0;
	$cur_row=0;
	$where.=" and ((ov.start_date>='" . $date_begin . "' and ov.start_date<='" . $date_end . "') or (ov.end_date>='" . $date_begin . "' and ov.end_date<='" . $date_end . "') " .
				" or (ov.start_date<='" . $date_begin . "' and ov.end_date>='" . $date_end . "'))";
	if($resource!="-1") {
		$where.= "and ov.resource_id='".$resource."' ";
	}
	$sql="select o.customers_name,op.orders_id,ov.start_date,ov.end_date,ov.start_time,ov.end_time,time_format(ov.start_time,'%h:%i %p') as start_time_text,op.final_price,op.products_tax," .
			" time_format(ov.end_time,'%h:%i %p') as end_time_text,ov.resource_id,ov.resource_name from " . TABLE_ORDERS . " o," . TABLE_ORDERS_PRODUCTS . " op," .
			TABLE_ORDERS_SERVICES . " ov where o.orders_id=op.orders_id and op.orders_products_id=ov.orders_products_id " . $where . " order by resource_name ";
	//echo $sql;		 
	$sql_page=$sql;
	if (!$summary_view && $post_action=="screen") $query_split = new splitPageResultsReport($page, REPORT_MAX_ROWS_PAGE, $sql_page, $query_split_numrows);
	$result_query = tep_db_query($sql_page);
	if (tep_db_num_rows($result_query)>0) $found_results=true;
	$details=array();
	$subtotal_details = array();
	$prev_resource=-1;
	$prev_index=0;
	$total_hours=0;
	$total_cost=0;
	$subtotal_hours = 0;
	$subtotal_cost = 0;
	$grand_total_hours = 0;
	$grand_total_cost = 0;
	$icnt=0;
	$switch = false;
	while($row=tep_db_fetch_array($result_query)){
		$resource_id=$row["resource_id"];
		if ($prev_resource!=$resource_id){
			if ($total_hours>0){
				$details[$prev_index]["hours"]=$total_hours;
				$details[$prev_index]["cost"]=$currencies->format($total_cost);
				$grand_total_hours +=$details[$prev_index]["hours"];
				$grand_total_cost +=$total_cost;
				$subtotal_hours += $details[$prev_index]["hours"];
				$subtotal_cost += $total_cost;
				if($switch){
					$details[$icnt] = array("type"=>"S","rname"=>"Subtotal","hours"=>$subtotal_hours,"cost"=>$currencies->format($subtotal_cost));
					$icnt++;
					$subtotal_hours = 0;
					$subtotal_cost = 0;
					$switch = false;
				}
				$total_hours=0;
				$total_cost=0;
			}
			$prev_index=$icnt;
			$prev_resource=$resource_id;
			$details[$icnt]=array("type"=>($icnt==0?"F":"T"),"rname"=>$row["resource_name"],"hours"=>0,"cost"=>0);
			$icnt++;
		}
		$amount=tep_add_tax($row["final_price"],$row["products_tax"]);
		if($details[$prev_index]["hours"]==0){
			$switch= true;
		}
		$total_hours+=tep_time_diff_in_format($row["start_date"] . ' ' . $row["start_time"],$row["end_date"] . ' ' . $row["end_time"],"H");
		if (!$summary_view){
			$details[$icnt]=array("type"=>"R","cname"=>$row["customers_name"],"orders_id"=>$row["orders_id"],"price"=>$currencies->format($amount));
			$details[$icnt]["sdate"]=format_date($row["start_date"]) . ' ' . $row["start_time_text"];
			$details[$icnt]["edate"]=format_date($row["end_date"]) . ' ' . $row["end_time_text"];
			$icnt++;
		}
		$total_cost+=$amount;
	}
	if ($total_hours>0){
		$details[$prev_index]["hours"]=$total_hours;
		$details[$prev_index]["cost"]=$currencies->format($total_cost);
		$grand_total_hours += $details[$prev_index]["hours"];
		$grand_total_cost += $total_cost;
		$subtotal_hours += $details[$prev_index]["hours"];
		$subtotal_cost += $total_cost;
		if($switch){
			$details[$icnt] = array("type"=>"S","rname"=>"Subtotal","hours"=>$subtotal_hours,"cost"=>$currencies->format($subtotal_cost));
			$subtotal_hours = 0;
			$subtotal_cost = 0;
			$switch = false;
		}
		$total_hours=0;
		$total_cost=0;
	}
	$format_grand_total_cost = $currencies->format($grand_total_cost);
	$report_filename=sprintf("resources_view_%s_%s",$login_id,time());
	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("resources_view_" . $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 showOrderDetails(id){
		location.href="orders.php?action=edit&oID="+id; 
	}
	function doReport(mode) {
		startDate=date_format(document.f.txt_start_date.value,'','Y-m-d',true);
		endDate=date_format(document.f.txt_end_date.value,'','Y-m-d',true);
		if(startDate>endDate) {
			alert("<?php echo REPORT_START_AFTER_END?>");
			return;
		}
		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_RESOURCES;?></td>!-->
		</tr>
        <tr >
		  	<TD>
			<?php 	echo tep_draw_form("f",FILENAME_SERVICES_RESOURCES_VIEW);
					echo '<input type="hidden" name="post_action" value="screen">';
			?>
			<table border="0" cellspacing="3" cellpadding="2" class="searchArea" width="100%">
				<tr valign="top"><?php $_array=array('d','m','Y');  $replace_array=array('DD','MM','YYYY'); 	$date_format=str_replace($_array,$replace_array,EVENTS_DATE_FORMAT);?>
					<td nowrap="true" width="250">
					<?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>
					</td>
					
					
					<td nowrap="true" width="250">	
					<?php echo  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>
					</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>
					<td>
						<?php echo  TEXT_RESOURCE . '&nbsp;' . tep_draw_pull_down_menu("sel_resource",$resources_array,$resource) ?>
					</td>
					<td>	
						<?php echo tep_draw_checkbox_field("chk_summary",1,$summary_show) . TEXT_SUMMARY_VIEW;?>
					</td>
					<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>
					<td valign="middle" align="right" colspan="3">
							<?php echo '<a href="javascript:doReport(3);">' . tep_image_button('button_export_excel.gif', IMG_EXPORT_EXCEL) . '</a>';?>
					</td>
				</tr>
			<!-- report content -->
		</table>
		</form>
		<br>
		</td>
	</tr>
	<tr ><td class="cell_bg_report_header">&nbsp;</td></tr>
	<?php if ($found_results) {	
				if (!$summary_view) {
	?>
			<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>
			<?php } ?>
			<tr>
				<td>
				<table border="0" width="100%" cellspacing="0" cellpadding="0">
					<?php
							for ($icnt=0;$icnt<count($details);$icnt++){
								$row=$details[$icnt];
								switch($row["type"]){
									case "F":
										echo '<tr class="dataTableHeadingTitleRow" height=20><td class="dataTableHeadingTitleContent">' .TEXT_RESOURCE_NAME . '</td><td class="dataTableHeadingTitleContent">' . TEXT_HOURS . '</td><td class="dataTableHeadingTitleContent" align="right">' . TEXT_COST . '&nbsp;&nbsp;</td>';
										echo '<tr class="dataTableHeadingTitleRow" height="20"><td class="dataTableHeadingTitleContent"><b>' . $row["rname"] . '</b></td><td class="dataTableHeadingTitleContent" width="300">' . 
												 '</td><td class="dataTableHeadingTitleContent" width="200" align="right">&nbsp;</td>';
										break;
									case "T":
										if (!$summary_view){
											echo '<tr><td>' . tep_draw_separator('pixel_trans.gif',1,5) . '</td></tr>';
										}
										echo '<tr class="dataTableHeadingTitleRow" height="20"><td class="dataTableContent"><b>' . $row["rname"] . '</b></td><td class="dataTableContent">' . 
												 '</td><td class="dataTableHeadingTitleContent" align="right"></td>';
										break;
									case "S":
										echo '<tr height="20"><td align="center" class="dataTableContent"><b>' . $row["rname"] . '</b></td><td class="dataTableContent" width="300">' . $row['hours'] . 
												 '</td><td class="dataTableHeadingTitleContent" width="200" align="right">' . $row['cost'] . '</td>';
										break;
									default:
									if($disp_class=='dataTableRow')
										$disp_class='dataTableRowOver';
									else
										$disp_class='dataTableRow';
										echo '<tr class="' . $disp_class . '"><td class="dataTableContent" height="20">' . $row["cname"] . '</td><td class="dataTableContent">' . $row["sdate"] . " - " . $row["edate"] .
											'</td><td class="dataTableHeadingTitleContent" align="right">' . $row["price"] . '</td>';
										break;
								}
							}
							echo '<tr class="dataTableHeadingTitleRow" height="20">';
							echo '<td class="dataTableHeadingTitleContent" align="center"><b>' . TEXT_TOTAL . '</b>&nbsp;&nbsp;</td>';
							echo '<td class="dataTableHeadingTitleContent"><b>' . $grand_total_hours . '</b></td>';
							echo '<td class="dataTableHeadingTitleContent" align="right"><b>' . $format_grand_total_cost . '</b></td>';
							echo '</tr>';
					?>
				</table>
				</TD>
			</tr>
	<?php }  else { ?>
			<tr>
				<td class="main" colspan="3" align="center"><?php echo TEXT_NO_DETAILS_FOUND;?></td>
			</tr>
	<?php } ?>
</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 generate_pdf(){
			global $display_header,$details,$report_filename,$grand_total_hours,$format_grand_total_cost;
						
			$table=new pdfTable("A4");
			$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:10;style:B");
			$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("rowwhite","color:#000000;bgcolor:#FFFFFF;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"]=15;
			$table->headers["width"]="100%";
			$table->headers["cols"]=3;
			$widths[1]=210;
			$widths[2]=110;
			$widths[0]=$table->width-($widths[1]+$widths[2]);
			$cols=array();			
			$cols[]=array("text"=>TEXT_RESOURCE_NAME,"width"=>$widths[0],"align"=>"L","style"=>"headrow","valign"=>"M");
			$cols[]=array("text"=>TEXT_HOURS,"width"=>$widths[1],"align"=>"L","style"=>"headrow","valign"=>"M");
			$cols[]=array("text"=>TEXT_COST,"width"=>$widths[2],"align"=>"R","style"=>"headrow","valign"=>"M");
			
			$table->tableheaders["text"]=$cols;
			unset($cols);
				
			if (count($details)<=0) {
				$cols[]=array("text"=>TEXT_NO_DETAILS_FOUND,"width"=>$table->width,"align"=>"C","style"=>"rowwhite","valign"=>"M");
				$table->OutputRow($cols,20);
				$table->Render("resources_view.pdf");
				return;
			}
			for ($kcnt=0;$kcnt<count($details);$kcnt++){
				$data=$details[$kcnt];
				switch($data["type"]){
					case "F":
					case "T":
						$cols[]=array("text"=>$data["rname"],"width"=>$widths[0],"align"=>"L","style"=>"headrow","valign"=>"M");
						$cols[]=array("text"=>"","width"=>$widths[1],"align"=>"L","style"=>"headrow","valign"=>"M");
						$cols[]=array("text"=>"","width"=>$widths[2],"align"=>"R","style"=>"headrow","valign"=>"M");
						break;
					case "S":
						$cols[]=array("text"=>$data["rname"],"width"=>$widths[0],"align"=>"L","style"=>"subrow","valign"=>"M");
						$cols[]=array("text"=>$data["hours"],"width"=>$widths[1],"align"=>"L","style"=>"subrow","valign"=>"M");
						$cols[]=array("text"=>$data["cost"],"width"=>$widths[2],"align"=>"R","style"=>"subrow","valign"=>"M");
						break;
					default:
						$cols[]=array("text"=>$data["cname"],"width"=>$widths[0],"align"=>"L","style"=>"row","valign"=>"M");
						$cols[]=array("text"=>$data["sdate"] . ' - ' . $data["edate"],"width"=>$widths[1],"align"=>"L","style"=>"row","valign"=>"M");
						$cols[]=array("text"=>$data["price"],"width"=>$widths[2],"align"=>"R","style"=>"row","valign"=>"M");
						break;
				}
				$table->OutputRow($cols,20);
				unset($cols);
			}
			$cols[]=array("text"=>TEXT_TOTAL,"width"=>$widths[0],"align"=>"L","style"=>"headrow","valign"=>"M");
			$cols[]=array("text"=>$grand_total_hours,"width"=>$widths[1],"align"=>"L","style"=>"headrow","valign"=>"M");
			$cols[]=array("text"=>$format_grand_total_cost,"width"=>$widths[2],"align"=>"R","style"=>"headrow","valign"=>"M");
			$table->OutputRow($cols,20);
			unset($cols);
			$table->Render($report_filename.".pdf");
		}

	function generate_excel(){
		global $display_header,$details,$report_filename,$grand_total_hours,$format_grand_total_cost;
		$result=sprintf("\"%s\",\"%s\",\"%s\"\n",TEXT_RESOURCE_NAME,TEXT_HOURS,TEXT_COST);
		for ($kcnt=0;$kcnt<count($details);$kcnt++){
			$row=$details[$kcnt];
			switch($row["type"]){
				case "S":
					$result.=sprintf("\"%s\",\"%s\",\"%s\"\n",$row["rname"],$row["hours"],$row["cost"]);
					break;
				case "F":
				case "T":
					$result.=sprintf("\"%s\",\"%s\",\"%s\"\n",$row["rname"],"","");
					break;
				case "R":
					$result.=sprintf("\"%s\",\"%s\",\"%s\"\n",$row["cname"],$row["sdate"] . " - " . $row["edate"],$row["price"]);
					break;
			}
		}
		$result.=sprintf("\"%s\",\"%s\",\"%s\"\n",TEXT_TOTAL,$grand_total_hours,$format_grand_total_cost);
		tep_write_text_file("$report_filename.csv",$result);
	}
?>
