<?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');
  
	// get the type of action
	
	$action=isset($HTTP_POST_VARS["action"])?$HTTP_POST_VARS["action"]:'';
	$tx_id=isset($HTTP_POST_VARS["survey_id"])?$HTTP_POST_VARS["survey_id"]:'';

	if ($tx_id==0) tep_redirect(tep_href_link(FILENAME_EVENTS_REPORTS_SURVEYS));
	
	$tx_report_type=isset($HTTP_POST_VARS["survey_report_type"])?(int)$HTTP_POST_VARS["survey_report_type"]:0;
	$tx_report_from=isset($HTTP_POST_VARS["survey_report_from"])?$HTTP_POST_VARS["survey_report_from"]:'';
		
	// build the additional options to query
	$add_option=" ";
	if ($tx_report_from!="") $add_option=" and suf.survey_flag_date>='" . $tx_report_from . "' ";
	if ($tx_report_to!="") $add_option.=" and suf.survey_flag_date<='" . $tx_report_to . "' ";

	$file_name="surveys_reports_" . strtolower(constant("REPORT_TYPE_" . $tx_report_type)) . ".csv";
	$file_path=DIR_FS_CATALOG . "images/" . $file_name;
	$file_created=create_file($file_path);
?>
<!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>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0">
<Div id="siffyCalendar"></Div>
<table border="0" width="100%" cellspacing="0" cellpadding="8"  class="formArea" height="100%">
	<tr>
		<td width="100%" valign="top">
		<?php if ($file_created) {?>
		<script language="javascript">
			function changeLink(mode){
				if (mode==1)
					document.getElementById("links_submit").className="linkover";
				else
					document.getElementById("links_submit").className="linkout";
			}
		</script>

		<table border="0" width="100%" cellspacing="0" cellpadding="2">
				<tr>
					<td class="main">
						<table border="0" cellpadding="2" cellspacing="0" class="formArea" width="100%">
							<tr>
								<td class="pageHeading" align="center"><?php echo sprintf(HEADING_TITLE,constant('REPORT_TYPE_' . $tx_report_type)); ?></td>
							</tr>
						</table>
					</td>
				</tr>
				<tr>
					<td><?php echo tep_draw_separator('pixel_trans.gif','1','5'); ?></td>
				</tr>
				<tr>
					<td class="main"><?php echo TITLE_DESCRIPTION;?></td>
				</tr>
				<tr>
					<td class="main">
						<table border="0" cellpadding="4" cellspacing="5">
							<tr>
								<td class="main"><?php echo '<a href="' . tep_catalog_href_link("images/" . $file_name) . '">' . tep_image(DIR_WS_IMAGES . "excel.gif",IMAGE_DOWNLOAD) . '</a>';?></td>
								<td class="main">
								<?php echo '<span onclick="javscript:location.href=\'' . tep_catalog_href_link("images/" . $file_name) . '\';" id="links_submit" onMouseOver="javascript:changeLink(1)" onMouseOut="javascript:changeLink(2)" class="linkout">' . LINK_DOWNLOAD . '</span>';
										echo TEXT_DOWNLOAD;
								?>
								</td>
							</tr>
						</table>
					</td>
				</tr>
				<tr>
					<td class="main">
						<table border="0" cellpadding="2" cellspacing="0" class="formArea" width="100%">
							<tr>
								<td class="main" align="center"><?php echo '<a href="javascript:;" onClick="javscript:window.close();">' . tep_image_button('button_close.gif',IMAGE_CLOSE) . '</a>';?></td>
							</tr>
						</table>
					</td>
				</tr>
				 <tr>
				 <td>
					<!-- footer //-->
					<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
					<!-- footer_eof //-->
				</td>
				</tr>
		</table>
<!-- body_text_eof //-->
	<?php } else { ?>
		<table border="0" width="100%" cellspacing="0" cellpadding="2">
				<tr>
					<td class="main">
						<table border="0" cellpadding="2" cellspacing="0" class="formArea" width="100%">
							<tr>
								<td class="pageHeading" align="center"><?php echo sprintf(HEADING_TITLE,constant('REPORT_TYPE_' . $tx_report_type)); ?></td>
							</tr>
						</table>
					</td>
				</tr>
				<tr>
					<td><?php echo tep_draw_separator('pixel_trans.gif','1','5'); ?></td>
				</tr>
				<tr>
					<td class="errorText" align="center">
						<?php echo TEXT_NO_FILE_PERMISSION;?>
					</td>
				</tr>
		</table>					
	<?php }?>
		</td>
	 </tr>
