<?php
	function check_array_parameter($parameter, $val){
		if(isset($_POST[$parameter])){
			foreach($_POST[$parameter] as $element){
				if ($element==$val){
					return true;
				}  
			}
		}
		return false;
	}
	
	function reverse_date($date){
		$date_arr = explode(" ", $date);
		$date_arr2 = explode("-", $date_arr[0]);
		return $date_arr2[2]."-".$date_arr2[1]."-".$date_arr2[0]." ".$date_arr[1];
	}
	
	$today = date("d-m-Y");
?>

<html>
<head>
	
	<!-- <script language="javascript" type="text/javascript" src="js/jqplot/jquery.min.js"></script> -->
	<script language="javascript" type="text/javascript" src="js/jqplot/jquery.jqplot.min.js"></script>
	<link rel="stylesheet" type="text/css" href="js/jqplot/jquery.jqplot.css">
	
	<!-- pie -->
	<script type="text/javascript" src="js/jqplot/plugins/jqplot.pieRenderer.min.js"></script>
	<script type="text/javascript" src="js/jqplot/plugins/jqplot.donutRenderer.min.js"></script>	
	
	<!-- axis with labels -->
	<script type="text/javascript" src="js/jqplot/plugins/jqplot.dateAxisRenderer.min.js"></script>
	<script type="text/javascript" src="js/jqplot/plugins/jqplot.canvasTextRenderer.min.js"></script>
	<script type="text/javascript" src="js/jqplot/plugins/jqplot.canvasAxisTickRenderer.min.js"></script>
	<script type="text/javascript" src="js/jqplot/plugins/jqplot.categoryAxisRenderer.min.js"></script>
	<script type="text/javascript" src="js/jqplot/plugins/jqplot.barRenderer.min.js"></script>
	
	<!-- chart with point labels -->	
	<script type="text/javascript" src="js/jqplot/plugins/jqplot.barRenderer.min.js"></script>
	<script type="text/javascript" src="js/jqplot/plugins/jqplot.categoryAxisRenderer.min.js"></script>
	<script type="text/javascript" src="js/jqplot/plugins/jqplot.pointLabels.min.js"></script>
	
	<style>
		#stats_table{
			font-family: Tahoma, Arial, Verdana;
			font-size: 12px;
			border-collapse: collapse;
			border: 2px solid grey;
			margin-left: 50px;
		}
		#stats_table caption{
			font-size: 18px;
			font-weight: normal;
			color: #666;
		}
		#stats_table th, .date_div{
			font-size: 12px;
			font-weight: bold;
			padding: 8px;	
			color: #2a6496;
		}
		#stats_table td{
			padding: 8px;
			color: #555;
			border-bottom: 1px solid #ccc;
		}
		#stats_table tr:nth-child(odd) {
			background: #ffffff;
		}

		#stats_table tr:nth-child(even) {
			background: #E6E7EB;
		}
		#stats_table thead th{
			background: #ffffff;
			border-bottom: 2px solid grey;
		}
		#stats_table tfoot td{
			color: #2a6496;
			border-top: 2px solid grey;
			background: #ffffff;
			font-weight: bold;
		}
	</style>
	
	<script type="text/javascript">
		$(document).ready(function(){			
			// ----------------------------- Max instances per study (Checkbox)	

			// Accept only numbers
			$(".onlynumber").keypress(function(evt){
				var charCode = (evt.which) ? evt.which : event.keyCode
				if (charCode > 31 && (charCode < 48 || charCode > 57))
					return false;	
			});
			
			// Spinner number rotation
			$('#max_instances').spinner({min:"0", max:"10010", step:"10", 
				spin: function( event, ui ) {
					if ( ui.value > 10000 ) {
					  $( this ).spinner( "value", 10 );
					  return false;
					} else if ( ui.value < 10 ) {
					  $( this ).spinner( "value", 10000 );
					  return false;
					}
				}
			});
			
			// Enable / Disable spinner input
			if($('#chk_max_instances').get(0).checked == true){
				$('.max_instance_container').css("color","black");
				$('#max_instances').spinner( "enable" );
			}
			else{
				$('.max_instance_container').css("color","gray");
				$('#max_instances').spinner( "disable" );
			}
			$('#chk_max_instances').click(function(){
				if($('#chk_max_instances').get(0).checked == true){
					$('.max_instance_container').css("color","black");
					$('#max_instances').spinner( "enable" );
				}
				else{
					$('.max_instance_container').css("color","gray");
					$('#max_instances').spinner( "disable" );
				}
			});
			
			// ---- Expand - Collapse button
			$('.expand_bar').click(function(){
				$.ajax({
					url: "ajax/menu/statistics_form_state.php",
					type: 'POST',
					cache: false
				}).done(function(){
					$('.expand_bar .arrows').toggleClass('pressed');
					$("#search_examination_container").slideToggle(300);
				});
			});

			<?php
				if(isset($_COOKIE["statistics_form_state"]) && $_COOKIE["statistics_form_state"]=="hidden"){
			?>
				$('.arrows').addClass('pressed');
				$("#search_examination_container").hide();
			<?php
				}
				else{
			?>
				$('.arrows').removeClass('pressed');
				$("#search_examination_container").show();
			<?php	
				}
			?>

		});		
	</script>
	
