<?php
session_start();
/*
** Classe connexion
*/
// namespace Library;
include_once('Basededonnees.php');

class Connexion{
	private $bdd;
	/*
	# Pour la connexion :
	# Admin => 0
	# Professeur => 1
	# Etudiant => 2
	*/
	public function __construct($DB_DATABASE){

		$database = new Basededonnees($DB_DATABASE);
		$this->bdd = $database->getBdd();
	}

	public function connect_user($pseudo, $password){

		$query="SELECT * FROM users_student WHERE username=?";
		//$query="SELECT * FROM users_student WHERE username=?";

		$req= $this->bdd->prepare($query);
		$req->execute(array($pseudo));
        
		if($donnees= $req->fetch()){
        	$verify = password_verify($password, $donnees['password']); 
        	if($verify) {
			//if($donnees['password'] == crypt($password,$donnees['password'])){

				switch($donnees['type_user']){
					case 0:
						//Récuperer l'établissement de l'étudiant
						/*$req_eta_etu="SELECT  eta.idEtablissement AS ideta FROM tabetudiant AS etu
									 INNER JOIN departement AS depart ON etu.idDepartement = depart.idDepartement
									 INNER JOIN etablissement AS eta ON depart.idEtablissement = eta.idEtablissement
									 INNER JOIN academique AS a ON a.idEtablissement= eta.idEtablissement
									 WHERE etu.matricule=? AND a.affiche=?";

						$requete = $this->bdd->prepare($req_eta_etu);
						$requete->execute(array($donnees['matricule'],'YES'));
						$rep = $requete->fetch();
						$idEtablissement = $rep['ideta'];*/

						$idEtablissement = $donnees["idEtablissement"] ;
						$_SESSION['idEtabli'] = $donnees["idEtablissement"] ;
						$_SESSION["etudiant_i"]	= $donnees["matricule"];
						
						include('/home/iitech/progiciel.geststudent.net/configuration_etabli.php');
						
                    	$universite= $this->bdd -> prepare('SELECT * FROM etablissement WHERE 	idEtablissement=:id');
                    	$universite-> execute(array('id'=>$idEtablissement)) or die(print_r($universite->errorInfo));
                    	$universite=$universite->fetch();
                    	$idUniv = $universite['idUniversite'];
                    
                        if($idUniv == 1) {
                            //header('Location:'.'https://info.geststudent.net/'); 
                            //exit();
                        }
						header("Location: accueil.php");
						break;
					default :
						header("Location: index.php");
						$_SESSION['message'] = "Echec de la tentative de connexion. Droit inssufisant.";  
				}
			}else{
				header("Location: index.php");
				$_SESSION['message'] = "Echec de la tentative de connexion. Vérifier votre login ou mot de passe.";  
			}
		}else{
			header("Location: index.php");
			$_SESSION['message'] = "Echec de la tentative de connexion. Vérifier votre login ou mot de passe.??????????????"; 
		}

	}
}
