<?php
// Gestion des inscrits du créneau précédent
$precren_info = null;
if (
    substr($crpre_info['valeur'], 0, 1) > 0
    && $_SESSION['num'] != 1
    && in_array($droits, [2, 4, 6])
) {
	// Créneau actuel
	$stmt = $pdo->prepare("
	    SELECT *
	    FROM {$prefix}_horaires
	    WHERE num_creneau = :num
	");

	$stmt->execute([
	    ':num' => $_SESSION['num']
	]);

	$cren_info = $stmt->fetch();
		
	// Ordre affichage
	$stmt = $pdo->prepare("
	    SELECT valeur
	    FROM {$prefix}_parametres
	    WHERE param_nom = :param
	");

	$stmt->execute([
	    ':param' => 'freq_ordreaff'
	]);

	$ordreaff_info = $stmt->fetch();

	$ordre = "ORDER BY eleves.nom ASC";

	switch ($ordreaff_info['valeur']) {

	    case 'div':
	        $ordre = "ORDER BY eleves.division ASC, eleves.nom ASC, eleves.prenom ASC";
	        break;

	    case 'nom':
	        $ordre = "ORDER BY eleves.nom ASC, eleves.prenom ASC";
	        break;

	    case 'hor':
	        $ordre = "ORDER BY freq.h_inscription DESC";
	        break;

	    case 'act':
	        $ordre = "ORDER BY freq.code_activ ASC";
	        break;

	    case 'esp':
	        $ordre = "ORDER BY espaces.espace_nom ASC, eleves.division ASC, eleves.nom ASC, eleves.prenom ASC";
	        break;
	}
	// Créneau précédent
	$prenum = $_SESSION['num'] - 1;

	$stmt = $pdo->prepare("
	    SELECT *
	    FROM {$prefix}_horaires
	    WHERE num_creneau = :num
	");

	$stmt->execute([
	    ':num' => $prenum
	]);

	$precren_info = $stmt->fetch();
}
if ($freq_gestion_jourscren['valeur'] == 0) {
    while (true) {
        if (!$precren_info || !isset($precren_info['hor_freq'])) {
            break;
        }
        if (substr($precren_info['hor_freq'], 0, 3) !== '000') {
            break;
        }
        $prenum--;
        $stmt = $pdo->prepare("
            SELECT *
            FROM {$prefix}_horaires
            WHERE num_creneau = :num
        ");
        $stmt->execute([
            ':num' => $prenum
        ]);
        $precren_info = $stmt->fetch(PDO::FETCH_ASSOC);
    }
} else {
    $jour = date('D');
    while (true) {
        if (!$precren_info || !isset($precren_info['hor_freq'])) {
            break;
        }
        $position = strpos($precren_info['hor_freq'], $jour);
        if ($position === false) {
            break;
        }
        $valeurJour = substr(
            $precren_info['hor_freq'],
            $position + strlen($jour),
            3
        );
        if ($valeurJour !== '000') {
            break;
        }
        $prenum--;
        $stmt = $pdo->prepare("
            SELECT *
            FROM {$prefix}_horaires
            WHERE num_creneau = :num
        ");
        $stmt->execute([
            ':num' => $prenum
        ]);
        $precren_info = $stmt->fetch(PDO::FETCH_ASSOC);
    }
}
	if (isset($prenum) && $prenum < $_SESSION['num']) {
		$dday = date("Y-m-d");
		$ccren = $dday.$_SESSION['ccren'];
		
		$sql = " SELECT freq.eleves_id, freq.date_freq, freq.code_activ, freq.hor_name, freq.h_inscription, espaces.espace_nom, espaces.espace_id, eleves.nom, SUBSTR(eleves.nom,1,10) AS nomsub, eleves.prenom, eleves.division, eleves.naissance, activ.nom_activ, activ.activ_id FROM {$prefix}_freq freq INNER JOIN {$prefix}_eleves eleves ON freq.eleves_id = eleves.eleves_id LEFT JOIN {$prefix}_freqactiv activ ON activ.code_activ = freq.code_activ LEFT JOIN {$prefix}_espaces espaces ON espaces.espace_id = freq.espace_id WHERE freq.date_freq = :date_freq AND freq.hor_name = :hor_name $ordre "; 
		$stmt = $pdo->prepare($sql); 
		$stmt->execute([ ':date_freq' => $dday, ':hor_name' => $precren_info['hor_name'] ?? '' ]); 
		$preins = $stmt->fetchAll(); 
		$nb_preins = count($preins); 
		if ($nb_preins > 0) {
			echo '<div name="preins" class="preinsgrappes">'; 
			echo '<h3 style="color:black;text-decoration:none;" onmouseover="this.style.textDecoration=\'underline\';" onmouseout="this.style.textDecoration=\'none\';" onmousedown="toggleDiv(\'divcrenp\');" >'; 
			echo '<i class="fas fa-angle-double-right"></i> '; 
			echo FREQ_INF1 . ' ('; echo htmlspecialchars($precren_info['hor_name'], ENT_QUOTES, 'UTF-8'); 
			echo ' - ';
			$stmtHoraire = $pdo->prepare(" SELECT * FROM {$prefix}_horaires WHERE hor_name = :hor_name "); 
			$stmtHoraire->execute([ ':hor_name' => $precren_info['hor_name'] ]); 
			$listeh = $stmtHoraire->fetch(); 
			$deb_cren = substr($precren_info['hor_name'], 0, 1); 
			include('include/hor_boucle.php'); 
			echo ')</h3>';

			$display = 'none'; 
			if (substr($crpre_info['valeur'], 0, 1) == 1) { $display = 'block'; } 
			echo '<div id="divcrenp" style="display:' . $display . ';">'; 
			echo '<table name="form">';
			/* | Préparation requête vérification ------------------------ */ 
			$stmtVerif = $pdo->prepare(" SELECT freq.eleves_id FROM {$prefix}_freq freq INNER JOIN {$prefix}_eleves eleves ON freq.eleves_id = eleves.eleves_id WHERE freq.date_freq = :date_freq AND freq.hor_name = :hor_name AND eleves.division = :division AND eleves.nom = :nom AND eleves.prenom = :prenom "); 
			/* |-----
			-- | Activité par défaut --------- */ 
			$stmtActivDefault = $pdo->query(" SELECT * FROM {$prefix}_freqactiv WHERE default_activ = 1 LIMIT 1 "); 
			$nom_activd = $stmtActivDefault->fetch(); 
			/* |-------------------| Liste activités --------- */ 
			$stmtActivites = $pdo->query(" SELECT code_activ, nom_activ FROM {$prefix}_freqactiv WHERE activ_activ = 1 AND code_activ <> 'ZERO' ORDER BY nom_activ ASC "); 
			$listeActivites = $stmtActivites->fetchAll(); 
			/* |------------------------- | Liste espaces ---- */ 
			$listeEspaces = []; if ($espopt['valeur'] == 1) { $stmtEspaces = $pdo->query(" SELECT espace_id, espace_nom FROM {$prefix}_espaces ORDER BY espace_nom ASC "); 
			$listeEspaces = $stmtEspaces->fetchAll(); } 
			/* |------------------------ | Boucle affichage ------ */ 
			foreach ($preins as $validpreins) { 
				/* |----------------- | Vérification déjà inscrit ------- */ 
				$stmtVerif->execute([ ':date_freq' => $dday, ':hor_name' => $_SESSION['ccren'], ':division' => $validpreins['division'], ':nom' => $validpreins['nom'], ':prenom' => $validpreins['prenom'] ]); 
				$preins_verif_nb = $stmtVerif->rowCount(); 
				/* |------------------------------- | Début ligne ----- */ 
				echo '<tr id="prec' . (int)$validpreins['eleves_id'] . '">'; 
				echo '<td>'; 
				echo htmlspecialchars($validpreins['division']); 
				echo ' - '; 
				if (mb_strlen($validpreins['nom']) > 10) { echo htmlspecialchars( mb_substr($validpreins['nom'], 0, 10), ENT_QUOTES, 'UTF-8' ); echo '... '; } else { echo htmlspecialchars( $validpreins['nom'], ENT_QUOTES, 'UTF-8' ); echo ' '; } echo htmlspecialchars( mb_substr($validpreins['prenom'], 0, 1), ENT_QUOTES, 'UTF-8' ); echo '.'; echo '</td>'; 
				/* |------------------------- | Activité --- */ 
				echo '<td>'; 
				echo htmlspecialchars( $validpreins['nom_activ'] ?? '', ENT_QUOTES, 'UTF-8' ); 
				echo '</td>';	

			/*foreach($preins as $validpreins) {
				// effacement s'ils sont inscrits dans le nouveau créneau
				$preins_verif_select = "SELECT freq.eleves_id, freq.date_freq, freq.hor_name, freq.code_activ, freq.cas, freq.h_inscription, espaces.espace_nom, espaces.espace_id, eleves.nom, eleves.prenom, eleves.division, eleves.naissance  
				FROM ".$prefix."_freq freq 
				INNER JOIN ".$prefix."_eleves eleves
				ON freq.eleves_id = eleves.eleves_id
				LEFT JOIN ".$prefix."_espaces espaces
				ON espaces.espace_id = freq.espace_id
				WHERE freq.date_freq = '".$dday."' AND freq.hor_name = '".$_SESSION['ccren']."' AND eleves.division = '".$validpreins['division']."' AND eleves.nom = '".addslashes($validpreins['nom'])."' AND eleves.prenom = '".addslashes($validpreins['prenom'])."'";
				$preins_verif = mysqli_query($bdd,$preins_verif_select);
				$preins_verif_nb = mysqli_num_rows($preins_verif);
				// formulaire
				echo '<tr id="prec'.$validpreins['eleves_id'].'"><td>'.$validpreins['division'].' - ';
				if(strlen($validpreins['nom'])>10) {
					echo mb_ereg_replace("[?]","",mb_convert_encoding($validpreins['nomsub'],"utf-8")).'... ';
				} else { echo $validpreins['nom'].' '; }
				echo mb_substr($validpreins['prenom'],0,1).'.</td>
				<td>'.$validpreins['nom_activ'].'</td>*/
				
				$preins_nb = 1;
				
				echo '<td>'; $displayStyle = ''; 
				/* |----------------| Gestion hor_freq ----------- */ 
				if ($freq_gestion_jourscren['valeur'] == 0) { $horFreq = substr($cren_info['hor_freq'], 0, 3); } else { $jour = date('D'); $position = strpos($cren_info['hor_freq'], $jour); 
				if ($position !== false) { $horFreq = substr( $cren_info['hor_freq'], $position + strlen($jour), 3 ); } else { $horFreq = '000'; } } 
				/* |------------------- | Affichage ou non ------------- */ 
				if ($preins_verif_nb > 0 || $horFreq === '000') { $displayStyle = ' style="display:none;" '; } echo '<div id="noins' . (int)$validpreins['eleves_id'] . '"' . $displayStyle . '>'; 
				/* |---------- | Activité par défaut ------- */ 
				$stmtActivDefault = $pdo->query(" SELECT * FROM {$prefix}_freqactiv WHERE default_activ = 1 LIMIT 1 "); 
				$nom_activd = $stmtActivDefault->fetch(); 
				/* |------------------------ | Liste activités ---------- */ 
				$stmtListeActiv = $pdo->query(" SELECT code_activ, nom_activ FROM {$prefix}_freqactiv WHERE activ_activ = 1 AND code_activ <> 'ZERO' ORDER BY nom_activ ASC "); 
				$listeActivites = $stmtListeActiv->fetchAll(); 
				/* |----------------------------- | Select activités ------- */ 
				echo '<div class="box">'; 
				echo '<select name="selectactiv" id="selectactiv' . (int)$validpreins['eleves_id'] . '" >'; 
				echo '<option value="ZERO"></option>'; 
				foreach ($listeActivites as $liste) { $selected = ''; if ( isset($_SESSION['code_activ']) && $verrtest['valeur'] == 0 ) { if ($_SESSION['code_activ'] == $liste['code_activ']) { $selected = ' selected'; } } else { if ( isset($nom_activd['code_activ']) && $nom_activd['code_activ'] == $liste['code_activ'] ) { $selected = ' selected'; } } echo '<option value="' . htmlspecialchars($liste['code_activ'], ENT_QUOTES, 'UTF-8') . '"' . $selected . '>'; echo htmlspecialchars( $liste['nom_activ'], ENT_QUOTES, 'UTF-8' ); echo '</option>'; } 
				echo '</select>'; 
				echo '</div>';
				if($espopt['valeur']==1) {
					$stmtEspaces = $pdo->query(" SELECT espace_id, espace_nom FROM {$prefix}_espaces ORDER BY espace_nom ASC "); 
					$listeEspaces = $stmtEspaces->fetchAll();
					echo '<div class="box">'; 
					echo '<select id="espace' . (int)$validpreins['eleves_id'] . '" name="espace" >'; 
					echo '<option value="0">'; 
					echo htmlspecialchars( $esp0['valeur'], ENT_QUOTES, 'UTF-8' ); 
					echo '</option>'; 
					foreach ($listeEspaces as $liste) { 
						$selected = ''; if ( (int)$validpreins['espace_id'] === (int)$liste['espace_id'] ) { $selected = ' selected'; } 
						echo '<option value="' . (int)$liste['espace_id'] . '"' . $selected . '>'; 
						echo htmlspecialchars( $liste['espace_nom'], ENT_QUOTES, 'UTF-8' ); 
						echo '</option>'; 
					} 
					echo '</select>'; 
					echo '</div>'; 
				}
				//gestion du seuil
				
				if ($espopt['valeur'] == 0) { 
					$stmt = $pdo->prepare(" SELECT freq.eleves_id, freq.date_freq, freq.hor_name, freq.code_activ, freq.cas, freq.h_inscription, eleves.nom, eleves.prenom, eleves.division, eleves.naissance FROM {$prefix}_freq freq INNER JOIN {$prefix}_eleves eleves ON freq.eleves_id = eleves.eleves_id WHERE freq.date_freq = :date AND freq.hor_name = :hor_name AND freq.cas NOT IN ('sor', 'exc') ORDER BY eleves.division ASC, eleves.nom DESC, eleves.prenom ASC "); 
					$stmt->execute([ ':date' => $dday, ':hor_name' => $_SESSION['ccren'] ]); 
					$inscrits = $stmt->fetchAll(); 
					$nb_inscrits = count($inscrits); } 
					/* |-------- | Paramètres (UNE seule fois idéalement, pas dans la boucle)- */ 
					$stmt = $pdo->prepare(" SELECT param_nom, valeur FROM {$prefix}_parametres WHERE param_nom IN ('freq_seuilnbi', 'freq_seuilreaci') "); 
					$stmt->execute(); 
					$params = $stmt->fetchAll(PDO::FETCH_KEY_PAIR); 
					$sin_info = [ 'valeur' => $params['freq_seuilnbi'] ?? 0 ]; 
					$sir_info = [ 'valeur' => $params['freq_seuilreaci'] ?? '' ]; 
					/* |----------------- | Affichage bouton / bloc interdit --- */ 
					$showButton = ( $espopt['valeur'] == 1 || $sin_info['valeur'] == 0 || $nb_inscrits < $sin_info['valeur'] ); 
					if ($showButton) { 
						echo '&nbsp; &nbsp; <input class="boutontab"
					        type="button"
					        value="'.FREQ_BUTTON1.'"
					        onclick="okpre('.(int)$validpreins['eleves_id'].')"
					        name="okpre'.(int)$validpreins['eleves_id'].'">';
					} 
					elseif ($sir_info['valeur'] === 'stopp') { 
						echo '&nbsp; &nbsp; ' . FREQ_RESA2; 
					} 
					echo '</div></td>';

				$today = date('Y-m-d');
				/* paramètres seuil */
				$stmt = $pdo->prepare("
				    SELECT param_nom, valeur
				    FROM {$prefix}_parametres
				    WHERE param_nom IN ('freq_seuilnbi', 'freq_seuilreaci')
				");

				$stmt->execute();
				$params = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

				$sin_val = $params['freq_seuilnbi'] ?? 0;
				$sir_val = $params['freq_seuilreaci'] ?? '';
				echo '<td class="noborder">';
				// Retards
				$stmt = $pdo->prepare("
				    SELECT *
				    FROM {$prefix}_retards
				    WHERE eleves_id = :id
				    AND retour_date < :today
				    ORDER BY retour_date ASC
				");

				$stmt->execute([
				    ':id' => $validpreins['eleves_id'],
				    ':today' => $today
				]);

				$retards = $stmt->fetchAll();

				$ret = '';

				if ($retards) {

				    $ret = '<span style="font-size:1.5em;color:#D90606;">
				            <i class="fa-solid fa-stopwatch" title="';

				    $i = 1;

				    foreach ($retards as $r) {

				        if (count($retards) > 1) {
				            $ret .= $i . '. ';
				        }

				        if (!empty($r['titre'])) {
				            $ret .= $r['titre'] . '. ';
				        }

				        if ($r['retour_date'] !== '0000-00-00') {
				            $date = date('d/m/Y', strtotime($r['retour_date']));
				            $ret .= FREQ_GEST1 . ' ' . $date . '. ';
				        }

				        if ($r['niv_alerte'] != 0) {

				            $ret .= FREQ_GEST2 . ' ';

				            if ($r['niv_alerte'] == 1) $ret .= FREQ_GEST3;
				            elseif ($r['niv_alerte'] == 2) $ret .= FREQ_GEST4;
				            elseif ($r['niv_alerte'] == 3) $ret .= FREQ_GEST5;

				            $ret .= '. ';
				        }

				        $i++;
				    }

				    $ret .= '"></i></span>';

				    echo $ret;
				}

				echo '</td>';

				/*
				|--------------------------------------------------------------------------
				| EXCLUSIONS
				|--------------------------------------------------------------------------
				*/

				echo '<td class="noborder" name="noprint">';

				$stmt = $pdo->prepare("
				    SELECT exclusions.*, causes.*
				    FROM {$prefix}_exclusions exclusions
				    LEFT JOIN {$prefix}_exclucauses causes
				        ON exclusions.exclucause_id = causes.exclucause_id
				    WHERE eleves_id = :id
				    AND (date_info >= :today OR date_fin >= :today)
				");

				$stmt->execute([
				    ':id' => $validpreins['eleves_id'],
				    ':today' => $today
				]);

				$exclusion = $stmt->fetchAll();

				if ($exclusion) {

				    $e = $exclusion[0];

				    $title =
				        FREQT2 . ' ' . LE2 . ' ' .
				        substr($e['date_exclusion'], 8, 2) . '/' .
				        substr($e['date_exclusion'], 5, 2) . '/' .
				        substr($e['date_exclusion'], 0, 4) .
				        ' au ' .
				        substr($e['date_fin'], 8, 2) . '/' .
				        substr($e['date_fin'], 5, 2) . '/' .
				        substr($e['date_fin'], 0, 4);

				    echo '<span style="font-size:1.5em;color:#D90606;">
				            <i class="fa-solid fa-ban" title="' . htmlspecialchars($title, ENT_QUOTES, 'UTF-8') . '"></i>
				          </span>';
				}

				echo '</td>';

				/*
				|--------------------------------------------------------------------------
				| LIMITES
				|--------------------------------------------------------------------------
				*/

				echo '<td class="noborder" name="noprint">';

				$stmt = $pdo->prepare("
				    SELECT limits.*, txt.*
				    FROM {$prefix}_limits limits
				    LEFT JOIN {$prefix}_limitstxt txt
				        ON limits.limittxt_id = txt.limittxt_id
				    WHERE eleves_id = :id
				    AND date_fin >= :today
				");

				$stmt->execute([
				    ':id' => $validpreins['eleves_id'],
				    ':today' => $today
				]);

				$limits = $stmt->fetchAll();

				if ($limits) {

				    $limtxt = '<span style="font-size:1.5em;color:#D90606;">
				              <i class="fa-solid fa-hand" title="';

				    $i = 1;

				    foreach ($limits as $l) {

				        if (count($limits) > 1 && $i > 1) {
				            $limtxt .= ' ';
				        }

				        if (count($limits) > 1) {
				            $limtxt .= $i . '. ';
				        }

				        $limtxt .= $l['limits_txt'] . ' ' . FROM3 . ' ' .
				            substr($l['date_debut'], 8, 2) . '/' .
				            substr($l['date_debut'], 5, 2) . '/' .
				            substr($l['date_debut'], 0, 4);

				        if ($l['date_fin'] >= $today) {
				            $limtxt .= ' ' . TO3 . ' ' .
				                substr($l['date_fin'], 8, 2) . '/' .
				                substr($l['date_fin'], 5, 2) . '/' .
				                substr($l['date_fin'], 0, 4) . '.';
				        }

				        $i++;
				    }

				    $limtxt .= '"></i></span>';

				    echo $limtxt;
				}

				echo '</td>';

				/*
				|--------------------------------------------------------------------------
				| ANNIVERSAIRE
				|--------------------------------------------------------------------------
				*/

				echo '<td class="noborder" name="noprint">';

				$birtxt = '';

				if (
				    $birthday['valeur'] == 1 &&
				    substr($validpreins['naissance'], 5, 5) == date('m-d')
				) {
				    $age = Age($validpreins['naissance']);

				    $birtxt = '<span style="font-size:1.5em;color:#D90606;">
				                <i class="fa-solid fa-cake-candles" title="' .
				                $age . ' ' . YEARS2 .
				                '"></i></span>';

				    echo $birtxt;
				}

				echo '</td>';
				$ret    = $ret ?? '';
				$exctxt = $exctxt ?? '';
				$limtxt = $limtxt ?? '';
				$birtxt = $birtxt ?? '';

				$to1 = $ret . ' ' . $exctxt . ' ' . $limtxt . ' ' . $birtxt;

				/*
				|--------------------------------------------------------------------------
				| Encodage propre (version moderne)
				|--------------------------------------------------------------------------
				*/

				$toins = htmlspecialchars($to1, ENT_QUOTES, 'UTF-8');
				echo '<input type="hidden" name="infos'.$validpreins['eleves_id'].'" id="infos'.$validpreins['eleves_id'].'" value="'.$toins.'" /></td></tr>';
				$label = $validpreins['division'].' - '.$validpreins['nom'].' '.$validpreins['prenom'];

				echo '<script>';
				echo 'window.eleveData = window.eleveData || {};';
				echo 'window.eleveData['.(int)$validpreins['eleves_id'].'] = '.
				json_encode([
				    "label" => $label,
				    "showActiv" => ($droits != 3 || $check_consultactiv_opt['valeur'] != 0),
				    "showEspace" => ($espopt['valeur'] == 1)
				], JSON_UNESCAPED_UNICODE);
				echo ';</script>';
				
			}
			echo '</table></div>';
			if (!isset($preins_nb)) {
				echo FREQ_INF2;
			}
			else if (isset($preins_nb)&&$preins_nb!=1) {
				echo FREQ_INF2;
			}
			echo '</div>';
		}
	}	echo '
	<script>
function okpre(eleve_id, param = "inspre") {

    const data = window.eleveData?.[eleve_id];
    if (!data) {
        console.error("eleveData missing for", eleve_id);
        return;
    }

    const sel = document.getElementById("selectactiv" + eleve_id);
    const selectactiv = sel ? sel.value : "";
    const selectactivtxt = sel ? sel.options[sel.selectedIndex].text : "";

    const espaceEl = document.getElementById("espace" + eleve_id);

    let espace = "";
    let espacetext = "";
    let espid = null;

    if (espaceEl) {
        espace = espaceEl.value;
        espacetext = espaceEl.options[espaceEl.selectedIndex].text;
        espid = "nb_tresp" + espace;
    }

    document.getElementById("noins" + eleve_id)?.style && 
        (document.getElementById("noins" + eleve_id).style.display = "none");

    const nb = document.getElementById("inscrits_nb");
    if (nb) nb.textContent = parseInt(nb.textContent || 0) + 1;

    if (espid) {
        const rne = document.getElementById(espid);
        if (rne) rne.textContent = parseInt(rne.textContent || 0) + 1;
    }

    const table = document.getElementById("listeinscrits");
    if (!table) return;

    const tr = document.createElement("tr");

    let html = `<td>${data.label}</td>`;

    if (data.showActiv) {
        html += `<td>${selectactivtxt}</td>`;
    }

    if (data.showEspace) {
        html += `<td>${espacetext}</td>`;
    }

    tr.innerHTML = html;
    table.appendChild(tr);

    $.ajax({
        type: "POST",
        url: "js/idl/freq_ind_syn.php",
        data: { param, eleve_id, selectactiv, espace },
        success: function(data) {
            $("#zone").html(data);
            $("#eleves").focus();
        },
        error: function(xhr) {
            console.error("AJAX error", xhr.responseText);
        }
    });
}
</script>';
?>