<?php
	session_start();
	
	include("connexion_db.php");
	
	if(isset($_SESSION['etat']) && $_SESSION['etat'] == 'on')
	{	
		date_default_timezone_set('Europe/Paris');
		if(isset($_GET['valeur_champ']) && $_GET['valeur_champ'] != '' &&
		isset($_GET['id_champ']) && $_GET['id_champ'] != '' &&
		isset($_GET['date']) && $_GET['date'] != '')
		{
			$date = date("Y-m-d");
			if(strcmp($_GET['date'], $date) == -1) {
				$table='donnees_grilles';
			}else{
				$date = $_GET['date'];$table='objectifs';
			}
			
				$resultat['table'] = $table;
				$resultat['datemoi'] = $_GET['date'];
				$resultat['dateserv'] = date('Y-m-d');
				$resultat['val'] = $_GET['valeur_champ'];
				$resultat['id'] = $_GET['id_champ'];
				$resultat['etat'] = 'debut';
				$resultat['va'] = (strcmp($_GET['date'], date('Y-m-d')));
			// On regarde si la base n'est pas déjà à jour via sondage ou thermo
			$sql = "SELECT * FROM " . $table . " WHERE id_champ = '" . $_GET['id_champ'] . "' AND id_grille = '" . $_SESSION['id_grille'] . "' AND id_docteur = '" . $_SESSION['id_docteur'] . "' AND id_patient = '" . $_SESSION['id_patient'] . "' AND date = '" . $date ."'";
			$req = cleanPDOQuery($sql);	
			$res = $req->fetch();
			
			// Si déjà à jour
			if($res['valeur'] == $_GET['valeur_champ']) {
				$resultat['etat'] = 'fini';
			}
			
			else
			{	
				// On cherche la date de la dernière MàJ
				$sql = "SELECT * FROM " . $table . " WHERE id_champ = '" . $_GET['id_champ'] . "' 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'];
				$resultat['etat'] = '?';
				if($lastUpdateDate == $date) {
					
					// On met à jour dans la base de données les informations sur le champ selectionné
					$sql = "UPDATE " . $table . " SET valeur = '" . $_GET['valeur_champ'] . "' WHERE id_champ = '" . $_GET['id_champ'] . "' AND id_grille = '" . $_SESSION['id_grille'] . "' AND id_docteur = '" . $_SESSION['id_docteur'] . "' AND id_patient = '" . $_SESSION['id_patient'] . "' AND date = '" . $date ."'";
					
				
					$req = cleanPDOQuery($sql);	
					$resultat['etat'] = 'update';
				}
				
				else if($lastUpdateDate < $date) {
				
					// On met à jour dans la base de données les informations sur le champ selectionné
					$sql = "INSERT INTO " . $table . " VALUES('', '" . $_SESSION['id_grille'] . "', '" . $_GET['id_champ'] . "', '" . $_GET['valeur_champ'] . "', '" . $_SESSION['id_patient'] . "', '" . $_SESSION['id_docteur'] . "', '" . $_SESSION['id_etablissement'] . "', '" . $date . "')";
					$req = cleanPDOQuery($sql);	
					$resultat['etat'] = 'insert';
					
				}
				
				
			}
			
			header('Content-Type: application/json');
			echo json_encode($resultat);
		}
	}

	
?>