<?
	require_once ("../common/scripts/connect.inc.php");
	require_once ("../common/scripts/template.inc.php");

//action 	 
//		 1 : supprimer
//		 2 : supprimer tous les msg avant une date
//		 3 : marquer comme non lu
//		 4 : affichage liste sans actions


function retourMess(){
header("Location:../connect/connect.php?file=messagerie");
}
if($_GET['action']==1){
supprimeMessage($_GET['id'],$_GET['login'],$_GET['password']);
//supprimeMessageDate();
}

if($_GET['action']==3) MarquerNonLu($_GET['id'],$_GET['login'],$_GET['password']);
if($_GET['action']==4) affichageListe($_GET['login'],$_GET['password']);
if($_GET['action']==5) newMessage($_GET['login'],$_GET['password'],$_GET['dest'],$_GET['obj']);
if($_GET['action']==6) getContact($_GET['login'],$_GET['password']);
if($_GET['action']==7) ajoutContact($_GET['id']);
if($_GET['action']==8) getMessage($_GET['id'],$_GET['login'],$_GET['password']);
if($_POST['envoi']){ lancerEnvoi($_GET['login'],$_GET['password']);}
if($_GET['ajout']){ 
ajoutContactValide($_GET['id'],$_GET['nouveau'],$_GET['supprimer']);
}

function getMessage($id,$login,$password ){
global $dbconn,$message,$login,$password;
//-----------  Declaration template  ------------------ //
$message = new Template(".");
$message->set_file("getMessage","getMessage.tpl");


//-----------  Declaration des blocks------------------ //
$message->set_block("getMessage","MESSAGE","Message");

//----------- Appels des fonctions --------------------//
afficheUnMessage($id, $login,$password);


//------------- ecriture fichier ---------------------//
$message->parse("output","getMessage");
$message->p("output");

}

// affichage d'un message
function afficheUnMessage($id, $login, $password){
global $dbconn,$message,$login, $password;

$qa=pg_query($dbconn,"select user_id from users where user_login='$login' and user_pass='$password'");
$resa=pg_fetch_array($qa);
$idR=$resa['user_id'];
$messagelu=pg_query($dbconn,"update send set message_read='0' where message_id='$id' and user_receive_id='$idR'");
$q=pg_query($dbconn,"select user_send_id, message_subject,message_text,message_date,message_id from messages where message_id='$id' ");
$q2=pg_query($dbconn,"select user_receive_id from send where message_id='$id' and  user_receive_id='$idR'");

$msg=pg_fetch_array($q);
$msg2=pg_fetch_array($q2);
// recup les logins des users
$ide=$msg['user_send_id'];
$idd=$msg2['user_receive_id'];
$q1=pg_query($dbconn,"select user_login from users where user_id='$ide'");
$q2=pg_query($dbconn,"select user_login,user_pass from users where user_id='$idd'");

$qi_r1=pg_fetch_array($q1);
$qi_r2=pg_fetch_array($q2);

	
	//$message->set_var("newb",$new);
	$message->set_var("id_message",$msg['message_id']);
	$message->set_var("expediteur",$qi_r1[0]);
	$message->set_var("destinataire",$qi_r2[0]);
	$message->set_var("objet",$msg['message_subject']);
	$message->set_var("date_msg",$msg['message_date']);
	$message->set_var("corps",$msg['message_text']);
	$message->set_var("psw",$qi_r2['user_pass']);
	$message->parse("Message","MESSAGE",true);
	

	
} 


function getContact($id)
{
	global $dbconn,$newMessage;
	$aff= pg_query($dbconn,"select u.user_login,u.user_id from users u join contact on contact.user_id_contact=u.user_id where contact.user_id='$id'");	
	//-----------  Declaration des blocks------------------ //

	while($contact=pg_fetch_array($aff))
	{
		$newMessage->set_var("contact",$contact['user_login']);
		$newMessage->set_var("idContact",$contact['user_id']);
		
		$newMessage->parse("listeContact","LISTE_CONTACT",true);
	}
}

function supprimeMessage($id,$login,$password){
	global $dbconn;
	$qa=pg_query($dbconn,"select user_id from users where user_login='$login' and user_pass='$password'");
	$resa=pg_fetch_array($qa);
	$idR=$resa['user_id'];
	$req= pg_query($dbconn, "select count(message_id) as nb from send where message_id ='$id'");
	$res=pg_fetch_array($req);
	$del2= pg_query($dbconn,"delete from send where message_id='$id' and user_receive_id='$idR'");	
	if ($res['nb']==1)  
	$del= pg_query($dbconn,"delete from messages where message_id='$id'");	

	
	affichageListe($login,$password);
}

