<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$titre = 'Amis';

$a = gpc('a');
$nom = gpc('nom', 'post');
if (!empty($a)) {
	$fav = explode(';', $queryUser['amis']);
	$cntfav = count($fav);

	$d = gpc('d');
	if (!empty($d) && $a == md5(date('GA').'@'.$d)) {
		for($i = 0; $i < $cntfav; $i++){
			if ($fav[$i] == $d) unset($fav[$i]);
		}
		$queryUser['amis'] = implode(';', $fav);
		$bdd->connexion();
		$bdd->query("UPDATE $table_user SET amis = '".$queryUser['amis']."' WHERE id = $id_user;");
		$bdd->deconnexion();
	}
	header('Location: ?p=amis');
	exit;
}
elseif (!empty($nom)) {
	$bdd->connexion();
	$plan = $bdd->unique_query("SELECT id FROM $table_user WHERE pseudo = '$nom';");
	if ($plan) {
		if (in_array($plan['id'], explode(';', $queryUser['amis']))) {
			$bdd->deconnexion();
			erreur('Ce joueur est déjà dans votre liste d\'amis.', "red", "?p=amis", 2000);
		}
		$queryUser['amis'] .= ";".$plan['id'];
		$bdd->query("UPDATE $table_user SET amis = '".$queryUser['amis']."' WHERE id = $id_user;");
	}
	else {
		$bdd->deconnexion();
		erreur('Joueur introuvable.', "red", "?p=amis", 2000);
	}
	$bdd->deconnexion();

	header('Location: ?p=amis');
	exit;
}
else {
	$page = 'amis';

	$fav = explode(';', $queryUser['amis']);
	$cntfav = count($fav);
	$destins = array();
	$bdd->connexion();
	for($i = 0; $i < $cntfav; $i++){
		$res = $bdd->unique_query("SELECT pseudo FROM $table_user WHERE id = ".$fav[$i].";");
		if ($res != false) {
			$destins[] = array($fav[$i], $res['pseudo'], md5(date('GA').'@'.$fav[$i]));
		}
	}
	$bdd->deconnexion();
	$template->assign('destins', $destins);
}
?>