<?php
include("../adodb/adodb.inc.php");
include('../adodb/tohtml.inc.php'); # load code common to ADOdb 
include_once("../adodb/toexport.inc.php");

// css stylesheet
	$header = <<<EOD
<html>
<head>
<title>UAI Mantis Reports</title>	
<STYLE TYPE="text/css">
  TABLE { border-collapse: collapse; white-space:normal}
  TR#Header { text-align: center; background-color: lightblue }
  TR#Even { background-color: silver }
  TR#Odd { background-color: lightgrey }
  TD { border: 1px solid grey; padding: 2}
  TD#C { border: 1px solid grey; padding: 2; text-align: center}
  TD#L { border: 1px solid grey; padding: 2; text-align: left}
  TD#R { border: 1px solid grey; padding: 2; text-align: right}
  TD#M { border: 1px solid grey; padding: 2; text-align: "$"}
  TD#D { border: 1px solid grey; padding: 2; text-align: "."}
  TH { border: 1px solid grey; padding: 2}
  DIV.title {font-size: x-large}
</STYLE>
</head>
<body>
<a href="/reports/index.php">UAI Mantis Reports</a><br>
EOD;

	$footer = <<<EOD
<br>
<a href="/reports/index.php">UAI Mantis Reports</a><br>
</body>
</html>
EOD;

	if ($_REQUEST['id'] != '') {
		header("Pragma: no-cache");
		header("Expires: 0"); 

		$conn = NewADOConnection('mysql');
		 
		$conn->Connect("localhost", "uid", "pwd", "bugtracker");
	
		$rs = $conn->Execute('SELECT id, name, form, `sql` FROM custom_report where id='.$_REQUEST['id']);
	 
		if (!$rs) 
			print $conn->ErrorMsg();
		else
		while (!$rs->EOF) {
					
			if ($rs->fields['form'] == '') {
				// copy form variables into sql
				$sql = $rs->fields['sql'];
				
				foreach (array_keys($_REQUEST) as $rname) {
					$sql = str_replace("<%".$rname."%>", $_REQUEST[$rname], $sql);
				}


				if (array_key_exists('csv', $_REQUEST)) {
					header("Content-Type: text/x-csv");
					header("Content-Disposition: attachment; filename=\"".$rs->fields['name'].".csv\"");
					execSql2CSV($conn, $sql);
				} else {
					print $header;
					//print "<pre>".$sql."</pre>\n";
					print "<div class=title>".$rs->fields['name']."</div><br>\n";
					execSql($conn, $sql);
					print $footer;
				}
			} else {
				if (array_key_exists('exec', $_REQUEST)) {
					
					// copy form variables into sql
					$sql = $rs->fields['sql'];
					
					foreach (array_keys($_REQUEST) as $rname) {
						$sql = str_replace("<%".$rname."%>", $_REQUEST[$rname], $sql);
					}
					
					//print "<pre>$sql</pre>";
					
					// if we have defined csv then return that
					if (array_key_exists('csv', $_REQUEST)) {
						header("Content-Type: text/x-csv");
						header("Content-Disposition: attachment; filename=\"".$rs->fields['name'].".csv\"");
						execSql2CSV($conn, $sql);
					} else {
						// otherwise return html
						print $header;
						print "<div class=title>".$rs->fields['name']."</div><br>\n";
						execSql($conn, $sql);
						print $footer;
					}
				} else {
					print $header;
					print "<div class=title>".$rs->fields['name']."</div><br>\n";
					// display form
					displayForm($rs->fields['id'], $rs->fields['form']);
					print $footer;
				}
			
			}
		
			$rs->MoveNext();
		}
		$rs->Close(); # optional
		$conn->Close(); # optional
	} 
		else
	{
		print 'cannot execute empty id';
	}
	

	function displayForm($id, $form)
	{
		$formheader = <<<EOD
<form action="exec.php">
EOD;
		
		$formfooter = <<<EOD
<BR>
<input type="checkbox" name="csv"> Export to Excel<br>
<input type="submit" name="B1" value="Submit"><input type="reset" name="B2" value="Reset"><br>
<input type="hidden" name="exec" value="1">
<input type="hidden" name="id" value="$id">
</form>
EOD;

		print $formheader.$form.$formfooter;
	}
	
	function parsFieldPrepend($fields)
	{
		$formatting = array();
		
		foreach (array_keys($fields) as $fname)
		{
			if (ereg('^([L|R|C|M|D])_.*',$fname, $m))
			{
				$formatting[$fname] = $m[1];
			}
		}
		
		return $formatting;
	}
	
	function clearFieldPrepend($field)
	{
			if (ereg('^[L|R|C|M|D]_(.*)',$field, $m))
			{
				return $m[1];
			} else {
				return $field;
			}
	}
	
	
	function execSql2CSV($conn, $sql)
	{
		$conn->SetFetchMode(ADODB_FETCH_ASSOC);
		
		$rs = $conn->Execute($sql);

		if (!$rs) 
			print $conn->ErrorMsg();
		else
		{			
			$s = "";
			// print field names
			foreach (array_keys($rs->fields) as $fname) 
			{
				if (strlen($s) > 0) $s = "$s,";	// append a comma if this isnt the first column
				
				
				// print the column names without the formatting prepended text
				$s = "$s\"".clearFieldPrepend($fname)."\"";
			}
			print $s."\n";

			while (!$rs->EOF) {

				$s = "";
				// print field names
				foreach (array_keys($rs->fields) as $fname) 
				{
					if (strlen($s) > 0) $s = "$s,";	// append a comma if this isnt the first column
					
					$s = $s.'"'.str_replace('"', '""', $rs->fields[$fname]).'"';
				}
				print "$s\n";
		
				$rs->MoveNext();
			}
		}
	}
	
	function execSql($conn, $sql)
	{
		$conn->SetFetchMode(ADODB_FETCH_ASSOC);
		
		$rs = $conn->Execute($sql);

		if (!$rs) 
			print $conn->ErrorMsg();
		else
		{
			// get the formatting array from the field names
			// if the field name is prepended with
			// C_ the column is centered
			// R_ right aligned
			// L_ left aligned
			// M_ aligned with the $
			// D_ aligned with the . in a number
			$formatting = parsFieldPrepend($rs->fields);
			
			// print table definition
			print "<table id=\"results\">\n";
	
 			print "<tr id=\"header\">\n";
			// print field names
			foreach (array_keys($rs->fields) as $fname) 
			{
				// print the column names without the formatting prepended text
				print "  <th>".clearFieldPrepend($fname)."</th>\n";
			}
			print "</tr>\n";

			$i = 0;

			while (!$rs->EOF) {
				
				if ($i % 2 == 0)
				{				
					print "<tr id=\"even\">\n";
				} else {
					print "<tr id=\"odd\">\n";
				}
				
				$i++;
				
				
				// print field names
				foreach (array_keys($rs->fields) as $fname) 
				{
					if (array_key_exists($fname, $formatting)) {
						$tdclass = " id={$formatting[$fname]}";
					} else {
						$tdclass = "";
					}
					
					print "  <td$tdclass>{$rs->fields[$fname]}</td>\n";
				}
				print "</tr>\n";
		
				$rs->MoveNext();
			}
			
			// print table close
			print "</table>\n";
		}
	}
?>