<?php
	include '../autoload.php';

	error_log ( "SurveyCompletingValidate...");

	$survey_id = -1;

	foreach ( $_POST as $id => $value )
	{
		if ( str_contains ( $id, "resp_" ) )
		{
			error_log ( "id : " .$id );
			error_log ( "value : " .$value );

			$tmp = explode ( "_", $id );
			$survey_id 	= $tmp [1];
			// break;
		}
	}

	
	$conn = get_dbconnection();
	
	$sql = "insert into survey_resp (survey_id, rdate) values (".$survey_id.", NOW()) returning id;";

	error_log ( "SurveyCompletingValidate : " .$sql );

	$query = pg_query($conn,$sql);
	$resp_id = -1;
	if ( $row = pg_fetch_row ($query) )
	{
		$resp_id 			= $row [0];
		error_log ( " id : " .$id );
	}

	if ( $resp_id != -1 )
	{
		foreach ( $_POST as $id => $value )
		{
			error_log ( "id : " .$id );
			error_log ( "value : " .$value );

			if ( str_contains ( $id, "resp_" ) )
			{
				$tmp = explode ( "_", $id );
			
				$survey_id 	= $tmp [1];
				$field_id 	= $tmp [2];
				$type 		= $tmp [3];

				error_log ( " survey_id : " .$survey_id );
				error_log ( " field_id : " .$field_id );
				error_log ( " type : " .$type );
				error_log ( " value : " .$value );

				if ( $type==7 || $type==8 )
					$sql = "insert into survey_resp_field (resp_id, field_id, value, value_text ) values (".$resp_id.", ".$field_id.", -1, '".$value."') returning id;";
				else
					$sql = "insert into survey_resp_field (resp_id, field_id, value ) values (".$resp_id.", ".$field_id.", ".$value.") returning id;";

				error_log ( "SurveyCompletingValidate : " .$sql );

				$query = pg_query($conn,$sql);
				if ( $row = pg_fetch_row ($query) )
				{
				}
			}
		}
	}
	

	echo '<div>Vos réponses ont été enregistées.</div><br>';
	echo '<div><b>Merci pour votre participation.</b></div>';
?>