function supprimeMessageDate()
{
	global $dbconn;
	$date = date("Y-m-d H:i:s",strtotime("-1 month"));
	$del= pg_query($dbconn,"delete from messages where message_date < '$date'");	
}

function MarquerNonLu($id,$login,$password)
{
	global $dbconn;
	$qa=pg_query($dbconn,"select user_id from users where user_login='$login' and user_pass='$password'");
	$resa=pg_fetch_array($qa);
	$idR=$resa['user_id'];
	$del= pg_query($dbconn,"update send set message_read='true' where message_id='$id' and user_receive_id='$idR'");
	affichageListe($login,$password);	
}

function affichageListe($login,$password) {
global $dbconn,$listeMessage,$login,$password;
//-----------  Declaration template  ------------------ //
$listeMessage = new Template(".");
$listeMessage->set_file("listeMessage","../messagerie/listeMessage.tpl");
$listeMessage->set_var("log",$login);
$listeMessage->set_var("login",$login);
$listeMessage->set_var("password",$password);
//-----------  Declaration des blocks------------------ //
$listeMessage->set_block("listeMessage","LISTE_MESSAGES","listeMessages");
//----------- Appels des fonctions --------------------//
affichageMessages($login,$password);
//------------- ecriture fichier ---------------------//
$listeMessage->parse("output","listeMessage");
$listeMessage->p("output");
}


function affichageMessages($login,$password){
global $dbconn,$listeMessage;

$qa=pg_query($dbconn,"select user_id from users where user_login='$login' and user_pass='$password'");
$res=pg_fetch_array($qa);
$id=$res['user_id'];
$q=null;
$q=pg_query($dbconn,"select message_id, message_read from send where user_receive_id='$id'order by message_id DESC ");
$cpt =0;
while($ligne=pg_fetch_array($q)) {
	$id2=$ligne['message_id'];
	$q2=pg_query($dbconn,"select message_read,user_send_id,message_subject,message_text,message_date from messages where message_id='$id2'");
	
	$msg=pg_fetch_array($q2);
	$idd=$msg['user_send_id'];
	$q3=pg_query($dbconn,"select user_login from users where user_id='$idd'");
	$exp=pg_fetch_array($q3);
	$cpt++;
		$obj =$msg['message_subject'];
		if($ligne['message_read']=="f") $new="<img src='../messagerie/images/lu.gif'>";
		if($ligne['message_read']=="t") $new="<img src='../messagerie/images/new.gif'>";
		$listeMessage->set_var("newb",$new);
		$listeMessage->set_var("de",$exp['user_login']);
		if($obj=="") $obj="Pas d'objet";
		$listeMessage->set_var("objet",$obj);
		
		$listeMessage->set_var("dat",datefr($msg['message_date']));
		$listeMessage->set_var("id_message",$id2);
		if($cpt%2==0)$listeMessage->set_var("atchoum","ligne1");
		else $listeMessage->set_var("atchoum","ligne2");
		
		$listeMessage->parse("listeMessages","LISTE_MESSAGES",true);
	}	
}

function datefr($date)
  {
   
  list($date2, $time) = explode(" ", $date);
  
  list($year, $month, $day) = explode("-", $date2);

  $mois = array('janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre');
  $today = date("Y-m-d");
  if ($date2 < $today) $dateFra = "$day ".$mois[$month -1]." $year";
  else $dateFra = $time;
  return $dateFra;
  
  }

/////////////// NEW MESSAGE ///////////////////////////////////////

function newMessage($login,$password,$dest,$obj) {
global $newMessage,$dbconn;

$qa=pg_query($dbconn,"select user_id from users where user_login='$login' and user_pass='$password'");
$res=pg_fetch_array($qa);
$id=$res['user_id'];
$new=1;
//-----------  Declaration template  ------------------ //
$newMessage = new Template(".");
$newMessage->set_file("newMessage","../messagerie/newMessage.tpl");
$newMessage->set_block("newMessage","LISTE_CONTACT","listeContact");
$newMessage->set_var("id_exp",$id);
$newMessage->set_var("destinataire",$dest);
if ($dest!="") $obj="Re : ".$obj;
$newMessage->set_var("objet",$obj);
if($new==1) {	
getContact($id);
//------------- ecriture fichier ---------------------//
$newMessage->parse("output","newMessage");

$newMessage->p("output");
}

}


