<?php
	
	include("connexion_db.php");
	
	$reponsepatient = '';
	
	$idPatient=$_POST['idPatient'];
	$idGrille=$_POST['idGrille'];
	$idQuestion=$_POST['idQuestion'];
	$champ=$_POST['champ'];
	$reponse=$_POST['reponse'];
	$etat=$_POST['etat'];
	$idDocteur=$_POST['idDocteur'];
	
	$reponsepatient[$idPatient][$idGrille][$idQuestion][$champ][$reponse] = array(
		'checked' => $etat);
		
	// On détermine si l'enregistrement est un insert ou un update
	$sql1 = "SELECT * FROM `reponse_patient`  WHERE `id_patient` = '" . $idPatient . "' AND `id_grille` = '" . $idGrille . "' AND `nom_champ` = '" . strtolower($champ) . "' AND `id_question` = '" . $idQuestion . "' AND `reponse` = '" . strtolower($reponse) . "'";
	$req1 = cleanPDOQuery($sql1);
	$nbRes1 = $req1->rowCount();

			
				
	// Si aucun enregistrement n'existe
	if ($nbRes1 == 0) 
	{
					
		// On insère les nouvelles valeurs
		$sql2 = "INSERT INTO reponse_patient ( id_docteur, id_patient, id_grille, nom_champ, id_question, reponse, checked) VALUES('" . $idDocteur . "', '". $idPatient ."', '" . $idGrille . "', '" . strtolower($champ) . "', '" . $idQuestion . "', '" . strtolower($reponse) . "', '" . $etat . "')";
		$req2 = cleanPDOQuery($sql2);
		
	}
	else 
	{

		// On met à jour l'enregistrement
		$sql2 = "UPDATE reponse_patient SET checked = '" . $etat . "' WHERE `id_patient` = '" . $idPatient . "' AND `id_grille` = '" . $idGrille . "' AND `nom_champ` = '" . strtolower($champ) . "' AND `id_question` = '" . $idQuestion . "' AND `reponse` = '" . strtolower($reponse) . "'";
		$req2 = cleanPDOQuery($sql2);

	}
		
	$_POST['reponsepatient']=$reponsepatient;
	
	header('Content-Type: application/json');
	echo json_encode($reponsepatient);
?>