<?php 
session_start();
require_once(dirname(__DIR__, 2) . '/config.php');
require_once(BASE_PATH . '/db/idl_connect.php');

if(isset($_SESSION['user_droits'])) {
	if($_SESSION['user_droits'][5]!="2") {
		echo '<p class="noaccess">'.NOMODULE.'<br><a href="../../index.php">'.ACCUEIL.'</a></p>';
	}
	else {
		// récupération des infos du modèle
		$modeles = mysqli_query($bdd,"SELECT * FROM ".$prefix."_barcodes WHERE typusage = 'eleve' ORDER BY bcmodele_id ASC");
		if(mysqli_num_rows($modeles)==1) { $modele = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT * FROM ".$prefix."_barcodes WHERE nom = 'default' AND typusage = 'eleve'")); }
		else { $modele = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT * FROM ".$prefix."_barcodes WHERE bcmodele_id = '".$_POST["barcodes"]."'")); }
		// mémorisation du modèle
		if($modele['bcmodele_id']!='') {
			mysqli_query($bdd,"UPDATE ".$prefix."_parametres SET valeur = '".$modele['bcmodele_id']."' WHERE 
			param_nom = 'barcodes_default_modeleve'");
		}
		// récupération du nom et ville de l'établissement si besoin
		if($modele['textup']==2||$modele['textup']==3) {
			$etab = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT nom, ville FROM ".$prefix."_etab"));
			$etab_bc = $etab['nom'].' - '.$etab['ville'];
		}

		// périmètre élève
		// cas 1, tous ceux qui ont un code :
		if($_POST['elechoix']=='tous') {
			$ele_nom = array();
			$ele_prenom = array();
			$ele_div = array();
			$ele_cod = array();
			$eleves = mysqli_query($bdd,"SELECT * FROM ".$prefix."_eleves WHERE code != '' ORDER BY division ASC, nom ASC, prenom ASC");
			$eleves_nb = mysqli_num_rows($eleves);
			foreach($eleves as $eleve_data) {
				array_push($ele_nom, $eleve_data['nom']);
				array_push($ele_prenom, $eleve_data['prenom']);
				array_push($ele_div, $eleve_data['division']);
				array_push($ele_cod, $eleve_data['code']);
			}
		}
		// cas 2, une ou plusieurs divisions
		else if($_POST['elechoix']=='divs') { 
			$ele_nom = array();
			$ele_prenom = array();
			$ele_div = array();
			$ele_cod = array();
			$division = $_POST['division'];
			$eleves_nb = 0;
			foreach($division as $regdiv) {
				$eleves = mysqli_query($bdd,"SELECT * FROM ".$prefix."_eleves WHERE code != '' AND division = '".$regdiv."' ORDER BY nom ASC, prenom ASC");
				$eleves_nb += mysqli_num_rows($eleves);
				foreach($eleves as $eleve_data) {
					array_push($ele_nom, $eleve_data['nom']);
					array_push($ele_prenom, $eleve_data['prenom']);
					array_push($ele_div, $eleve_data['division']);
					array_push($ele_cod, $eleve_data['code']);
				}
				$groupele = mysqli_query($bdd,"SELECT groupele.groupe_id, groupele.eleves_id, eleves.nom, eleves.prenom, eleves.division, eleves.code
				FROM ".$prefix."_groupele groupele
				INNER JOIN ".$prefix."_eleves eleves
				ON groupele.eleves_id = eleves.eleves_id
				WHERE groupele.groupe_id = ".$regdiv."
				ORDER BY eleves.division ASC, eleves.nom ASC");
				$eleves_nb += mysqli_num_rows($groupele);
				foreach($groupele as $eleve_data) {
					array_push($ele_nom, $eleve_data['nom']);
					array_push($ele_prenom, $eleve_data['prenom']);
					array_push($ele_div, $eleve_data['division']);
					array_push($ele_cod, $eleve_data['code']);
				}
			}
		}
		// cas 3, élèves d'une classe
		else if($_POST['elechoix']=='inclas') {
			$ele_nom = array();
			$ele_prenom = array();
			$ele_div = array();
			$ele_cod = array();
			$array = array_keys($_POST);
			$eleves_nb = 0;
			foreach($array as $checked_id) {
				$eleve_id = $checked_id;
				if(is_int($eleve_id)) {
					$eleves = mysqli_query($bdd,"SELECT * FROM ".$prefix."_eleves WHERE code != '' AND eleves_id = '".$checked_id."'");
					$eleve_data = mysqli_fetch_assoc($eleves);
					$eleves_nb += mysqli_num_rows($eleves);
					array_push($ele_nom, $eleve_data['nom']);
					array_push($ele_prenom, $eleve_data['prenom']);
					array_push($ele_div, $eleve_data['division']);
					array_push($ele_cod, $eleve_data['code']);
				}
			}
		}
		// cas 4, élèves par id
		else if($_POST['elechoix']=='elev') { 
			$ele_nom = array();
			$ele_prenom = array();
			$ele_div = array();
			$ele_cod = array();
			$array = explode(",",$_POST['eleid']);
			$eleves_nb = 0;
			foreach($array as $checked_id) {
				$eleve_id = $checked_id;
				$eleves = mysqli_query($bdd,"SELECT * FROM ".$prefix."_eleves WHERE code != '' AND eleves_id = '".$checked_id."'");
				if(mysqli_num_rows($eleves)>0) {
					$eleve_data = mysqli_fetch_assoc($eleves);
					$eleves_nb += 1;
					array_push($ele_nom, $eleve_data['nom']);
					array_push($ele_prenom, $eleve_data['prenom']);
					array_push($ele_div, $eleve_data['division']);
					array_push($ele_cod, $eleve_data['code']);
				}
			}
		}
		// variables issues du modèle
		$margextd = $modele['margextd'];
		$margexth = $modele['margexth'];
		$margextg = $modele['margextg'];
		$td_nb = $modele['nbwidth'];
		$tr_perpage = $modele['nbheight'];
		$fontsize = $modele['fontsize'];

		// gestion d'une feuille incomplète
		$debut=$_POST['debut']; // le numéro correspond à la 1re étiquette imprimée
		if($debut<=($td_nb*$tr_perpage)) {
			if($modele['format']=='P') { $pageh = 297; } else { $pageh = 210; }
			if(intval(((($debut-1)/$td_nb)),0)>0) {
				$tr_space = intval(($debut-1)/$td_nb,0)+1;
				$margexth = $modele['margexth']+((($pageh-$modele['margexth']-$modele['margextb'])/$tr_perpage)*($tr_space-1));
			}
			if(($debut-1)%$td_nb>0) {
				$td_space = ($debut-1)%$td_nb;
			}
			else { $td_space = 0; }
		}
		
		// autres variables
		$tr_total_reel = ($eleves_nb + ($debut - 1)) / $td_nb; // Nombre total de lignes (avec décimale)
		$tr_total = intval($tr_total_reel); // Nombre total de lignes (entier absolu)
		$pages_total = intval($tr_total_reel / $tr_perpage); // Nombre total de pages (entier)
		// Utilisation de fmod pour le modulo avec des flottants
		$pages_modulo = fmod($tr_total_reel, $tr_perpage); // Lignes restantes après dernière page pleine

		if($modele['format']=='P') { $pagew = 210; } else { $pagew = 297; }
		$tdwidth = (($pagew-$modele['margextd']-$modele['margextg'])/$td_nb);

		// gestion d'un nombre d'étiquettes sur moins d'une ligne
		if(($eleves_nb+($debut-1))<$td_nb) {
			$margextd = (($pagew-$modele['margextd']-$modele['margextg'])/$td_nb)*($td_nb-($eleves_nb+($debut-1)));
			if(($debut-1)%$td_nb>0) {
				$debsp = ($debut-1)%$td_nb;
				$margextg = (($pagew-$modele['margextd']-$modele['margextg'])/$td_nb)*$debsp;
			}
		}

		// marges sur les pages 2 et suivantes
		$margins = 'margin-left = "'.$margextg.'mm" margin-right = "'.$margextd.'mm" margin-top = "'.$modele['margexth'].'mm" margin-bottom = "'.$modele['margextb'].'mm"';

		$k=0;
		$bctab = '';
		for($h=0;$h<$pages_total;$h++) {
			$bctab .= '<table>';
			if(!isset($tr_space)) { $tr_space=1; }
			if($h!=0) { $tr_space = 1; }
			for($i=$tr_space;$i<=$tr_perpage;$i++) {
				$bctab .= '<tr>';
				if($h==0&&$td_space>0&&$i==$tr_space) { 
					for($n=1;$n<=$td_space;$n++) {
						$bctab .= '<td style="width:'.($tdwidth+($modele['margextg']/$td_space)).'mm;"></td>';
					}
					$td_space = $td_space; 
				}
				else { $td_space = 0; }
				for($j=1;$j<=$td_nb-$td_space;$j++) {
					if($ele_nom[$k]!="") {
						$bctab .= '<td>';
						include('barcodes_td.php');
						$bctab .= '</td>';
					}
					else {
						$bctab .= '<td style="width:'.($tdwidth+($modele['margextd'])).'mm;"></td>';
					}
					$k++;
				}
				$bctab .= '</tr>';
			}
			if($i!=($tr_perpage+1)&&$h==$pages_total&&$td_modulo>0) {
				$bctab .= '<tr>';
				for($i=1;$i<=$td_nb;$i++) {
					$bctab .= '<td>';
					if($td_modulo>=$i) {
						include('barcodes_td.php');
					}
					$bctab .= '</td>';
					$k++;
				}
				$bdtab .= '</tr>';
			}
			$bctab .= '</table>';
			$break=0;
			if($h!=$pages_total) {
				$bctab .= '<pagebreak '.$margins.'>';
				$break=1;
			}
		}
		if($pages_modulo>0) {
			if($pages_total>1&&$break==0) {
				$bctab .= '<pagebreak '.$margins.'>';
			}
			$bctab .= '<table>';
			for($i=1;$i<=$pages_modulo;$i++) {
				$bctab .= '<tr>';
				for($j=1;$j<=$td_nb;$j++) {
					$bctab .= '<td>';
					include('barcodes_td.php');
					$bctab .= '</td>';
					$k++;
				}
				$bctab .= '</tr>';
			}
			if($td_modulo>0) {
				$bctab .= '<tr>';
				for($i=1;$i<=$td_nb;$i++) {
					$bctab .= '<td>';
					if($td_modulo>=$i) {
						include('barcodes_td.php');
					}
					$bctab .= '</td>';
					$k++;
				}
				$bctab .= '</tr>';
			}
			$bctab .= '</table>';
		}

		$html = '
		<html>
		<head>
		<style>
		body {font-family: sans-serif;
			font-size: '.$fontsize.'pt;
		}
		@page :first {
			margin-left : '.$margextg.'mm;
			margin-right : '.$margextd.'mm;
			margin-top : '.$margexth.'mm; 
			margin-bottom : '.$modele['margextb'].'mm;
		}
		td { 
			text-align:center; 
			padding: '.$modele['marginth'].'mm '.$modele['margintd'].'mm '.$modele['margintb'].'mm '.$modele['margintg'].'mm;
			width: '.$tdwidth.'mm;
		}
		.barcode {
			vertical-align: top;
			color: #000000;
		}
		.barcodecell {
			text-align: center;
			vertical-align: middle;
			padding: 0;
		}
		</style>
		</head>
		<body>
		'.$bctab.'
		</body>
		</html>
		';
		
		$path = (getenv('MPDF_ROOT')) ? getenv('MPDF_ROOT') : __DIR__;
		if(phpversion()>=8.0) {
			require_once '../mpdf8/autoload.php';
		}
		else {
			require_once '../mpdf/autoload.php';
		}
		$mpdf = new \Mpdf\Mpdf([
			'orientation' => ''.$modele['format'].'',
			/*'margin_left' => $modele['margextg'].'mm',
			'margin_right' => $margextd.'mm',
			'margin_top' => $modele['margexth'].'mm',
			'margin_bottom' => $modele['margextb'].'mm',*/
			'showBarcodeNumbers' => FALSE
		]);
		try {
			$mpdf->WriteHTML($html);
		} catch (\Mpdf\MpdfException $e) {
			die ($e->getMessage());
		}
		ob_end_clean();
		$mpdf->Output('eleves_barcodes.pdf', \Mpdf\Output\Destination::DOWNLOAD);
	}
}
else {
	include('../noaccess.php');
	echo '<a href="../../index.php">'.ACCUEIL.'</a>.</p>';
}