<?php 
class UsersController extends Controller{
	/**
	* Initialisation
	**/
	function login(){
		
		$_SESSION['s_groupe']='users';
		$_SESSION['s_page']= 'admin';
		$_SESSION['s_vue']='login';	
		
		// unset($_SESSION['User']);
		// $_SESSION['b_connecte'] = false;
		
		$this->loadModel('Users');

		if($this->request->data){
			
			// règles de validation
			$this->Users->validate = array(
				'login' => array(
					'R0'=>array(
						'rule' => 'notEmpty',
						'message' => decode_lng_text('ADMIN_LOGIN_ID_R0')
					)
				),
				'passwd' => array(
					'R0'=>array(
						'rule' => 'notEmpty',
						'message' => decode_lng_text('ADMIN_LOGIN_PSWD_R0')
					)
				)

			);
// var_dump($_POST);
// var_dump($this->request->data);
			if($this->Users->validates($this->request->data)){	
				$data = $this->request->data;
				$data->passwd = md5($data->passwd); 
				$table = 'oxg_users';
				$this->Users->table = $table;	

				$condition = array('login' => $data->login,'passwd' => $data->passwd);
				$row_user=$this->Users->findFirst(array(
					'fields'     => '*',
					'conditions' => $condition
				));
	// $_SESSION['ind_affiche']=1;			
//var_dump($row_user);
					
				if(!empty($row_user)){
					$_SESSION['b_connecte'] = true;
					$_SESSION['b_Sosa'] = true;
					$_SESSION['s_privilege'] = $row_user->privilege; 
					$_SESSION['s_user'] = $row_user->login;
					$_SESSION['s_nom'] = $row_user->nom;
					$_SESSION['s_prenom'] = $row_user->prenom; 
					$_SESSION['s_skin'] = $row_user->skin;
					$_SESSION['s_colorH'] = substr($row_user->colorH,1,6);
					$_SESSION['s_colorF'] =  substr($row_user->colorF,1,6);
					$_SESSION['s_texte_connexion'] = decode_lng_text('PRIVATE_HELLO').' '.$row_user->prenom.' '.$row_user->nom.' <i>('.$row_user->privilege.')</i>';
					
					
					$_SESSION['s_ReqContemporain'] = ' and contemporary = 1';
					$this->request->data->passwd = ''; 
					$_SESSION['s_erreur'] = '';
					
					$this->redirect('accueil/index');
				}
				else {
					$this->Session->setMessage(decode_lng_text('ADMIN_LOGIN_NOT_CNX'),'error'); 
					$_SESSION['erreur'] = 'login';
					$this->request->data->passwd = '';  
					$this->render('login');
				}
			}
		}
/*
* pour comprendre les libellés multi-langues
*/			
// "ADMIN_LOGIN" => "Veuillez saisir vos identifiants",
// "ADMIN_LOGIN_ID_R0" => "Indiquez un identifiant valide",
// "ADMIN_LOGIN__PSWD_R0" => "Indiquez un mot de passe valide",
// "ADMIN_LOGIN_NOT_CNX" => "Identifiant et/ou mot de passe non reconnus",
		
	} // fin de fonction login
	

	/**
	* Logout deconnexion utilisateur
	**/
	function logout(){
		$_SESSION['s_page']= 'accueil';
		$_SESSION['s_vue']='logout';	
		unset($_SESSION['User']);
		unset($_SESSION['s_colorH']);
		unset($_SESSION['s_colorF']);
		$_SESSION['s_skin']= 'BROWN_TOP_LEFT';
		
		$_SESSION['b_connecte'] = false;
		//$_SESSION['b_Sosa'] = false;
		$_SESSION['privilege'] = 'user';
		
		//$this->Session->setMessage('Vous êtes maintenant déconnecté'); 
		$this->redirect('accueil/index'); 
	} // fin de fonction logout

	/**
	*  gestion des utilisateurs autorisés
	**/	
	