</head>

<body>

	<div class="expand_bar <?php print($additional_class); ?>">	
		Στατιστικά 
		<div class="arrows"></div>
	</div>
	
	<div id="search_examination_container" class="<?php print($additional_class); ?>">
		
		<!----Search Form------->
		<form method="POST">
			<input type="hidden" name="cp" value="statistics">
			<table>
				<thead>
					<tr>
						<th>Παράμετρος α</th>
						<th>Παράμετρος β</th>						
						<th>
							<select name="date_type" id="date_type">
							  <option value="exam" <?php ((isset($_POST['date_type']) && $_POST['date_type']=='exam')?print('selected'):print(''))?> >Ημερομηνίες Εξέτασης</option>
							  <option value="db" <?php ((isset($_POST['date_type']) && $_POST['date_type']=='db')?print('selected'):print(''))?>>Ημερομηνίες Καταχώρησης</option>
							</select>
						</th>						
						<th>Επιλογή γραφήματος</th>
						<th></th>
					</tr>
				</thead>

				<tbody>
				<tr>
					<!-- Factor a -->
					<td>
						<br>
						<select name="factor_a" id="factor_a">
						  <option value="Number_of_Examinations" <?php ((isset($_POST['factor_a']) && $_POST['factor_a']=='Number_of_Examinations')?print('selected'):print(''))?>>Αριθμός Εξετάσεων</option>
						</select>					
						
						<div class="max_instance_container" style="color:gray;">
							<hr>
							<input type="checkbox" name="chk_max_instances" id="chk_max_instances" <?php (isset($_POST['chk_max_instances'])?print("checked"):print("")) ?>> Φιλτράρισμα για εξετάσεις με <br> περισσότερες από 
							<input id="max_instances" class="onlynumber" type="text" name="max_instances" maxlength="5" size="5" placeholder="0" value="<?php (isset($_POST['max_instances'])?print(htmlspecialchars($_POST['max_instances'], ENT_QUOTES)):print("0")) ?>">
							εικόνες
						</div>
					</td>
					
					<!-- Factor b -->
					<td>
						<br>
						<select name="factor_b" id="factor_b">							
							<option value="Modality" <?php ((isset($_POST['factor_b']) && $_POST['factor_b']=='Modality')?print('selected'):print(''))?> >Διαγνωστική Μονάδα</option>
							<option value="Station_Name" <?php ((isset($_POST['factor_b']) && $_POST['factor_b']=='Station_Name')?print('selected'):print(''))?>>Όνομα Διαγνωστικής Μονάδας</option>
							<option value="Referring_Doctor" <?php ((isset($_POST['factor_b']) && $_POST['factor_b']=='Referring_Doctor')?print('selected'):print(''))?>>Παραπέμπων Ιατρός</option>
							<option value="dates_exam" <?php ((isset($_POST['factor_b']) && $_POST['factor_b']=='dates_exam')?print('selected'):print(''))?> >Ημερομηνία Εξέτασης</option>
							<option value="dates_db" <?php ((isset($_POST['factor_b']) && $_POST['factor_b']=='dates_db')?print('selected'):print(''))?> >Ημερομηνία Καταχώρησης</option>
						</select>					
					</td>
					
					<!-- ΕΧΑΜΙΝΑΤΙΟΝ DATES -->
					<td>
						<div>Από</div>
						<div>
							<input type="text" size="8" name="order_date" id="order_date" value="<?php (isset($_POST['order_date'])?print(htmlspecialchars($_POST['order_date'], ENT_QUOTES)):print(""));?>" >
						</div>
						<br>
						<div>Έως</div>
						<div>
							<input type="text" size="8" name="order_date_to" id="order_date_to" value="<?php (isset($_POST['order_date_to'])?print(htmlspecialchars($_POST['order_date_to'], ENT_QUOTES)):print(date( "d-m-Y",strtotime( "$today + 0 day"))));?>" >
						</div>
					</td>
								
					<!-- Graph -->
					<td width="150px">
					<!--	<input type="checkbox" name="graph[]" value="table" <?php (check_array_parameter('graph', 'table')?print('checked'):print(''))?>> <span>Πίνακας</span>	
						<br>  -->
						<input type="checkbox" name="graph[]" value="bar" <?php (check_array_parameter('graph', 'bar')?print('checked'):print(''))?>> <span class="graphs <?php print($additional_class); ?>">Στήλες</span> 
						<br>
						<input type="checkbox" name="graph[]" value="pie" <?php (check_array_parameter('graph', 'pie')?print('checked'):print(''))?>> <span class="graphs <?php print($additional_class); ?>">Πίτα</span>
						<br>
						<!-- <input type="checkbox" name="graph[]" value="line" <?php (check_array_parameter('graph', 'line')?print('checked'):print(''))?>> <span>Γραμμή</span>	-->						
					</td>
					
					<td style="text-align:center;">
						<button class="button_blue <?php print($additional_class); ?>" type="submit" id="search_submit_button"><i class="big_icon fa fa-search fa-flip-horizontal"></i> Αναζήτηση</button>
					</td>
						
				</tr>
				</tbody>
			</table>
		</form>
	</div>
	<br>

