<?php
session_start();
if(!isset($_SESSION["etudiant_i"]) OR !isset($_SESSION["idEtablissement"])){
	header("Location:index.php");
	exit();
}
require_once('tcpdf_include.php');
//include('../../info-admin.php');
//include('../../notifierErreur.php');

include('liste-ue.php');
include('function.php');

include_once('../../Library/Basededonnees.php');

$DB_DATABASE = $_SESSION["DB_DATABASE"];

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

$databaseg = new Basededonnees('iitech_universite');
$bddg = $databaseg->getBdd();

//Etablissement
$etabli= $bdd->prepare('SELECT * FROM etablissement WHERE idEtablissement=?');
$etabli->execute(array($_SESSION['idEtablissement']));
$nomEtablissement= $etabli->fetch();

$ville = $nomEtablissement['ville'];
//Etablissement
$univ= $bdd->prepare('SELECT * FROM universite WHERE idUniversite=?');
$univ->execute(array($nomEtablissement['idUniversite']));
$nomUniv= $univ->fetch();

$req1=$bdd->prepare('SELECT idMention,idFiliere, intituleFilieres FROM filieres WHERE 	idFiliere=?');
$req1->execute(array($_GET['idFiliere']));
$idMention=$req1->fetch();

/***La mention et le domaine***/
$req2=$bddg->prepare('SELECT idDomaine,sigleMention FROM mention WHERE idMention=?');
$req2->execute(array($idMention['idMention']));
$resultatMention=$req2->fetch();

$req3=$bddg->prepare('SELECT sigleDomaine FROM domaine WHERE idDomaine=?');
$req3->execute(array($resultatMention['idDomaine']));
$resultatDomaine=$req3->fetch();


$annee = $_GET['annee'];
if($_GET['niveau'] == 1) {
	$diplome = "Licence"; $CreditFormation = 180;		  
}else if($_GET['niveau'] == 2){
	$diplome = "Master"; $CreditFormation = 120;		  
}else{
	$diplome = "Doctorat"; $CreditFormation = 180;	
}
//on recupère les id des semestres, le matricule et l'année depuis la page html du releve
$id_semestre1	=	$_GET['annee'] * 2 - 1;;
$id_semestre2	=	$_GET['annee'] * 2;
$semestre 		= 	$id_semestre2;
$ue1 = getAllUE($_GET['idFiliere'], $id_semestre1, $_GET['annee'], $_GET['niveau'], $_GET['academique'], $bdd); //ON récupére tout les ue de la filiere au premier semestre
$ue2 = getAllUE($_GET['idFiliere'], $id_semestre2, $_GET['annee'], $_GET['niveau'], $_GET['academique'], $bdd); //ON récupére tout les ue de la filiere au second semestre

//requete pour la recuperation de l'etudiant.
$selection= $bdd -> prepare("SELECT * FROM tabetudiant INNER JOIN tabinscription ON tabetudiant.matricule=tabinscription.matricule
							WHERE idFiliere=? AND annee=? AND niveauFormation=? AND tabinscription.annee_acad=? AND tabinscription.matricule=?");
$array = array_merge([$_GET['idFiliere']], [$annee], [$_GET['niveau']], [$_GET['academique']], [$_GET['matricule']]);							
$selection->execute($array);

// Extend the TCPDF class to create custom Header and Footer
class MYPDF extends TCPDF {
	// Page footer
	public function Footer() {
		// Position at 15 mm from bottom
		$this->SetY(-15);
		// Set font
		$this->SetFont('helvetica', 'I', 8);
		$this->SetLineWidth(0.1);
		$this->SetDrawColor(0, 0, 0);
		$this->Cell(0, 10, 'NB : Cette fiche ne peut en aucun cas tenir lieu de relevé de notes.', 0, false, 'C', 0, '', 0, false, 'T', 'M');
	}
}
// create new PDF document
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('IITECH');
$pdf->SetTitle($idMention['intituleFilieres']);
$pdf->SetSubject('Relevé de notes');
$pdf->SetKeywords('IITECH, PDF');

// remove default header/footer
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(true);

$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// set margins
//$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
	require_once(dirname(__FILE__).'/lang/eng.php');
	$pdf->setLanguageArray($l);
}