	/*
	* menu d'administration
	*/
	function admin_index() {
		
		$_SESSION['s_groupe']='users';
		$_SESSION['s_page']= 'admin';
		$_SESSION['s_vue']='admin_index';
		$users=array();	
		$_SESSION['users']=array();
	

		$action = isset($this->request->data->action)?$this->request->data->action : '';
		$user = isset($this->request->data->user)?$this->request->data->user : '';

		if (($user!="" and $action!="" )) {
				
			$this->loadModel('Users');
			$table = 'oxg_users';
			$this->Users->table = $table;	
					
				
			if ($action=="edit")    { self::admin_edit(); }
			if ($action=="passwd")  { self::admin_passwd(); }
			if ($action=="delete")  { self::admin_delete(); }
		}
		else if ($action=="new") 	{ self::admin_new(); }
		
		else {
			$message = "";
			if ($user!="" and $action=="" ) 	{ $this->Session->setMessage(decode_lng_text('ADMIN_INDEX_1'),'error'); }
			if ($user=="" and $action!="new" )  { $this->Session->setMessage(decode_lng_text('ADMIN_INDEX_2'),'error'); }	
			if ($user=="" and $action=="" )     { $this->Session->setMessage(decode_lng_text('ADMIN_INDEX_0')); }
				
		}
		
		$action='';
		$user='';

		self::liste_users();
		
		$this->render('admin_index');
		
/*
* pour comprendre les libellés multi-langues
*/		
// "ADMIN_INDEX_0" =>"Sélectionnez un utilisateur et une action",
// "ADMIN_INDEX_1"=>"Erreur: il faut aussi sélectionner une action",
// "ADMIN_INDEX_2"=>"Erreur: il faut aussi sélectionner un utilisateur",
		
	} // fin de fonction admin_index
	
	function liste_users() {
		$users=array();	
		$_SESSION['users']=array();

		$this->loadModel('Users');

		$table = 'oxg_users';
		$this->Users->table = $table;	
					
		$result_user=$this->Users->find(array(
			'fields'     => '*'
		));
		
		foreach($result_user as $k=>$row) {
			$users[]= array('num'=>$k,'login'=>$row->login,'passwd'=>$row->passwd,'nom'=>	$row->nom, 'prenom'=> $row->prenom, 'email'=>$row->email,'privilege'=>$row->privilege);
		}
		$_SESSION['t_users']=$users;
		
	} // fin de fonction liste_users

	function admin_new() {
//var_dump($this->request->data);	
//$_SESSION['ind_affiche']=1;
	$_SESSION['s_page']= 'admin';
	$_SESSION['s_vue']='admin_new';	
	
	// verif passage initial
	 if (($this->request->data) && (empty($this->request->data->login))) {
		$this->render('admin_new');
	 }
	$this->loadModel('Users');
	$table = 'oxg_users';
	$this->Users->table = $table;			
	$verif = $this->Users->findFirst(array(
			'conditions' => array('login' => $this->request->data->login)
		));
		if(!empty($verif)){
			$this->Session->setMessage(decode_lng_text('ADMIN_NEW_USER_EXISTING'),'error'); 
			$this->render('admin_new');
		}
		

		// installation des règles de validation
		$this->Users->validate = array(
			'login' => array(
				'R0'=>array(
					'rule' => 'notEmpty',
					'message' => decode_lng_text('ADMIN_NEW_LOGIN_R0')
				),
				'R1' => array(
					'rule' =>  '[\.a-zA-Z0-9]+',
					'message' => decode_lng_text('ADMIN_NEW_LOGIN_R1')
				),
				'R2' => array(
					'rule' =>  'min_4',
					'message' => decode_lng_text('ADMIN_EDIT_LOGIN_R2')
				)
			),
			'passwd' => array(
				'R0'=>array(
					'rule' => 'notEmpty',
					'message' => decode_lng_text('ADMIN_NEW_PSWD_R0')
				)
			),
			'nom' => array(
				'R0'=>array(
					'rule' => 'notEmpty',
					'message' => decode_lng_text('ADMIN_NEW_NOM_R0')
				)
			),
			'prenom' => array(
				'R0'=>array(
					'rule' => 'notEmpty',
					'message' => decode_lng_text('ADMIN_NEW_PRENOM_R0')
				)
			),
			'email' => array(
				'R0'=>array(
					'rule' => '[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})',
					'message' => decode_lng_text('ADMIN_NEW_EMAIL_R0')
				)
			)
		);


//$_SESSION['ind_affiche']=1;

		if($this->Users->validates($this->request->data)){
			$data = $this->request->data;
			
			 // on supprime les infos non utiles à la màj 
			unset($data->user); 
			unset($data->submit);
//echo 'data <br/>' ; var_dump($data);
			$data->nom = ucfirst(strtolower($this->request->data->nom));
			$data->prenom = ucfirst(strtolower($this->request->data->prenom));
	echo $this->request->data->password."<br/>";
			$data->passwd = md5($this->request->data->passwd); 
	echo $data->passwd;
			$result_insert = $this->Users->insert($data);
			if ($result_insert>0) {  
				$this->Session->setMessage(decode_lng_text('ADMIN_NEW_SUCCESS'));
				self::liste_users();
				$this->render('admin_index');
			}
			else {
				$this->Session->setMessage(decode_lng_text('ADMIN_NEW_ECHEC'),'error'); 
			}
			
			return; 
		}
		else{
			$this->Session->setMessage(decode_lng_text('ADMIN_NEW_CORRECTION1'),'error'); 
		}
		
	//

	$this->render('admin_new');
/*
* pour comprendre les libellés multi-langues
*/		
// "ADMIN_NEW_SUCCESS"=>"Le compte a été créé avec succès",
// "ADMIN_NEW_ECHEC"=>"Echec lors de la tentative de création du compte",
// "ADMIN_NEW_CORRECTION1"=>"Merci de corriger vos informations",	
// "ADMIN_NEW_CORRECTION2""Données absentes ou incomplètes. Création impossible"
// "ADMIN_NEW_LIB1" =>"Identifiant absent",
// "ADMIN_NEW_LIB2" =>"Nom absent",
// "ADMIN_NEW_LIB3" =>"Prénom absent",
// "ADMIN_NEW_LIB4" =>"L'adresse mail n'est pas valide",	
// "ADMIN_NEW_LIB5" =>"Mot de passe absent",	

	}
	
