<?php

  require_once '../../autoload.php';

  $conn = get_dbconnection();

  $arr = array (
			"result"		=> 'Error',
			"Results"	=> array ()
	);

	if ( $conn )
	{
		$survey_id = -1;

    if(isset($_POST['survey_id']) && $_POST['survey_id'] != '')
		{
			$survey_id = $_POST['survey_id'];
		}

		// $sql = "select count(id) from survey_resp where survey_id = ".$survey_id;
		$sql = "select count(survey_resp.id),to_char(begindate,'DD/MM/YYYY') as begindate,to_char(enddate,'DD/MM/YYYY') as enddate from survey_resp, survey where survey_resp.survey_id=survey.id and  survey_id=".$survey_id." group by begindate,enddate";

		if ( $query = pg_query($conn,$sql) )
		{
			while ( $row = pg_fetch_row($query) )
			{
				$arr["result"] 		= "OK";
				$arr["BeginDate"] = $row[1];
				$arr["EndDate"] 	= $row[2];
				$arr["NbResult"] 	= $row[0];
			}
		}


		// $sql = "select field_id, type, min(value),max(value),avg(value),stddev(value) from survey_resp_field,survey_resp,survey_field where survey_resp.id=survey_resp_field.resp_id and survey_resp_field.field_id=survey_field.id and survey_resp.survey_id=".$survey_id." and type in (2,3,4) group by survey_resp_field.field_id,type,position order by position;";

		$sql ="select v_survey.field_id, field_type, position, case field_type when 1 THEN NULL else min(value) end, case field_type when 1 THEN NULL else max(value) end, case field_type when 1 THEN NULL else avg(value) end from survey_resp_field right join v_survey on survey_resp_field.field_id=v_survey.field_id where v_survey.survey_id=".$survey_id." group by v_survey.field_id,position,field_type order by position,field_type,v_survey.field_id;";

		if ( $query = pg_query($conn,$sql) )
		{
			while ( $row = pg_fetch_row($query) )
			{
				// $arr1 = array ( "name" => $row[0], "mod_id" => $row[1] );

				// $arr["result"] = "OK";
				// $arr["NbResult"] = $row[0];

				// array_push ( $arr["users"], $arr1 );

				$res = array ( 	"field_id" => $row[0],
												"type" => $row[1],
												"position" => $row[2],
												"min" => $row[3],
												"max" => $row[4],
												"avg" => $row[5],
												"stddev" => $row[6]);

				// $arr["Results"][$row[0]] = $res;
				array_push ( $arr["Results"], $res );
			}
		}
	}

	header('Content-type: application/json');
	$result = json_encode ( $arr );
	
	echo $result;

?>
