<?php
	session_start();
	
	include("connexion_db.php");
	
	if(isset($_SESSION['etat']) && $_SESSION['etat'] == 'on')
	{	
		if(isset($_GET['reponse']) && $_GET['reponse'] != '' && isset($_GET['id_question']) && $_GET['id_question'] != '')
		{	
			// On regarde si la base n'est pas déjà à jour via sondage ou thermo
			$sql = "SELECT * FROM questions WHERE id_question = '" . $_GET['id_question'] . "' AND id_grille = '" . $_SESSION['id_grille'] . "' AND id_docteur = '" . $_SESSION['id_docteur'] . "' AND id_patient = '" . $_SESSION['id_patient'] . "' AND date = DATE(NOW())";
			$req = cleanPDOQuery($sql);	
			$res = $req->fetch();
			
			if($res['reponse'] == $_GET['reponse']) {
				$resultat['etat'] = 'fini';
			}
			
			else
			{	
				// On cherche la date de la dernière MàJ
				$sql = "SELECT * FROM questions WHERE id_question = '" . $_GET['id_question'] . "' AND id_grille = '" . $_SESSION['id_grille'] . "' AND id_docteur = '" . $_SESSION['id_docteur'] . "' AND id_patient = '" . $_SESSION['id_patient'] . "' ORDER BY date DESC";
				$req = cleanPDOQuery($sql);	
				$res = $req->fetch();
				$lastUpdateDate = $res['date'];
				
				if($lastUpdateDate == date("Y-m-d")) {
				
					// On met à jour dans la base de données les informations sur le champ selectionné
					$sql = "UPDATE questions SET reponse = '" . $_GET['reponse'] . "' WHERE id_question = '" . $_GET['id_question'] . "' AND id_grille = '" . $_SESSION['id_grille'] . "' AND id_docteur = '" . $_SESSION['id_docteur'] . "' AND id_patient = '" . $_SESSION['id_patient'] . "' AND date = DATE(NOW())";
					$req = cleanPDOQuery($sql);	
					$resultat['etat'] = 'update';
				}
				
				else if($lastUpdateDate < date("Y-m-d")) {
				
					// On met à jour dans la base de données les informations sur le champ selectionné
					$sql = "INSERT INTO questions VALUES('', '" . $_SESSION['id_grille'] . "', '" . $_GET['id_question'] . "', '" . $_GET['reponse'] . "', '" . $_SESSION['id_patient'] . "', '" . $_SESSION['id_docteur'] . "', '" . $_SESSION['id_etablissement'] . "', NOW())";
					$req = cleanPDOQuery($sql);	
					$resultat['etat'] = 'insert';
				}
				
				
			}
			
			header('Content-Type: application/json');
			echo json_encode($resultat);
		}
	}

	
?>