//---------------- FONCTIONS ------------------------//

//---------------------------------------------------//
// lance l'envoi si l'utilisateur existe... ---------//
//---------------------------------------------------//
function lancerEnvoi($login,$password) {
global $_POST,$dbconn;
$logins=$_POST[destinataire];
$dests =explode(", ",$logins);
$dests_envoi=$dests;
$i=0;
		$idMessage = ajoutMessage();
// verifie si les utilisateurs existent tous
	foreach($dests as $dest){
  		$validation_user=-1;
  		$validation_user=verifMessage($dest);
		$tab[$i]=$validation_user;
		$i++;
 		if($validation_user==-1){
	  	$dests=-1;
  	  	ErreurEnvoi($dest,$dests_envoi);
  		}
		else {
		ajoutMessageAutilisateur($validation_user,$idMessage);

		} 
	}
retourMess();
}

function ajoutMessageAutilisateur($tab,$id) {
global $dbconn;
$mess = pg_query($dbconn, "insert into send (message_id,user_receive_id,message_read) values ('$id', '$tab','1')");

}

//---------------------------------------------------//
// -------- Si un des destinataires existe pas ------//
//---------------------------------------------------//
function ErreurEnvoi($dest) { 
global $_POST,$dbconn;
$dat=date("Y/m/d H:i:s");
$exp=$_POST[id_exp];
$sujet="Message non delivre";

$corps="Le message a ".$dest." n a pas pu etre envoye l utilisateur n existe pas";

$q=pg_query($dbconn,"insert into messages(message_read,user_send_id,message_subject,message_text,message_date) VALUES ('1','$exp','$sujet','$corps','$dat')");
$recupId=pg_query($dbconn, "select max(message_id) as idd from messages where user_send_id='$exp'");
$ligne=pg_fetch_row($recupId);
$msgId=$ligne[0];
$q=pg_query($dbconn,"insert into send(message_id,user_receive_id,message_read) VALUES ('$msgId','$exp','1')");

}

//---------------------------------------------------//
//------   Vérification d'un utilisateur    ---------//
//---------------------------------------------------//
function verifMessage($log){
global $_POST,$dbconn;
$val=-1;
// verifier que le nom d'utilisateur existe dans la base
$q=pg_query($dbconn,"select user_login,user_id from users where user_login='$log'" );
$result=pg_fetch_array($q);
if($result['user_id']!="") $val=$result['user_id'];
// retourne 1 si ok sinon retourne false

return $val;
}

function ajoutMessage(){
global $_POST,$dbconn;
// recupere id du destinataire

$dat=date("Y/m/d H:i:s");
$exp=$_POST['id_exp'];
$sujet=$_POST['objet'];
$corps=$_POST['message'];

	$q=pg_query($dbconn,"insert into messages (message_read,user_send_id,message_subject,message_text,message_date) VALUES ('1','$exp','$sujet','$corps','$dat')");
	$recupId=pg_query($dbconn, "select max(message_id) as idd from messages where user_send_id='$exp'");
	$ligne=pg_fetch_row($recupId);
	$msgId=$ligne[0];
	// on retourne l'id du message qui vient d'etre eneregistre
	return $msgId; 
	

}

function ajoutContact($id){
global $_POST,$_GET,$dbconn;
//-----------  Declaration template  ------------------ //
$contact = new Template(".");
$contact->set_file("contact","../messagerie/newContact.tpl");
$contact->set_var("id_exp",$id);
//$contact->set_var("destinataire",$dest);
//------------- ecriture fichier ---------------------//
$contact->parse("output","contact");

$contact->p("output");

}

function ajoutContactValide($id,$new,$sup){
global $_GET,$dbconn, $log,$pass;
	if($new!="") {
		$recupId=pg_query($dbconn, "select user_id from users where user_login='$new'");
		$ligne=pg_fetch_row($recupId);
		if($ligne) {
			$newId=$ligne[0];
			$q=pg_query($dbconn,"insert into contact (user_id,user_id_contact) VALUES ('$id','$newId')");
		}
	}
	if($sup!="") {
		$recupId=pg_query($dbconn, "select user_id from users where user_login='$sup'");
		$ligne=pg_fetch_row($recupId);
		if($ligne) {
			$newId=$ligne[0];		
		$q=pg_query($dbconn,"delete from contact where user_id_contact='$newId' and user_id='$id'");
		}
	}

retourMess();

}

?>
