<?php
 
$dsn = 'sqlite:/home/artefacts/Documents/coachenergie/coachenergie.sqlite';
 
$dbh = init_db( $dsn );
//fill_random_data( $dbh );
//test_datas( $dbh );
//test_inscription ($dbh, 'mail@test3', 'toto', 'toto', 'password');
test_conect ($dbh, 'mail@test3' , 'pass');
 
function init_db( $dsn )
{
	//connection DataBase
	try {
		$dbh = new PDO($dsn, '', '');
		$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		echo 'Connexion OK', "\n";
		return $dbh ;
	} catch (PDOException $e) {
		echo 'Connexion échouée : ' . $e->getMessage(), "\n";
	}
	return null ;
}
 
function fill_random_data( $dbh )
{
	//remplir la DataBase de valeurs
	for ($i = 0; $i < 10; $i++) 
	{
		$val = rand(-5,30);
		$day = date("Y-m-d H:i:s"); //"2015-12-09 17:16:18"
		$requete = 'INSERT INTO datas (sensors_id,date,value) VALUES (1,"' . $day . '",' . $val . ')';
 
		$res = $dbh->exec($requete);
		if ($res === false)
			die('erreur requete');
	}
}
 
function test_datas( $dbh )
{
	// test requete select	
	$requete = 'SELECT value, date FROM datas';
	foreach ($dbh->query($requete) as $row) 
	{
		echo $row['value'] . "\t";
		echo $row['date'] . "\n";
	}
}
 
//test d'inscription
function test_inscription ($dbh, $email, $Lname, $Fname, $password)
{
	$requete = 'SELECT COUNT (email) FROM users WHERE email ="'. $email .'"';
	echo $requete ."\n"; 
	$count = $dbh->query($requete);
 
	if ($count->fetchColumn() > 0)
	{
		echo "mail deja prit" ."\n"; 
	}
	else
	{
		$requete = 'INSERT INTO users (email,lastname,firstname,password) VALUES ("' . $email . '","' . $Lname . '","' . $Fname . '","' . $password . '")';
 
		$res = $dbh->exec($requete);
		if ($res === false)
			die('erreur requete');
	}
}
 
//test de connection
function test_conect ($dbh, $email , $password)
{
	$requete = 'SELECT COUNT (email) FROM users WHERE email ="'. $email .'" AND password ="'. $password .'"';
	echo $requete ."\n"; 
	$count = $dbh->query($requete);
 
	if ($count->fetchColumn() > 0)
		echo "co OK" ."\n"; 
	else
		echo "erreur de co" ."\n"; 
}