$pdf->AddPage('P','A4');
$pdf->SetFont('times', '', 10);
$j=0;
$annee_encour = ''; 
switch ($annee) {
    case 1:
        $annee_encour="DE LA PREMIERE ANNEE";
        break;
    case 2:
        $annee_encour="DE LA DEUXIEME ANNEE";
        break;
    case 3:
        $annee_encour="DE LA TROISIEME ANNEE";
        break;    
    default:
        break;
}

while($etudiant=$selection->fetch(PDO::FETCH_ASSOC)) {
	//Cherchons le qrCode de l'etudiant
	$qrcode= $bdd->prepare('SELECT codeQr FROM qrcode WHERE matricule=? AND idFiliere=? AND annee_acad=? AND annee=?');
	$qrcode->execute(array($etudiant['matricule'], $_GET['idFiliere'], $_GET['academique'], $annee)) or die(print_r($qrcode->errorInfo()));
	$qrcode=$qrcode->fetch();
	//les variables 
	$total_credi_formation=0;
	$total_ue_entame=0;
	$total_ue_valide=0;
	$total_ue_restant_a_valide=0;
	$total_credit_cumule=0;
	$total_credit_capitalie=0;
	$total_credit = 0;
	$somme_moyenne=0;
	$j++;
	// Image example with resizing
	$extension = explode($nomEtablissement['nameimgeta'], '.');
	$chemin = 'https://progiciel.geststudent.net/Admin/';
	$chemin .= $nomEtablissement['nameimgeta'];
	$pdf->Image($chemin, 7, 10, 20, 20, '', '', '', true, 150, '', false, false, 0, false, false, false);
	$text1='<span align="center" color="blue">'.$nomUniv['descruni'].'</span><br/>
			<span align="center">-*-*-*-</span><br/>
			<span align="center" color="#ec067d">'.$nomEtablissement['descreta'].'</span><br/>';
	$pdf->writeHTML($text1, true, false, true, false, '');
	if($j == 1){
		$pdf->Ln(6);
	}else{
		$pdf->Ln(15);
	}


	$releve='<h4 align="center">FICHE BILAN '.$annee_encour.'</h><br/><br/>';
	$pdf->writeHTML($releve, true, false, true, false, '');

	$pdf->SetFont('times', '', 8.3);

	//Affichade des infos sur le nom prenom datenaiss.........
	$text2 = entete1($etudiant['nom'], $etudiant['prenom'], $etudiant['sexe'], $etudiant['date_nais'], $etudiant['lieu_nais'], $etudiant['matricule'], $resultatDomaine['sigleDomaine'], $diplome, $resultatMention['sigleMention'], $idMention['intituleFilieres']);

	$pdf->writeHTML($text2, true, false, true, false, '');
	$pdf->SetLineWidth(0.508);
	// set color for cell border
	$pdf->SetDrawColor(255,0,0);
	// set filling color
	$pdf->SetFillColor(255,255,255);
	$pdf->SetFont('helvetica', '', 10);
	$pdf->SetXY(130, 65.5);
	$pdf->Cell(32, 0, 'N° DU SEMESTRE', 1, $ln=0, 'C', 0, '', 0, false, 'T', 'C');
	$pdf->SetXY(180, 65.5);
	$pdf->Cell(13, 0, $id_semestre1.' & '.$id_semestre2, 1, $ln=0, 'C', 0, '', 0, false, 'T', 'C');
	$pdf->SetXY(175, 65.5);
	$pdf->writeHTML(':', true, false, true, false, '');

	$extension = explode($nomUniv['nameimguni'], '.');

	$chemin1 = 'https://progiciel.geststudent.net/Admin/';
	$chemin1 .= $nomUniv['nameimguni'];
	$pdf->Image($chemin1, 179.8, 10, 20, 20, '', '', '', true, 150, '', false, false, 0, false, false, false);

	//style du code QR
	$style = array(
		'border' => 0,
		'vpadding' => 'auto',
		'hpadding' => 'auto',
		'fgcolor' => array(0,0,0),
		'bgcolor' => false, //array(255,255,255)
		'module_width' => 1, // width of a single module in points
		'module_height' => 1            // height of a single module in points
	);

	$extension = explode($etudiant['cheminPhoto'], '.');

	$cheminQR = 'https://progiciel.geststudent.net/Inscription/qrcode/';
	$cheminQR .= $_SESSION['idEtablissement'];
	$cheminQR .= '/';
	
	$pdf->Image($cheminQR.$qrcode['codeQr'].'.png', 7.8, 30, 20, 20, 'png', '', '', true, 150, '', false, false, 0, false, false, false);

	$pdf->Image('https://progiciel.geststudent.net/Inscription/'.$etudiant['cheminPhoto'], 179.8, 30, 20, 20, '', '', '', true, 150, '', false, false, 0, false, false, false);

	$pdf->SetFont('times', '', 7);

	//=================Affichage de l'entete du tableau====================================================
	$contenu_releve= entete2();
	$contenu_releve.=
	'<tr>
		<td class="vert" colspan="9"> SEMESTRE '.$id_semestre1.'</td>
	 </tr>';

	//=====================================================================================================

	//Total crédit cumulés dans le cursus 
	$resultat = 'A';
	$sql1 = 'SELECT * FROM tabinscriunite WHERE matricule =? AND tabinscriunite.niveauFormation =? AND resultat =? AND annee <=?';
	$credcu1 = $bdd->prepare($sql1);
	$credcu1->execute(array($etudiant['matricule'],  $_GET['niveau'], $resultat, $annee));
	while($row = $credcu1->fetch(PDO::FETCH_ASSOC))  {
		$code_unite 	= $row['code_unite'];
		$pi          	= $row['premiere_inscription'];
		$idF 			= $row['idFiliere'];	
		$ann 			= $row['annee'];	
		$sql2 			= 'SELECT credit FROM unites WHERE code_unite =? AND idFiliere =? AND annee_acad = ? AND semestre <=? AND annee =?';
		$credcu2 		= $bdd->prepare($sql2);
		$credcu2->execute(array($code_unite,  $idF, $pi, $semestre, $ann));
		$credcu2 = $credcu2->fetch();
		$total_credit_cumule += $credcu2['credit'];
	}

	//Total UE entamées
	$sql0 = 'SELECT * FROM tabinscriunite WHERE matricule =? AND tabinscriunite.niveauFormation =? AND annee <=?';
	$credcu1 = $bdd->prepare($sql0);
	$credcu1->execute(array($etudiant['matricule'],  $_GET['niveau'], $annee));
	while($row = $credcu1->fetch(PDO::FETCH_ASSOC))  {
		$code_unite 	= $row['code_unite'];
		$pi          	= $row['premiere_inscription'];
		$idF 			= $row['idFiliere'];	
		$ann 			= $row['annee'];	
		$sql2 			= 'SELECT credit FROM unites WHERE code_unite =? AND idFiliere =? AND annee_acad = ? AND semestre <=? AND annee =?';
		$credcu2 		= $bdd->prepare($sql2);
		$credcu2->execute(array($code_unite,  $idF, $pi, $semestre, $ann));
		$total_ue_entame += $credcu2->rowCount();
	}


	//Total UE restant à valider dans le cursus
	$resultat = 'R';
	$sql1 = 'SELECT * FROM tabinscriunite WHERE matricule =? AND tabinscriunite.niveauFormation =? AND resultat =? AND annee <=?';
	$credcu1 = $bdd->prepare($sql1);
	$credcu1->execute(array($etudiant['matricule'],  $_GET['niveau'], $resultat, $annee));
	while($row = $credcu1->fetch(PDO::FETCH_ASSOC))  {
		$code_unite 	= $row['code_unite'];
		$pi          	= $row['premiere_inscription'];
		$idF 			= $row['idFiliere'];	
		$ann 			= $row['annee'];	
		$sql2 			= 'SELECT credit FROM unites WHERE code_unite =? AND idFiliere =? AND annee_acad = ? AND semestre <=? AND annee =?';
		$credcu2 		= $bdd->prepare($sql2);
		$credcu2->execute(array($code_unite,  $idF, $pi, $semestre, $ann));
		//$credcu2 = $credcu2->fetch();
		$total_ue_restant_a_valide += $credcu2->rowCount();
	}

	//===========================================================Affichage des unités d'enseignements==================================================================================
	$contenu_releve.=afficher_matiere($ue1, $_GET['idFiliere'], $id_semestre1, $annee, $_GET['niveau'], $_GET['academique'], $etudiant['matricule'], $bdd);
	$contenu_releve.=
	'<tr>
		<td class="vert" colspan="9"> SEMESTRE '.$id_semestre2.'</td>
	 </tr>';
	$contenu_releve.=afficher_matiere($ue2, $_GET['idFiliere'], $id_semestre2, $annee, $_GET['niveau'], $_GET['academique'], $etudiant['matricule'], $bdd);

	/////////////////////=================================================================================================================================////////////////////////////

	$la_moyenne=0;
	if($total_credit!=0)$la_moyenne=$somme_moyenne/$total_credit;
	$grade			= gradeECTS($la_moyenne, $bdd);  
	$la_moyenne  	= sprintf("%.2f",myround($la_moyenne,2));		
	$entier = intval($la_moyenne);  // et la partie avant
	if(strlen($entier) < 2){
		$la_moyenne = "0".$la_moyenne;
	}

    $html = '<span style="background-color:yellow;color:blue;">&nbsp;COPIE ETUDIANT&nbsp;</span>
    <p stroke="0.2" fill="true" strokecolor="yellow" color="blue" style="font-family:helvetica;font-weight:bold;font-size:15pt;text-align:center;">
    Cette fiche ne peut en aucun cas tenir lieu de relevé de notes</p>';
    $pdf->writeHTML($html, true, false, true, false, '');
				  
	//Affiche du message du résultats de fin d'année.
	$message = message($bdd, $etudiant['matricule'], $annee);

	$contenu_releve.= affichePiedsParcourt($CreditFormation, $total_ue_entame, $total_ue_valide, $total_ue_restant_a_valide, $total_credit_cumule, $total_credit_capitalie, $id_semestre1, $semestre);

	$grad='<em>Grade ECTS :</em> <span style=" font-weight: bold ">'.$grade.'</span>';
	$moyenne='<em>Moyenne semestre '.$id_semestre1.' & '.$id_semestre2.' : </em> <span style=" font-weight: bold;">'.$la_moyenne.'</span>';

	$decision='<span style="font-weight: bold; text-decoration: underline ">Décision  du Conseil de Département</span><span >:</span>';
	$decision.=$message;
	$frequence='*<i style="color: red">Fréquence d\'inscription dans l\'UE</i>';

	$contenu_releve.= affichePiedsParcourt2($decision, $frequence, $moyenne, $grad, $ville);

	$pdf->writeHTML($contenu_releve, true, false, true, false, '');
	
	// add a page
	//$pdf->AddPage();
}
//$pdf->Ln(10);
//$adresse = $nomEtablissement['adresse'];
//$contenu_releve1 = tableauSpecification($_GET['idFiliere'], $annee, $_GET['niveau'], $_GET['academique'], $adresse, $bdd);	    
//$pdf->writeHTML($contenu_releve1, true, false, true, false, '');	
//echo $contenu_releve;
$pdf->Output('Releve_'.$_GET['academique'].'.pdf', 'I');