<?php	

if(isset($_POST['factor_a'])){
	show_statistics();
}

function show_statistics(){

	global $additional_class;
	global $userid;
	global $usergroup;	
	global $referring;
	global $institution;
	
	global $institution_name;
	global $src_aet;
	global $domain_name;
	
	global $dbh;
	
	if($usergroup == 'Management'){	
	
		if(isset($_POST['order_date'])){
			$date = (reverse_date($_POST['order_date']))." 00:00:00";
		}else{
			$date = "";
		}
		
		if(isset($_POST['order_date_to'])){
			$date_to = (reverse_date($_POST['order_date_to']))." 23:59:59";
		}else{
			$date_to = date("Y-m-d")." 23:59:59";
		}	
		
		$sql = "";

		if($_POST['date_type']=='exam'){
			$dat = "study_datetime";
			$date_type = "study.created_time";
		}else{	
			$dat = "study.created_time";
			$date_type = "study_datetime";
		}	
		
		$from = "study left join series on study_fk=study.pk";	
		
		if($_POST['factor_a'] == 'Number_of_Examinations' ){
			if($_POST['factor_b'] == 'Modality'){	
				$factor_b = "mods_in_study";
				$table = "study";
				$select = "mods_in_study, count(distinct study.pk) as count, study.num_instances";							
			}	
			if($_POST['factor_b'] == 'Station_Name'){	
				$factor_b = "station_name";
				$table = "series";
				$select = "station_name, count(distinct study.pk) as count, study.num_instances ";						
			}							
			if($_POST['factor_b'] == 'Referring_Doctor'){	
				$factor_b = "ref_physician";
				$table = "study";
				$select = "ref_physician, count(distinct study.pk) as count, study.num_instances ";					
			}	
			if( ($_POST['factor_b'] == 'dates_exam' && $_POST['date_type']=='exam') || ($_POST['factor_b'] == 'dates_db' && $_POST['date_type']=='db') ){	
				//$factor_b = $dat;		
				$factor_b = "DATE_FORMAT(".$dat.", '%d-%m-%Y')";
				$table = "study";
				$select = "DATE_FORMAT(".$dat.", '%d-%m-%Y') as `date`, count(distinct study.pk) as count, study.num_instances ";						
			}	
			if( ($_POST['factor_b'] == 'dates_exam' && $_POST['date_type']=='db') || ($_POST['factor_b'] == 'dates_db' && $_POST['date_type']=='exam') ){	
				//$factor_b = $dat;		
				$factor_b = $date_type;
				$table = "study";
				$select = "count(distinct study.pk) as count, DATE_FORMAT(".$date_type.", '%d-%m-%Y') as date,  study.num_instances ";	
			}	
		}
		
		$output = array();
		$values = array();
		$keys = array();
		$mod = array();
		
		$null_value = ')';
		$factorb_values = '';
		$x = '';
		
		if(!($_POST['factor_b'] == 'dates_exam'  || $_POST['factor_b'] == 'dates_db')){
			
			$sth = $dbh->prepare("SELECT DISTINCT $factor_b FROM $table;");
			$sth->execute();
			$sth->setFetchMode(PDO::FETCH_ASSOC);
		
			while($row = $sth->fetch()){	
									
				if($row[$factor_b] != null){
					if ($factorb_values==''){
						$factorb_values = "?";
						$params[]=$row[$factor_b];
					}
					else{
						$factorb_values = $factorb_values.",?";						
						$params[]=$row[$factor_b];
					}
				}else{
					$null_value = " OR ".$factor_b." is null)";
				}
			}
			
			$x = "(".$factor_b." IN ($factorb_values)".$null_value;	
		}
		
		
		$max = '';
		
		if(isset($_POST['max_instances'])){
			$x = $x." and study.num_instances >= ? ";
			$max = " and study.num_instances >= ? ";
			$params[]= $_POST['max_instances'];
		}
		$where = "where $x and $dat >= ? and $dat <= ?";
		$order = "count";
		
		if(($_POST['factor_b'] == 'dates_exam' && $_POST['date_type']=='exam') || ($_POST['factor_b'] == 'dates_db' && $_POST['date_type']=='db')){
			$params = array();
			$where = "where ".$dat." >= ? and ".$dat." <= ?".$max;						
			$order = $dat;
			$factor_b = "date";
		}
		
		if(($_POST['factor_b'] == 'dates_exam' && $_POST['date_type']=='db') || ($_POST['factor_b'] == 'dates_db' && $_POST['date_type']=='exam')){
			$params = array();
			$where = "where ".$dat." >= ? and ".$dat." <= ?".$max;						
			$order = $date_type;
			$factor_b = "date";
		}
				
		$inst = " AND src_aet = ? ";
		
		$sql="SELECT $select FROM $from $where $inst group by $factor_b order by $order asc";

		$params[] = $date;
		$params[] = $date_to;		

		if(($_POST['factor_b'] == 'dates_exam' && $_POST['date_type']=='exam') || ($_POST['factor_b'] == 'dates_db' && $_POST['date_type']=='db') || ($_POST['factor_b'] == 'dates_exam' && $_POST['date_type']=='db') || ($_POST['factor_b'] == 'dates_db' && $_POST['date_type']=='exam') ){					
			if(isset($_POST['max_instances'])){
				$params[]= $_POST['max_instances'];
			}
		}
		
		$params[] = $src_aet;
		
		$sth = $dbh->prepare($sql);
		$sth->execute($params);
		$sth->setFetchMode(PDO::FETCH_ASSOC);
		
		$i=0;
		while($plot_row = $sth->fetch()){
			if($plot_row[$factor_b] == null){
				$keys[] = '(null)';
			}
			else{
				$keys[] = $plot_row[$factor_b];
			}
			$values[] = array($plot_row['count']);
			$output[] = array($keys[$i], $plot_row['count']);	
			$i++;
		}
		//$keys = $mod;
		
		if(!($_POST['factor_b'] == 'dates_exam' || $_POST['factor_b'] == 'dates_db' ) && !empty($output) ){
			$output[] = array_multisort($values, SORT_DESC, $keys, SORT_ASC, $output);
		}
		
		if(empty($output)){ // Fill the array output if it is empty (prevents JS error)
			$output[0] = array(null, 0);
		}
		
		$values = json_encode($values);
		$outputString = json_encode($output, JSON_NUMERIC_CHECK);
		
// ----------- Show graphs ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		$total = null;
		$div_date_from='---';
		$div_date_to='---';
		
		if($_POST['date_type'] == 'exam'){
			$dt = 'Ημερομηνίες Εξέτασης';
		}else{
			$dt = 'Ημερομηνίες Καταχώρησης';
		}
		
		if(preg_match("/^([0-9]{2})-[0-9]{2}-([0-9]{4})$/", $_POST['order_date'])){
			$div_date_from = htmlspecialchars($_POST['order_date'], ENT_QUOTES);
		}
		if(preg_match("/^([0-9]{2})-[0-9]{2}-([0-9]{4})$/", $_POST['order_date_to'])){
			$div_date_to = htmlspecialchars($_POST['order_date_to'], ENT_QUOTES);
		}
?>								
			<!-- <div id="chartbar"></div>  -->
			<div class="date_div <?php print($additional_class); ?>" style="text-align: center;">
				<?php print($dt." από ".$div_date_from." έως ".$div_date_to); ?>
			</div>
			
			<hr style="border: 1px solid #6a6b72; margin: 0px auto; margin-bottom: 30px">
			
			<table id="stats_table" class="<?php print($additional_class); ?>">
				<caption>Πίνακας αποτελεσμάτων</caption>							
				<thead>
					<tr style="font-weight:bold;">
						<th id="col1"></th>
						<th id="col2"></th>
					</tr>
				</thead>
				<tbody>
					<?php foreach ($output as $item) { ?>
						<tr>
							<td align="left"><?php echo htmlspecialchars($item[0], ENT_QUOTES); ?></td>
							<td align="center"><?php echo htmlspecialchars($item[1], ENT_QUOTES); ?></td>
						</tr>
						
					<?php $total = $total + $item[1];
						
					 } ?>
					<tfoot>
						<tr>
							<td align="left"><b>Σύνολο</b></td>
							<td align="center"><b><?php echo $total; ?></b></td>
						</tr>
					</tfoot>
				</tbody>
			</table>
		<?php 
		
		if(check_array_parameter('graph', 'bar')) { ?>								
			<br><div id="chartbar"></div>						
		<?php }
		
		if(check_array_parameter('graph', 'pie')){ ?>			
			<br><div id="chartpie"></div>
		<?php }
		
		if(check_array_parameter('graph', 'line')){ ?>	
			<br><div id="chartline"></div>
		<?php }
	}
	else {
		echo "You don't have rights for this page";
	}
?>	

	<script type="text/javascript">
		
		$(document).ready(function(){
		
			if($('#chartbar').length){
				var line1 = <?php echo $outputString; ?>;			
				var plot1 = $.jqplot('chartbar', [line1], {
					title: 'Γράφημα Στηλών',
					//animate: true,
					seriesDefaults: {renderer: $.jqplot.BarRenderer},
					series:[
						{pointLabels:{
						   show: true,
						   labels: <?php echo $values; ?>
						}}
					],
					axesDefaults: {				
						tickRenderer: $.jqplot.CanvasAxisTickRenderer,
						tickOptions: {
							angle: -15,
							fontSize: '8pt'
						}
					},
					axes: {
						xaxis: {
							renderer: $.jqplot.CategoryAxisRenderer
						}
					}
				});
			}
			
			$('#stats_table caption').text(
				$('#stats_table caption').text()+" ("+$('#stats_table tfoot td:last').text()+")"
			);
			
			if($('#chartpie').length){
				var data = <?php echo $outputString; ?>;			 
				var plot2 = $.jqplot ('chartpie', [data], {
					title: 'Γράφημα Πίτας',
					seriesDefaults: {
						// Make this a pie chart.
						renderer: $.jqplot.PieRenderer, 
						rendererOptions: {
							// Put data labels on the pie slices.
							// By default, labels show the percentage of the slice.		
							sliceMargin: 1,
							showDataLabels: true,
							dataLabels: 'percent'  //label
						}
					}, 
					legend: { 
						show:true, 
						location: 's',
						placement: 'outside',
						rendererOptions:{
							fontSize: '8pt',
							numberRows: 2
						},
						
					}
				});
			}
			

			// if($('#chartline').length){
				// var line2 = [14, 32, 41, 44, 40, 47, 53, 67];
				// var plot3 = $.jqplot('chartline', [line2], {
					// title: 'Γράφημα γραμμών', 
					// animate: true,
					// seriesDefaults: { 
						// showMarker:false,
						// pointLabels: { show:true } 
					// }
				// });	
			// }
			
			var col1_name = $('#factor_a option:selected').text();
			document.getElementById("col2").innerHTML=col1_name;
			
			var col2_name = $('#factor_b option:selected').text();
			document.getElementById("col1").innerHTML=col2_name;
		});		
			
	</script>

<?php } ?>

<script type="text/javascript">
	$(function(){
		
		var date_from = "<?php (isset($_GET['order_date'])?print(htmlspecialchars($_GET['order_date'], ENT_QUOTES)):print($today));?>";
		var date_to = "<?php (isset($_GET['order_date_to'])?print(htmlspecialchars($_GET['order_date_to'], ENT_QUOTES)):print($today));?>";
		
		$("#order_date").datepicker({
			changeMonth: true,
			changeYear: true,
			yearRange: "2000:2030",
			dateFormat: "dd-mm-yy",
			setDate: date_from,
			showOn: "button",
			buttonImage: "img/Calendar.png",
			buttonImageOnly: true,
			buttonText: "Ημερολόγιο"
		});

		$("#order_date_to").datepicker({
			changeMonth: true,
			changeYear: true,
			yearRange: "2000:2030",
			dateFormat: "dd-mm-yy",
			setDate: date_to,
			showOn: "button",
			buttonImage: "img/Calendar.png",
			buttonImageOnly: true,
			buttonText: "Ημερολόγιο"
		});
	});
	

	
</script>

</body>
</html>