</table>
<!-- body_eof //-->
</body>
</html>

<?php	
	require(DIR_WS_INCLUDES . 'application_bottom.php'); 

	function create_file($file_path){
	//header('Content-type: application/vnd.ms-excel');
	//header('Content-Disposition: attachment; filename="surveys_reports_' . strtolower(constant("REPORT_TYPE_" . $tx_report_type)) . '.csv"');
	global $tx_report_type;
		$handle=fopen($file_path,"w");
		if (!$handle) return false;
		
		if ($tx_report_type==1){ // summary report
			// get the questions for selected survey
			$result=output_summary();
	
		} else if($tx_report_type==2) {
			$result=output_detail();
		}
		fwrite($handle,$result,strlen($result));
		fclose($handle);
		return true;
	}
	 
	 
	 function output_summary(){
	 	global $tx_id,$add_option;
		$result="";
		$question_query=tep_db_query("SELECT * from " . TABLE_EVENTS_SURVEYS_QUESTION . " where survey_id='" . $tx_id . "' and (question_type=6 or question_type<4) order by question_id");
		if (tep_db_num_rows($question_query)<=0){
			$result.=sprintf("\"%s\",,,\n",SURVEY_NO_QUESTIONS);
			return;
		}
		$result.=sprintf("\"%s\",\"%s\",\"%s\",\"%s\"\n",SUMMARY_QUESTION,SUMMARY_CHOICE ,SUMMARY_TOTAL ,SUMMARY_PERCENT);
		$row=1;
		$found_question=false;
		while($question=tep_db_fetch_array($question_query)){
			if ( $question["question_type"]==6){ // if question type is heading
				$result.=sprintf("\"%s\",,,\n",$question["question_text"]);
				$found_question=true;
			} else if ($question["question_type"]<4) { // if question type is multiple choice
				$result.=sprintf("\"%ld. %s\",,,\n",$row,$question["question_text"] . ($question["question_required"]==1?TEXT_REQUIRED:''));
				// get the total count of choice for current question
				$total_query=tep_db_query("SELECT count(sua.choice_id) as total from " . TABLE_EVENTS_SURVEYS_FLAG . " suf, " . TABLE_EVENTS_SURVEYS_ANSWER . " sua where sua.question_id='" . $question['question_id'] . "' " . $add_option . " and suf.survey_flag_id=sua.survey_flag_id group by sua.question_id");
				$total_result=tep_db_fetch_array($total_query);
				$total_count=(int)$total_result["total"];
				
				// get the choices for the question
				$choice_query=tep_db_query("SELECT choice_id,choice_text from " . TABLE_EVENTS_SURVEYS_CHOICE . " where question_id='" . $question["question_id"] . "' order by choice_id");
				if (tep_db_num_rows($choice_query)>0) {
					$row2=0;
					while($choice=tep_db_fetch_array($choice_query)){
						// get the total for the current choice
						$choice_total_query=tep_db_query("SELECT count(sua.choice_id) as total from " . TABLE_EVENTS_SURVEYS_FLAG . " suf, " . TABLE_EVENTS_SURVEYS_ANSWER . " sua where sua.choice_id='" . $choice['choice_id'] . "' " . $add_option . " and suf.survey_flag_id=sua.survey_flag_id group by sua.choice_id");
						$choice_total_result=tep_db_fetch_array($choice_total_query);
						$choice_total_count=(int)$choice_total_result['total'];
						$percent=0;
						if ($total_count>0)
							$percent=number_format($choice_total_count/$total_count*100,0);
						
						$result.=sprintf(",\"%s\",%ld,%d%%\n",$choice["choice_text"],$choice_total_count,$percent);
						$row2++; 
					}
					$result.=sprintf(",\"%s\",%ld,\n",TOTAL_CHOICE_QUESTIONS,$total_count);
				}
				$found_question=true;
			}
			 if ($question['question_type']!=6)$row++;
		}
		return $result;
	 }
	 function output_detail(){
	 	global $tx_id,$add_option;	
		$survey_flag_query=tep_db_query("SELECT survey_flag_id from " . TABLE_EVENTS_SURVEYS_FLAG . " suf where suf.survey_id='" . $tx_id . "' " . $add_option);
		$found_results="SURVEY";
		if (tep_db_num_rows($survey_flag_query)<=0)  $found_results=SURVEY_NO_DETAILS;
		
		// get all the questions to be found for this survey
		$question_query=tep_db_query("SELECT * from " . TABLE_EVENTS_SURVEYS_QUESTION . " where survey_id='" .$tx_id ."'");
		if (tep_db_num_rows($question_query)<=0)  $found_results=SURVEY_NO_QUESTIONS;
		if ($found_results!="SURVEY") { // if both survey_flag and questions found
			$result.=$found_results;
			return;
		}
		
		$row=1;
		while($survey_flag=tep_db_fetch_array($survey_flag_query)){
			$result.=sprintf("\"%s\"\n",SURVEY_ID . $row);
			$row2=1;
			$cur_row=0;
			tep_db_data_seek($question_query,0);
			while($question=tep_db_fetch_array($question_query)){
				// display question detail
				if ($question['question_type']==6) { 
					$result.=sprintf("\"%s\"\n",$question['question_text']);
				} else {
					$result.=sprintf("\"%d. %s\"\n",$row2,$question["question_text"] . ($question["question_required"]==1?TEXT_REQUIRED:''));
				}
				$answer_text="";
				if ($question["question_type"]<=3) {// if type is single radio or pull down choice or multiple choice
					$answer_query=tep_db_query("SELECT suc.choice_text from " . TABLE_EVENTS_SURVEYS_ANSWER . " sua, " . TABLE_EVENTS_SURVEYS_CHOICE . " suc where sua.survey_flag_id='" . $survey_flag["survey_flag_id"] . "' " .
												"and sua.question_id='" . $question["question_id"] . "' and sua.choice_id=suc.choice_id order by suc.choice_id");
					if (tep_db_num_rows($answer_query)>0){
						while($answer=tep_db_fetch_array($answer_query)){
							if ($answer_text!="") $answer_text.=", ";
							$answer_text.=$answer["choice_text"];
						}
					} else {
						$answer_text=QUESTION_NO_ANSWER;
					}
				} else if ($question["question_type"]==4 || $question["question_type"]==5) {// if type is text answer
					$answer_query=tep_db_query("SELECT answer_text from " . TABLE_EVENTS_SURVEYS_TEXT . " where survey_flag_id='" . $survey_flag["survey_flag_id"] . "' and question_id='" . $question["question_id"] . "'");
					if (tep_db_num_rows($answer_query)>0){
						$answer=tep_db_fetch_array($answer_query);
						$answer_text=$answer["answer_text"];
					} else {
						$answer_text=QUESTION_NO_ANSWER;
					}
				}
				if ($question['question_type']!=6) {
					$result.=sprintf("\"%s\"\n",$answer_text);
					$row2++; 
				} // question type if
			$cur_row++;
			} //question while
			$row++;
		} //survey while
		return $result;
	 }
?>