<?php
session_start();
require_once('tcpdf_include.php');
//include('./phpqrcode/qrlib.php');

$idEtablissement = $_SESSION["idEtablissement"];

include('/home/iitech/progiciel.geststudent.net/configuration_etabli.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();

date_default_timezone_set('Africa/Porto-Novo'); 
// Récupère l'heure
$d  = getdate();
$y  = $d["year"]; 
$mo = str_pad($d["mon"],2, '0', STR_PAD_LEFT); 
$wd = str_pad($d["mday"],2, '0', STR_PAD_LEFT);

$localtime =  localtime();
$seconde   =  str_pad($localtime[0],2, '0', STR_PAD_LEFT);
$minute    =  str_pad($localtime[1],2, '0', STR_PAD_LEFT);
$heure     =  str_pad($localtime[2],2, '0', STR_PAD_LEFT);
$a = 'à';
$h= ':';
$m= ':';
$date_imprime = "$wd-$mo-$y $a $heure:$minute:$seconde";

header('Content-Type: text/html; charset="utf-8"');
ob_start();
$refFacture = (isset($_GET['ref'])) ? $_GET['ref'] : $_POST['refFacture'];
//$refInter = $_POST['refInter'];

if(isset($_POST['refFacture'])) {
    /*$fichierpdf = "facturebank/"; //repertoire contenant les factures au format pdf
    $fichierpdf .= $_SESSION["idEtablissement"];
    $fichierpdf .= "/";
    $fichierpdf .= "pdf";
    $fichierpdf .= "/";
    $fichierpdf .= $refFacture;
    $fichierpdf .= ".";
    $fichierpdf .= "pdf";*/
?>
    <!-- <script type="text/javascript">
        var strWindowFeatures = "menubar=no,location=no,resizable=yes,scrollbars=yes,status=no";
        //var strWindowFeatures = "";
        var id = "<?php //echo $fichierpdf;?>";
        var lienpdf = "https://progiciel.geststudent.net/Comptable/"+id;
    	window.open(lienpdf, "GestStudent Finance", strWindowFeatures);
    </script> -->

<?php
    //header( "Location: https://progiciel.geststudent.net/Comptable/$fichierpdf" ); 
    //exit();
}
$article= $bddg->prepare('SELECT article FROM universite WHERE idUniversite=?');
$article->execute(array($nomEtablissement['idUniversite']));
$nomArticle = $article->fetch();

$emecef= $bddg -> prepare('SELECT emecef FROM etablissement WHERE 	idEtablissement=:id');
$emecef-> execute(array('id'=>$_SESSION["idEtablissement"])) or die(print_r($emecef->errorInfo));
$tab=$emecef->fetch();
$emecef = $tab['emecef'];	

//$refFacture = $_SESSION['refFacture'];
/*$ref= $bdd->prepare('SELECT * FROM facture WHERE refFacture=? AND refInternationale=?');
$ref->execute(array($refFacture, $refInter));
$reference=$ref->fetch();*/

$ref= $bdd->prepare('SELECT * FROM facture WHERE refFacture=?');
$ref->execute(array($refFacture));
$reference=$ref->fetch();

$typeOperation = $reference['typeOperation'];
$statutOperation = $reference['statutOperation'];
if($statutOperation == 0){
    $statutOperation = 'Succès';
}else if($statutOperation == 1 ){
    $statutOperation = 'En attente';
}else{
    $statutOperation= 'Echec';
}

//Recuperer toutes les informations provenant à afficher de la base de donnees 
/***Le matricule et le statut***/
$req= $bdd->prepare('SELECT * FROM tabetudiant WHERE matricule=?');
$req->execute(array($reference['matricule']));
$matricule_statut=$req->fetch();

/*L'université*/
$uni= $bdd->prepare('SELECT * FROM `universite`');
$uni->execute();
$nomUniversite= $uni->fetch();

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

//couleur de l'établissement
$couleur = $nomEtablissement['couleur'];

$typefacture = $reference['typefacture'];
$infoRecu = '';
$code_emecef = ''; //E-MECeF
if($typefacture == 'FA') {
    $refFN  = $reference['refFN'];
    $refFV = $reference['code_me_ce_fdgi']; //E-MECeF
    $code_emecef = '
    <tr>
        <td style="width:20%;">CODE MECeF/DGI FV</td>
        <td style="width:5%;">:</td>
        <td>'.$refFV.'</td>
    </tr>';
    $fadate = $reference['dateTransaction'];
    $infoRecu = '<div style="font-family:Impact;"><h5 style="margin:0;padding-top:50px;background-color:'.$couleur.';color:#fff;">Référence reçu d\'avoir : '.$refFacture.' ############################### Référence reçu : '.$refFN.' en date du : '.$fadate.'</h5></div> ';
}else{
    $infoRecu = '<div style="font-family:Impact;"><h5 style="margin:0;padding-top:50px;background-color:'.$couleur.';color:#fff;">Référence reçu : '.$refFacture.'</h5></div>';
}

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


/***La filiere , 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();

$statutetud = 0;
$niveauFormation = 0;
try{
	$sql2 = "SELECT statut, niveauFormation  FROM tabinscription  WHERE (matricule = :matri AND annee_acad = :acad)";
	$statement2 = $bdd->prepare($sql2);
	$statement2->bindParam(':matri',  	$reference['matricule'], 	PDO::PARAM_STR);
	$statement2->bindParam(':acad',  	$reference['annee_acad'], 			PDO::PARAM_STR);
	$statement2->execute();
	$row2=$statement2->fetch(PDO::FETCH_ASSOC);
	$statutetud     = $row2['statut'];	
	$niveauFormation = $row2['niveauFormation'];	
}catch(PDOException  $e ){
		$impossible ='
		<div style="width:500px;background:#fff;padding:20px;border-radius:5px;font-family:Calibri;box-shadow:0px 0px 5px #ccc inset;margin:auto;">
			<h3 style="color:red;">Attention</h3>
			<div style="color:#555;">
				'.$e->getMessage( ).'.<br/>
				<a href=""><button style="width:100px;border:1px solid #ccc;text-align:center;background:#fff;">Retour</button></a>
			</div>
		</div>
		';
		echo $impossible;
}

//Recherche du diplome préparé
if($niveauFormation == 1) {
    $diplomeprepare = 'Licence';
}else{
    $diplomeprepare = 'Master';
}

//Statut de l'etudiant
$statutEtudiant=$bdd->prepare('SELECT statut FROM statuts WHERE idStatut=? AND idEtablissement=?');
$statutEtudiant->execute(array($statutetud, $nomEtablissement['idEtablissement']));
$statutEtudiant= $statutEtudiant->fetch();

//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($matricule_statut['matricule'],$idMention['idFiliere'],$reference['annee_acad'],$reference['annee'])) or die(print_r($qrcode->errorInfo()));
$qrcode=$qrcode->fetch();

//Cherchons le qrCode de l'etablissement
$qrcodeEta= $bdd->prepare('SELECT codeQrEtablis FROM codeqretablis WHERE idEtablissement=? AND idFiliere=? AND annee_acad=? AND annee=?');
$qrcodeEta->execute(array($nomEtablissement['idEtablissement'],$idMention['idFiliere'],$reference['annee_acad'],$reference['annee']));
$qrcodeEta=$qrcodeEta->fetch();

$compte= $bddg->prepare('SELECT * FROM comptebancaire WHERE idEtablissement=?');
$compte->execute(array($_SESSION['idEtablissement']));
$nomCompte= $compte->fetch();

//Déterminer le montant
$resMontant = $bdd->prepare('SELECT * FROM montant WHERE idEtablissement=? AND idFiliere =? AND annee =? AND periode =? AND idStatut =?');
$resMontant->execute(array($nomEtablissement['idEtablissement'],$idMention['idFiliere'],$reference['annee'],$reference['annee_acad'],$statutetud));
$Montant            = $resMontant->fetch();
$montant       	    = $Montant['scolarite'] ;
$fraisInscription   = $Montant['fraisInscription'] ;//	

$montTotaleDu = 0; //pour l'ensemble des années
/** Pour chaque étudiant, on fait la recherche de ces dettes antérieures */
$sqlm 	 = "SELECT * FROM tabinscription WHERE annee_acad < :acad AND matricule =:matr";
$resm     = $bdd -> prepare($sqlm);
$resm     ->execute(array('acad'=>$reference['annee_acad'], 'matr'=>$reference['matricule'])) or die(print_r($resm->errorInfo()));
while($donneem=$resm->fetch()) {
	//Déterminer le montant
	$resMontantm = $bdd->prepare('SELECT * FROM montant WHERE idEtablissement=? AND idFiliere =? AND annee =? AND periode =? AND idStatut =?');
	$resMontantm->execute(array($nomEtablissement['idEtablissement'],$donneem['idFiliere'],$donneem['annee'],$donneem['annee_acad'],$donneem['statut']));
	$Montantm   = $resMontantm->fetch();
	$fraism     = $Montantm['scolarite'] + $Montantm['fraisInscription'];
	
	$p = ($donneem['annee_acad']-1).'-'.$donneem['annee_acad'];
	$montantDu = $fraism - $donneem['montant'];
	$affiche .= '['.$p.' : '.$montantDu.' FCFA]   ';
	$montTotaleDu = $montTotaleDu + $montantDu;
}

$scolarite = $montant + $fraisInscription + $montTotaleDu;
//Cherchons le montant payé par l'etudiant
$montantp= $bdd->prepare('SELECT montant FROM tabinscription WHERE matricule=? AND idFiliere=? AND annee_acad=? AND annee=?');
$montantp->execute(array($matricule_statut['matricule'],$idMention['idFiliere'],$reference['annee_acad'],$reference['annee'])) or die(print_r($montantp->errorInfo()));
$montantp=$montantp->fetch();

//Monatnt dû 
//=======================================Evaluation du montant total payé par l'etudiant===========================================================//
$valeurpayer = 0;
$totalpayer= $bdd->prepare('SELECT montant, typefacture FROM facture WHERE matricule =? AND annee=? AND niveau =? AND annee_acad =? AND idFiliere =?');
$totalpayer->execute(array($matricule_statut['matricule'], $reference['annee'], $reference['niveau'], $reference['annee_acad'], $reference['idFiliere'])) or die(print_r($totalpayer->errorInfo()));
while($total=$totalpayer->fetch()) {
    if($total['typefacture'] == 'FV') {
        $valeurpayer += $total['montant'];
    }else{
        $valeurpayer -= $total['montant'];
    }
}
//=======================================Evaluation du montant total payé par l'etudiant===========================================================//
$soldedu = $scolarite - $valeurpayer;

$niveauFormation = $idMention['sigleFilieres'];
$niveauFormation .= " ";
$niveauFormation .= $reference['annee'];

// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, 'A5', true, 'UTF-8', false);
	
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('IITECH');
$pdf->SetTitle('');
$pdf->SetSubject('Reçu');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');

$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);



// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
$PDF_MARGIN_TOP=8;
$pdf->SetMargins(PDF_MARGIN_LEFT, $PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);


// set auto page breaks
$PDF_MARGIN_BOTTOM=8;
$pdf->SetAutoPageBreak(TRUE, $PDF_MARGIN_BOTTOM);

// set image scale factor
$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);
}

// ---------------------------------------------------------

// add a page
$pdf->AddPage('P' , 'A3');
if(isset($_POST['refFacture'])) {
    //$date_imprime = $dateTransaction;
    // set bacground image
    $pdf->Image('https://progiciel.geststudent.net/Inscription/imageEtudiant/duplicata.jpg', 175, 65, 20, 20, 'JPG', '', '', true, 500, '', false, false, 0, false, false, true);
    
    // set bacground image
    $pdf->Image('https://progiciel.geststudent.net/Inscription/imageEtudiant/duplicata.jpg', 175, 265, 20, 20, 'JPG', '', '', true, 500, '', false, false, 0, false, false, true);
}
//<h3>Ministère de l\'Enseignement Supérieur et de la Recherche Scientifique</h3>
$periode = ($reference['annee_acad'] - 1).'-'.$reference['annee_acad'];
$pdf->SetFont('dejavusans', '', 10);
$html = '
		<div style="font-family:Calibri;font-size:10px;">
		<header style="text-align:center;">
			<table style="margin:0;padding:0;padding-top:10px;">
				<tr>
					<td style="width:100%;display:inline-block;text-align:center;font-family:Comic;font-size:10px;">
					    <img src="https://progiciel.geststudent.net/Admin/'.$nomUniversite['logorecu'].'" alt="" style="width:1020px;height:115px;"/>
					</td>
				</tr>
			</table>
		</header>
		<table style="padding-top:5px;">
		<tr>
			<td style="height:20px; width:100%;padding-top:10px;font-size:8px;text-align:center;">
				<div  style="font-family:Calibri;color:#000105;width:35%;text-align:center;">
					<b><i>GestStudent Comptabilité</b></i> <br/>
					<b><i style="font-size:6px;">https://geststudent.net/</b></i><br/>
				</div>
			</td>
		</tr>
		</table>
		
		<div style="font-family:Impact;"><h5 style="margin:0;padding-top:50px;background-color:'.$couleur.';color:#fff;">Identité</h5></div>
		<table id="identity" style="font-family:Helvetica;font-size:11px;">
			<tr>
			<td id="identity_first" style="width:65%;">
				<span ><u>Nom et Prénom</u> : &nbsp;&nbsp; <b><i style="font-size:8px;"> '.$matricule_statut['nom'].' '.$matricule_statut['prenom'].'</i></b></span><br>
				<span><u>Spécialité</u> :&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;<i style="font-size:8px;"><b> '.$niveauFormation.'</b></i></span><br>
				<span><u>Diplôme préparé</u> : &nbsp;<b><i style="font-size:8px;"> '.$diplomeprepare.'</i></b></span><br>
				<span><u>Statut</u> :  &nbsp; &nbsp;&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;<b><i style="font-size:8px;"> '.$statutEtudiant['statut'].'</i></b></span>
			</td>
			<td id="identity_second" style="width:35%;">
				<span><u>Sexe</u> : &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;<b><i style="font-size:8px;">'.$matricule_statut['sexe'].'</i></b></span><br>
				<span><u>Matricule</u> :&nbsp;&nbsp;<b><i style="font-size:8px;">'.$matricule_statut['matricule'].'</i></b></span><br>
				<span><u>Période</u> : &nbsp;&nbsp;<b><i style="font-size:8px;">'.$periode.'</i></b></span><br>
			</td>
			</tr>
		</table>
	
		<section>
			<article>
				'.$infoRecu.'
				<table id="identity" style="font-family:Helvetica;font-size:11px;">
					<tr>
					<td id="identity_first" style="width:50%;">
						<span ><u>Type opération </u> : &nbsp; <b><i style="font-size:8px;">'.$typeOperation.' </i></b></span><br><br><br>
						<span><u>Montant opération </u> : &nbsp;<b><i style="font-size:8px;">'.$reference['montant'].' FCFA</i></b></span>
					</td>
					<td id="identity_second" style="width:50%;">
						<span><u>Statut opération </u> : &nbsp; <b><i style="font-size:8px;">'.$statutOperation.'</i></b></span><br><br><br>
						<span><u>Solde dû </u> : &nbsp;<b><i style="font-size:8px;">'.$soldedu.' FCFA [Attention : Solde dû à la date d\'impression du duplicata]</i></b></span>
					</td>
					</tr>
				</table>
			</article>
			<article>
				<div></div>
				<h5 style="margin:0;padding:0;background-color:'.$couleur.';color:#fff;">Consulter vos résultats avec GestStudent Mobile</h5>
				<p style="border:1px solid #ccc;text-align:justify;font-size:7px;">GestStudent : <b><i>Une application développée par l\'Institut d\'Innovation Technologique(IITECH)</b></i>. A '.$nomArticle['article'].' '.$nomUniversite['descruni'].',
				vos résultats sont disponibles à travers l\'application mobile GestStudent téléchargeable sur le Play Stor.</p>
			</article>
		
			<table>
				<tr>
					<td style="width:20%;margin:0;">
						<img style="width:65px;height:65px;" src="https://progiciel.geststudent.net/Inscription/qrcode/'.$_SESSION["idEtablissement"].'/'.$qrcode['codeQr'].'.png" alt=""/>
					</td>
					<td style="text-align:center;width:60%;">
						<div></div>
						<i>Fait le '.$date_imprime.'</i><br/><br/>
					    <table border = "1">
					        <tr>
					            <td style="width:40%;margin:0;"><i><b>Etudiant</b></i><br/><br/><br/></td>
					            <td style="width:20%;margin:0;"><i><b>Signature</b></i></td>
					            <td style="width:40%;margin:0;"><i><b>Comptable</b></i></td>
					        </tr>
					    </table>
					</td>
					<td style="width:10%;margin:0;">
					</td>
					<td style="width:10%;margin:0;">
						<img style="width:120px;height:120px;" src="https://progiciel.geststudent.net/Inscription/qrcode/'.$_SESSION["idEtablissement"].'/'.$qrcodeEta['codeQrEtablis'].'.png" alt=""/>
					</td>
				</tr>
			</table>
		</section>
		<br/>
		<hr/>';
        if($emecef == 'YES') {
            $html .= '
        		<table>
        			<tr>
        				<td style="width:70%;margin:0;">
        				    <table cellspacing="7">
        				        <tr>
        				            <td style="width:20%;">CODE MECeF/DGI</td>
        				             <td style="width:5%;">:</td>
        				            <td>'.$reference['code_me_ce_fdgi'].'</td>
        				        </tr>
        				        <tr>
        				            <td style="width:20%;">MECeF NIM</td>
        				            <td style="width:5%;">:</td>
        				            <td>'.$reference['nim_mecef'].'</td>
        				        </tr>
        				        <tr>
        				            <td style="width:20%;">MECeF Compteurs</td>
        				            <td style="width:5%;">:</td>
        				            <td>'.$reference['counters_mecef'].'</td>
        				        </tr>
        				        <tr>
        				            <td style="width:20%;">MECeF Heure</td>
        				            <td style="width:5%;">:</td>
        				            <td>'.$reference['date_time_mecef'].'</td>
        				        </tr>
        				        '.$code_emecef.'
        				    </table>
        				</td>
        				<td style="width:30%;margin:0;">
        					<img style="width:105px;height:105px;" src="https://progiciel.geststudent.net/Comptable/facturebank/'.$_SESSION["idEtablissement"].'/qrmecef/'.$reference['refFacture'].'.png" alt=""/>
        				</td>
        			</tr>
        		</table><br/>
            ';    
        }else{
            $html .= '
                <div >
                    <div style="text-align: center ; color:#808080; font-size:6px";>
                        <p  class="">Si vous avez des questions ou besoins d\'aide , vous pouvez nous contacter<br>Siege Social: Abomey-Calavi  <br /> Tél: (00229) 61373500 <br /> iitech@iitech-benin.net <br />IITECH-BENIN : https://iitech-benin.net/</p>
                    </div>
                </div>
            ';    
        }
$pdf->writeHTML($html, true, 0, true, true);
$pdf->writeHTML('<hr />', true, 0, true, true);
$pdf->writeHTML($html, true, 0, true, true);
$pdf->lastPage();
ob_end_clean();
//echo $html;
// ---------------------------------------------------------
//Nom du fichier pdf de l'etudiant
//$fichierpdf = "//..//..//facturebank//"; //repertoire contenant les factures au format pdf
//$fichierpdf .= $_SESSION["idEtablissement"];
//$fichierpdf .= "//";
//$fichierpdf .= "pdf";
//$fichierpdf .= "//";
$fichierpdf = $refFacture;
$fichierpdf .= ".";
$fichierpdf .= "pdf";
//Close and output PDF document
$pdf->Output($fichierpdf, 'D');

?>