<?php
// include db connect class
require_once 'include/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

$matricule = "";
$niveau = "";

if(isset($_POST['matricule'])){
	$matricule = $_POST['matricule'];
}
if(isset($_POST['niveau'])){
    $niveau = $_POST['niveau'];
}
mysql_query("SET NAMES utf8");

$sql11 = "select max(annee_acad) as annee_acad from tabetudiant where matricule = '$matricule'";
$result11 = mysql_query($sql11);
$tab11     = mysql_fetch_array($result11, MYSQL_ASSOC);
$annee_acad = $tab11['annee_acad'];

$sql1 = "select annee, idFiliere from tabetudiant where matricule = '$matricule' and annee_acad = '$annee_acad'";
$result1 = mysql_query($sql1);
$tab     = mysql_fetch_array($result1, MYSQL_ASSOC);
$annee = $tab['annee'];
$idfiliere = $tab['idFiliere']; //

if($annee == 1) {
      $ids1 = 1;
      $ids2 = 2;
}else if($annee == 2) {
      $ids1 = 3;
      $ids2 = 4;
} else if($annee == 3){
      $ids1 = 5;
      $ids2 = 6;
}
$json1  = array();
$json2 = array();
$json  = array();

$sql = "select code_unite, intituleUnite, credit from unites where idFiliere = $idfiliere and annee_acad = '$annee_acad' AND annee = '$annee' and semestre = $ids1 order by intituleUnite ASC"; 
$result = mysql_query($sql);
$arr1 = array('code_unite' => "::::::::::::::::::::::::::", 'intituleUnite' => "SEMESTER $ids1 ::::::::::::::::::::::::::");
$json1['unites'][]= $arr1;
if(mysql_num_rows($result)){
	while($row=mysql_fetch_assoc($result)){
		$unites = $row['intituleUnite'];
		$code_unite = $row['code_unite'];
		$json1['unites'][]=$row;		
		$sql1 = "select intituleEcu, credit from ecu where idFiliere = $idfiliere and annee_acad = '$annee_acad' AND annee = '$annee' and code_unite = '$code_unite'  order by  intituleEcu ASC"; 		 
		$result1 = mysql_query($sql1);
		while($row1=mysql_fetch_assoc($result1)){
			$json2[$unites][]=$row1;
		}
	}
}
$sql2 = "select code_unite, intituleUnite, credit from unites where idFiliere = $idfiliere and annee_acad = '$annee_acad' AND annee = '$annee' and semestre = $ids2 order by intituleUnite ASC"; 
$result2 = mysql_query($sql2);
$arr2 = array('code_unite' => "::::::::::::::::::::::::::", 'intituleUnite' => "SEMESTER $ids2 ::::::::::::::::::::::::::");
$json1['unites'][]= $arr2;
if(mysql_num_rows($result2)){
	while($row2=mysql_fetch_assoc($result2)){
		$unites2 = $row2['intituleUnite'];
		$code_unite2 = $row2['code_unite'];
		$json1['unites'][]=$row2;		
		$sql3 = "select intituleEcu, credit from ecu where idFiliere = $idfiliere and annee_acad = '$annee_acad' AND annee = '$annee' and code_unite = '$code_unite2'  order by  intituleEcu ASC"; 		 
		$result3 = mysql_query($sql3);
		while($row3=mysql_fetch_assoc($result3)){
			$json2[$unites2][]=$row3;
		}
	}
}
$json['ue'][]   = $json1;
$json['ecue'][] = $json2;
echo json_encode($json); 
?>