	function admin_edit() {
		
		//var_dump($this->request->data);	
		$_SESSION['s_page']= 'admin';
		$_SESSION['s_vue']='admin_edit';
		
		$user=$this->request->data->user;
		
		$this->loadModel('Users');
		$table = 'oxg_users';
		$this->Users->table = $table;	
					
		$result_user=$this->Users->find(array(
			'fields'     => '*',
			'conditions' => "login='".$user."'"
		));
		
		foreach($result_user as $row) {
			$_SESSION['s_utilisateur']['login'] = $row->login;
			$_SESSION['s_utilisateur']['passwd'] = $row->passwd;
			$_SESSION['s_utilisateur']['nom'] =ucfirst(strtolower($row->nom));
			$_SESSION['s_utilisateur']['prenom'] = ucfirst(strtolower($row->prenom));
			$_SESSION['s_utilisateur']['email'] = $row->email;
			$_SESSION['s_utilisateur']['privilege'] = $row->privilege;
		 }
		 // verif passage initial
		 if (($this->request->data) && (empty($this->request->data->login))) {
			$this->render('admin_edit');
		 }
		 
		// installation des règles de validation
		$this->Users->validate = array(
			'login' => array(
				'R0'=>array(
					'rule' => 'notEmpty',
					'message' => decode_lng_text('ADMIN_EDIT_LOGIN_R0')
				),
				'R1' => array(
					'rule' =>  '[\.a-zA-Z0-9]+',
					'message' => decode_lng_text('ADMIN_EDIT_LOGIN_R1')
				),
				'R2' => array(
					'rule' =>  'min_4',
					'message' => decode_lng_text('ADMIN_EDIT_LOGIN_R2')
				 )
				//,
				// 'R3' => array(
					// 'rule' =>  'max_8',
					// 'message' => decode_lng_text('ADMIN_EDIT_LOGIN_R3')
				// )				
			),	
			'nom' => array(
				'R0'=>array(
					'rule' => 'notEmpty',
					'message' => decode_lng_text('ADMIN_EDIT_NOM_R0')
				),			
				'R1'=>array(
					'rule' => '[-\' a-zA-Z ]+',
					'message' => decode_lng_text('ADMIN_EDIT_NOM_R1')
				)
				
			),
			'prenom' => array(
				'R0'=>array(
					'rule' => 'notEmpty',
					'message' => decode_lng_text('ADMIN_EDIT_PRENOM_R0')
				),
				'R1'=>array(
					'rule' => '[a-zA-Z]+',
					'message' => decode_lng_text('ADMIN_EDIT_PRENOM_R1')
				)
			),
			'email' => array(
				'R0'=>array(
					'rule' => '[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})',
					'message' => decode_lng_text('ADMIN_EDIT_EMAIL_R0')
				)
			)
		);
//$_SESSION['ind_affiche']=1;
//		 var_dump($this->request->data);
		if ($this->Users->validates($this->request->data)){	
		
				$data = $this->request->data;

				$table = 'oxg_users';
				$this->Users->table = $table;	
				
				$conditions = "login='".$data->login."'";
					
			 // on supprime les infos non utiles à la màj 
				unset($data->user); 
				unset($data->submit);

				$result_upd=$this->Users->update($data,$conditions);
			//	var_dump($result_upd);
				if ($result_upd>0) {  
						$this->Session->setMessage(decode_lng_text('ADMIN_EDIT_SUCCESS'));
						self::liste_users();
						$this->render('admin_index');
					}
					else {
						$this->Session->setMessage(decode_lng_text('ADMIN_EDIT_ECHEC'),'error'); 
					}
			}
		else{
			$this->Session->setMessage(decode_lng_text('ADMIN_EDIT_CORRECTION'),'error'); 
		}
		
		$this->render('admin_edit');
		
/*
* pour comprendre les libellés multi-langues
*/		
// "ADMIN_EDIT_SUCCESS"=>"Le compte a été modifié avec succès",
// "ADMIN_EDIT_ECHEC"=>"Echec lors de la tentative de mise à jour du compte",
// "ADMIN_EDIT_CORRECTION"=>"Merci de corriger vos informations",	
// "ADMIN_EDIT_LIB1" =>"Identifiant absent",
// "ADMIN_EDIT_LIB2" =>"Nom absent",
// "ADMIN_EDIT_LIB3" =>"Prénom absent",
// "ADMIN_EDIT_LIB4" =>"L'adresse mail n'est pas valide",	
		
	} // fin de la fonction admin_edit	

/*
*  Permet de modififier le password d'un utilisateur
*/	
	function admin_passwd() {
//var_dump($this->request->data);
		$user=$this->request->data->user;
		
		$_SESSION['s_groupe']='users';
		$_SESSION['s_page']= 'admin';
		$_SESSION['s_vue']='admin_passwd';
	
		$this->loadModel('Users');
		$table = 'oxg_users';
		$this->Users->table = $table;	
					
		$result_user=$this->Users->find(array(
			'fields'     => '*',
			'conditions' => "login='".$user."'"
		));
		
		foreach($result_user as $row) {
			$_SESSION['s_utilisateur']['login'] = $row->login;
			$_SESSION['s_utilisateur']['passwd'] = $row->passwd;
echo 		$user." ".$row->passwd." ".$_SESSION['s_utilisateur']['passwd']."<br>";	
			$_SESSION['s_utilisateur']['nom'] =ucfirst(strtolower($row->nom));
			$_SESSION['s_utilisateur']['prenom'] = ucfirst(strtolower($row->prenom));
			$_SESSION['s_utilisateur']['email'] = $row->email;
			$_SESSION['s_utilisateur']['privilege'] = $row->privilege;
		}

		$_SESSION['flash'] = array();

		if (isset($this->request->data->pass0) or isset($this->request->data->pass1) or isset($this->request->data->pass2)) {	
			$erreur=0;
			
			$pass1 = addslashes($this->request->data->pass1);
			$pass2 = addslashes($this->request->data->pass2);
echo 		$this->request->data->pass0." - ". md5($this->request->data->pass0)."<br>";				
			if ($_SESSION['s_utilisateur']['passwd']!= md5($this->request->data->pass0) ) {$erreur=1;$this->Session->setMessage(decode_lng_text('ADMIN_PASSWD_ERREUR'),'error');}
			elseif ($pass1=="" and $pass2=="") {$erreur=1; $this->Session->setMessage(decode_lng_text('ADMIN_PASSWD_VIDE'),'error');}
			elseif ($pass1=="" or $pass2=="") {$erreur=1; $this->Session->setMessage(decode_lng_text('ADMIN_PASSWD_INCOMP'),'error');}
			elseif ($pass1!=$pass2) {$erreur=1; $this->Session->setMessage(decode_lng_text('ADMIN_PASSWD_DIFF'),'error');}
	// $_SESSION['ind_affiche']=1;	
			switch($erreur) {
				case 1:
					break;
				
				case 0:
				
					$pass1 = md5($this->request->data->pass1);
					$conditions= "login='".$user."'";
					
					$result_upd=$this->Users->update(array('passwd'=>$pass1),$conditions);
					if ($result_upd>0) {  
						$this->Session->setMessage(decode_lng_text('ADMIN_PASSWD_SUCCESS'));
						$this->render('admin_index');
					}
					else {
						$this->Session->setMessage(decode_lng_text('ADMIN_PASSWD_ECHEC'),'error'); 
					}
				
					break;
				
			}
		}

		$this->render('admin_passwd');
}

/*
* Permet de supprimer un utilisateur
*/
	function admin_delete() {
		
			$user=$this->request->data->user;
			
			$this->loadModel('Users');
			$table = 'oxg_users';
			$this->Users->table = $table;	
			$condition  = "login ='". $user."'";
					
			$row_user=$this->Users->delete(array(
				'conditions' => $condition
			));

			if ($row_user>0) {
				$this->Session->setMessage(decode_lng_text('ADMIN_DELETE_SUCCESS'),'success'); 
			}
			else {
				$this->Session->setMessage(decode_lng_text('ADMIN_DELETE_ECHEC'),'error'); 
			}

			return;
	
	}

} // fin de la classe