<?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(DIR_WS_FUNCTIONS . 'subscription_tree.php');
  define(BOX_WIDTH1,'125');
  define('SUBSCRIPTIONS_CONDITION_STATUS',"and (su.subscription_status=1 or ( su.subscription_status=2 ) or (su.subscription_status>=3)) and date_format(su.subscription_date_available,'%Y-%m-%d')<='".getServerDate()."'");

	// 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"]!="change_status"){
				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_date_begin'])?tep_convert_date_raw($input_params['txt_date_begin']):'';
	$date_end=isset($input_params['txt_date_end'])?tep_convert_date_raw($input_params['txt_date_end']):'';
	$customer=isset($input_params['sel_customer'])?$input_params['sel_customer']:"-1";
	$subscription=isset($input_params['sel_subscription'])?$input_params['sel_subscription']:-1;
	$summary_show=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();
	
	// change the current status of selected orders
	if ($post_action=="change_status"){
		$stat_ids=$input_params["chk_status"];
		$new_status=$input_params["new_status"];
		$order_ids="";
		for ($icnt=0;$icnt<sizeof($stat_ids);$icnt++){
			$order_ids.=$stat_ids[$icnt] . ",";
		}
		if ($order_ids!=""){
			$order_ids=substr($order_ids,0,-1);
			tep_db_query("UPDATE " . TABLE_ORDERS . " set last_modified=now(),orders_status='" . $new_status . "' where orders_id in(" . $order_ids . ")");
			tep_db_query("update " . TABLE_ORDERS_PRODUCTS . " set orders_products_status= '" . $new_status . "' where orders_id = '" . (int)$order_ids . "'"); 
			tep_redirect(tep_href_link(FILENAME_UNPAID_SUBSCRIPTIONS,'return=1'));
		/*	echo tep_draw_form("frmSearch",FILENAME_UNPAID_SUBSCRIPTIONS);
			echo '<input type="hidden" name="post_action" value="screen">';
			echo tep_get_report_params();
			echo 'h';
			echo '<script language="javascript">' .
					'alert("hai");'.
					'alert(document.frmSearch);'.
				'document.frmSearch.submit();' .
				'</script></form>';
			return;*/
		}
	}

	if ($post_action==""){
		$post_action="screen";
	}
	if ($date_begin==""){
		$date_begin=getServerDate();
	}
	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 =  "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"];	
	}

	$customers_array = array();
	$subscription_array = array();
	$order_status_array=array();
	$status_array=array();
	
	// get all call centre orders
	$sql="SELECT distinct c.customers_id,concat(LTRIM(c.customers_lastname),' ',LTRIM(c.customers_firstname)) as customers_name from " . TABLE_CUSTOMERS . " c, " . TABLE_ORDERS . 
			" o where c.customers_id=o.customers_id order by customers_name";
	
	$sql_result=tep_db_query($sql);
	$customers_array[]=array("id"=>"-1","text"=>TEXT_ALL_CUSTOMERS);
	while($row=tep_db_fetch_array($sql_result)){
		$customers_array[]=array("id"=>$row["customers_id"],"text"=>$row["customers_name"]);
	}
	mysql_free_result($sql_result);

	// get the mysql results;
	$sql="SELECT orders_status_id,orders_status_name from " . TABLE_ORDERS_STATUS . " where language_id='" . $languages_id . "'";
	$sql_result=tep_db_query($sql);
	$orders_statuses=tep_get_orders_status();
	$status_array=tep_get_orders_status();
	while($row=tep_db_fetch_array($sql_result)){
		$order_status_array[$row["orders_status_id"]]=$row["orders_status_name"];
		//$status_array[]=array('id'=>$row["orders_status_id"],'text'=>$row["orders_status_name"]);
	}
	$found_results=false;
		$where = " ";
		//$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 . "')))";
		$db_result=array();
		$num_rows=0;
		$cur_row=0;
		$rows_each=REPORT_MAX_ROWS_PAGE;
		if($subscription!="-1") {
				$where.= "and su.subscription_id='".$subscription."' ";
			}
			if($customer!="-1") {
				$where.= "and o.customers_id='".tep_db_prepare_input($customer)."' ";
			}
			// create the query to fetch unpaid subscription details
			//and ((date_format(date_add(o.date_purchased,interval 0 hour),'%Y-%m-%d')>='2007-01-18' and date_format(date_add(o.date_purchased,interval 0 hour),'%Y-%m-%d')<='2007-01-25')
//OR (date_format(date_add(date_add(o.date_purchased,interval 0 hour),interval su.subscription_period day),'%Y-%m-%d')>='2007-01-18'and date_format(date_add(date_add(o.date_purchased,interval 0 hour),interval su.subscription_period day),'%Y-%m-%d')<='2007-01-25'))

			$sql = "select o.orders_id, concat(LTRIM(c.customers_lastname),' ',LTRIM(c.customers_firstname)) as customers_name,o.customers_id,
			o.customers_email_address customers_email_address, sud.subscription_name item_name,su.subscription_id as item_id,
			subscription_type, waitlist_type, orders_status,sum(op.final_price) as final_price,
			op.products_tax from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_SUBSCRIPTIONS . " su, " . TABLE_SUBSCRIPTIONS_DESCRIPTION . 
			" sud, " . TABLE_ORDERS . " o, " .TABLE_CUSTOMERS ." c," . TABLE_ORDERS_SUBSCRIPTIONS . " os where os.products_id=op.products_id and os.orders_id=o.orders_id and o.customers_id=c.customers_id and op.orders_id=o.orders_id  and sud.language_id='" . $languages_id . "'
			and op.products_id=su.subscription_id and sud.subscription_id=su.subscription_id and op.products_type='S' and o.orders_status=1 " . $where ." group by o.orders_id,su.subscription_id order by item_name,customers_name";
			
			//echo $sql;			
			if ($post_action=="screen"){
				$query_split1 = new splitPageResultsReport($page, $rows_each, $sql, $query_split_numrows1);
			}
			$db_result[$cur_row]=array("display"=>TEXT_SUBSCRIPTIONS , "result"=>tep_db_query($sql));
			$num_rows=tep_db_num_rows($db_result[$cur_row]["result"]);
			$cur_row++;
		if ($num_rows>0) {
			$found_results=true;
			if ($post_action=="screen"){
				if ($query_split_numrows1>=$query_split_numrows2){
					$query_split=&$query_split1;
				} else {
					$query_split=&$query_split2;
				}
				$query_split_numrows=$query_split_numrows1+$query_split_numrows2;
			}
		}
		
?>
<!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  require(DIR_WS_INCLUDES . 'date_format_js.php');?>
<script language="javascript">
	function showOrderDetails(id){
		location.href="orders.php?action=edit&oID="+id;
	}
	function doReport(mode) {
		strStart = document.f.txt_date_begin.value.split("-");
		startDate = new Date(strStart[0], strStart[1], strStart[2]);
	
		strEnd = document.f.txt_date_end.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();
	}
	function validate(){
		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{
			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_UNPAID_PAYMENTS;?></td>!-->
		</tr>
        <tr >
		  	<TD>
			<?php 	echo tep_draw_form("f",FILENAME_UNPAID_SUBSCRIPTIONS);
					echo '<input type="hidden" name="post_action" value="screen">';
			?>
			<table border="0" cellspacing="3" cellpadding="2" class="searchArea" width="100%">
				<tr>
					<td nowrap="true" width="30%"><?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_FROM . '&nbsp;' . tep_draw_input_field("txt_date_begin",format_date($date_begin),'maxlength="10" size="10"');?>
						<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>
					&nbsp;&nbsp;&nbsp;
						<?php echo  TEXT_TO . '&nbsp;' . tep_draw_input_field("txt_date_end",format_date($date_end),'maxlength="10" size="10"');?>

						<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>
					&nbsp;&nbsp;&nbsp;
						<?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 TEXT_SUBSCRIPTION . '&nbsp;' . tep_draw_subscription_select_menu('sel_subscription',$all_subscriptions_array,$subscription_id,' id="sel_subscription"');
						?>
					<td valign="middle" align="right">
						<?php echo '<a href="javascript:validate();">' . tep_image_button('button_report_search.gif', IMAGE_SEARCH_DETAILS) . '</a>'; ?>
					</td>
				</tr>
				
				<tr>
					<td nowrap="true" align="left">
						<?php
								echo TEXT_CUSTOMER . '&nbsp;' . tep_draw_pull_down_menu("sel_customer",$customers_array,$customer);
								echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
								echo tep_draw_checkbox_field("chk_summary",1,$summary_show) . TEXT_SUMMARY_ONLY;
						?>
					</td>
				</tr>
			<!-- report content -->
		</table>
		</form>
		<br>
		</td>
	</tr>
	<script language="JavaScript">
		function validateForm(frm){
			var err="";
			var element=frm.elements["chk_status[]"];
			if (element.length){
				for (icnt=0;icnt<element.length;icnt++){
					if (element[icnt].checked) break;
				}
				if (icnt>=element.length){
					err="<?php echo addslashes(stripslashes(ERR_SELECT_ORDER));?>";
				}
			} else {
				if (!element.checked){
					err="<?php echo addslashes(stripslashes(ERR_SELECT_ORDER));?>";
				}
			}
			if (err!="") {
				alert(err);
				return false;
			}
			return true;
		}
		function selectAll(){
			var element=document.change_status.elements["chk_status[]"];
			var status=document.change_status.chk_select.checked;
			if (element.length){
				for (icnt=0;icnt<element.length;icnt++){
					element[icnt].checked=status;
				}
			} else {
				element.checked=status;			
			}
		}
	</script>
	<?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>
	<?php } ?>
	<tr>
		<td>
	   <table border="0" width="100%" cellspacing="1" cellpadding="1">
			<?php 
				if ($found_results) {
					echo tep_draw_form("change_status",FILENAME_UNPAID_SUBSCRIPTIONS,'','post','onSubmit="javascript:return validateForm(this);"');
					echo tep_get_report_params();
					echo '<input type="hidden" name="post_action" value="change_status">';
					for ($icnt=0;$icnt<sizeof($db_result);$icnt++) {
						$sql_result=&$db_result[$icnt]["result"];
			?>
				<tr>
					<td>
					<table border="0" cellpadding="2" cellspacing="0" class="searchArea" width="100%">
						<tr>
							<td class="TableHeading"><?php echo $db_result[$icnt]["display"]?></td>
						</tr>
					</table>
					</td>
				</tr>
				<tr>
					<td><?php echo tep_draw_separator('pixel_trans.gif',1,5);?></td>
				</tr>
				<tr>
					<td>
					<table border="0" cellpadding="2" cellspacing="1" width="100%">
						<tr class='dataTableHeadingTitleRow'>
						<td>
						<table>
							<tr class="dataTableHeadingTitleRow">
								<td class='dataTableHeadingTitleContent' width="30">&nbsp;</td>
							</tr>
						</table>
						</td>
						<td>
						<table width="100%" cellpadding="0" cellspacing="1" border="0">
							<tr class="dataTableHeadingTitleRow">
								<td class='dataTableHeadingTitleContent' width="40"><?php echo TEXT_ID;?></td>
								<td class='dataTableHeadingTitleContent'><?php echo TEXT_CLIENT;?></td>
								<td class='dataTableHeadingTitleContent' width="50"><?php echo TEXT_EMAIL;?></td>
								<td class='dataTableHeadingTitleContent' width="100"><?php echo TEXT_STATUS;?></td>
								<td class='dataTableHeadingTitleContent' width="100" align="right"><?php echo TEXT_AMOUNT;?></td>
							</tr>
						</table>
						</td>
						</tr>
						<tr height="10"></tr>

			<?php
					$i=1;
					$prev_customer="";
					$prev_item=0;
					$total=0;
					$grand_total=0;
          			while($row = tep_db_fetch_array($sql_result)) {
						$customer=$row["customers_id"];
						$item=$row["item_id"];
					?>
					<?php if ($prev_item!=$item) { // output the item name
								if ($total>0) { // output the total amount
						?>
							<tr>
								<td>
								<table>
									<tr><td></td></tr>
								</table>
								</td>
								<td width="100%">
								<table width="100%" border="0">
									<tr>
										<td class="dataTableContent" align="right" width="85%">
											<b><?php echo TEXT_TOTAL;?></b>
										</td>
										<td align="right" class='dataTableContent'>
											<?php echo $currencies->format($total);
												$total=0;
											?>
										</td>
									</tr>
								</table>
								</td>
							</tr>
							<tr>
								<td colspan="6"><?php echo tep_draw_separator();?></td>
							</tr>
						<?php } // total >0 ?>
							<tr>
								<td class="dataTableContent" colspan="6"><b>
									<?php
										echo $row["item_name"];
										$prev_item=$item;
									?>
									</b>
								</td>
							</tr>
					<?php 
					} // prev item 
						$amount=tep_add_tax($row['final_price'],$row["products_tax"]);
						$amount=tep_get_rounded_amount($amount);
						if (!$summary_show) {
					?>
					<tr>
						<td>
						<table border="0">
							<tr class="dataTableRow" height="20">
								  <td class='dataTableContent'><?php echo tep_draw_checkbox_field('chk_status[]',$row["orders_id"]);?></td>	
							</tr>
						</table>
						</td>
						<td width="100%">
						<table width="100%" cellpadding="2" cellspacing="1" border="0">
						  <tr class='dataTableRow' height="20" onMouseOver="rowOverEffect(this)" onMouseOut="rowOutEffect(this)" onClick="javascript:location.href='<?php echo tep_href_link(FILENAME_ORDERS,'oID=' . $row["orders_id"] . '&action=edit&return=up_sub');?>';">
							  <td class='dataTableContent' style="cursor:hand" width="40"><?php echo $i?></td>
							  <td class='dataTableContent' style="cursor:hand"><?php echo $row['customers_name']?></td>
							  <td class='dataTableContent' align="center" width="50"><a href="mailto:<?php echo $row['customers_email_address']?>"><img src="images/icons/mail.gif" border="0"></a></td>
							  <td class='dataTableContent' style="cursor:hand" width="100"><?php echo $order_status_array[$row['orders_status']];?></td>
							  <td class='dataTableContent' style="cursor:hand" width="100" align="right"><?php echo $currencies->format($amount);?></td>
						  </tr>
						</table>
						</td>
					</tr>
			<?php 
						} // summary show
						$i++;
						$total+=$amount;
						$grand_total+=$amount;
						}
						if ($total>0) {
						?>
							<tr>
								<td>
								<table>
									<tr><td></td>
								</tr>
								</table>
								</td>
								<td>
								<table width="100%">
									<tr>
										<td class="dataTableContent" style="cursor:hand" width="85%" align="right">
											<b><?php echo TEXT_TOTAL;?></b>
										</td>
										<td style="cursor:hand" align="right" class='dataTableContent'>
											<?php echo $currencies->format($total);
												$total=0;
											?>
										</td>
									</tr>
								</table>
								</td>
							</tr>
							<tr>
								<td colspan="6"><?php echo tep_draw_separator();?></td>
							</tr>
						<?php } // total >0 
						if ($grand_total>0) {
						?>
							<tr>
								<td>
								<table>
									<tr><td></td>
								</tr>
								</table>
								</td>
								<td>
								<table width="100%">
									<tr>
										<td class="dataTableContent" style="cursor:hand" width="85%" align="right">
											<b><?php echo TEXT_GRAND_TOTAL;?></b>
										</td>
										<td style="cursor:hand" align="right" class='dataTableContent'>
											<?php echo $currencies->format($grand_total);
											?>
										</td>
									</tr>
								</table>
								</td>
							</tr>
						<?php } // grand total >0 ?>
				</table>
				</td>
			</tr>
			<tr>
				<td><?php echo tep_draw_separator('pixel_trans.gif',1,5);?></td>
			</tr>
			<?php
					}
				if (!$summary_show) {
			?>
					<tr><td class="bottomLine">&nbsp;</td></tr>
					<tr>
						<td class="main" valign="top">
							<?php  echo '<input type="checkbox" name="chk_select" value="1" onClick="javascript:selectAll();">&nbsp;' . TEXT_SELECT_ALL . '&nbsp;&nbsp;'; ?>
						</td>
					</tr>
					<tr>
						<td><?php echo tep_draw_separator('pixel_trans.gif',1,5);?></td>
					</tr>
					<tr>
						<td class="main" valign="middle">
						<?php 
								echo tep_image_submit('button_change_status.gif',IMAGE_CHANGE_STATUS,'align=absmiddle') . '&nbsp;&nbsp;';
								echo tep_draw_pull_down_menu('new_status',$status_array);
						?>
						</td>
					</tr>
				<?php } ?>
				</form>	
			<?php
				}//found_results
				else{
					echo '<tr><td class="main" align="center">' . TEXT_NO_SUBSCRIPTION_FOUND . '</td></tr>';
				}
			?>
	</table>
	</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'); 

?>