<?PHP

$getConfig = false;
if (file_exists('../config.php')) {
	require_once '../config.php';
	$getConfig = true;
} else if (file_exists('.\config.php')) {
	require_once '.\config.php';
	$getConfig = true;
}

function getPath($nbrRep): string
{
	$directory = new DirectoryIterator(dirname(__FILE__));
	// Display the path 
	$path = explode("\\", $directory->getPath());
	return $path[count($path) - 1 - $nbrRep];
}
function retireTags($texte): string
{
	if ($texte != '')
		return strip_tags($texte, "<span><u><sub><sup><strong><em><img><b><i>");
	else
		return '';
}
function ldapSearch($username, $lastname, $firstname)
{
	//Récupère les paramettre du site
	include_once("Parametre/" . getPath(1) . "/" . getPath(1) . ".php");
	$configFile = __DIR__ . '/../config.php';

	$ldap_enabled = defined('LDAP_ENABLED') ? LDAP_ENABLED : '';
	$ldap_host   = defined('LDAP_HOST')   ? LDAP_HOST   : '';
	$ldap_port   = defined('LDAP_PORT')   ? LDAP_PORT   : '';
	$bind_dn     = strtolower(defined('BIND_DN')   ? BIND_DN   : '');
	$bind_password     = defined('BIND_PASSWORD')   ? BIND_PASSWORD   : '';
	$base_dn     = defined('BASE_DN')   ? BASE_DN   : '';

	echo "nous sommes ici ldapSeach";
	exit;

	$filter = '';
	if (!empty($username)) {
		$user = $username;
		$filter .= "(cn=$user*)";
	} else
		$user = '';

	if (!empty($lastname)) {
		$lastname = $lastname;
		$filter .= "(sn=$lastname)";
	} else
		$lastname = '';

	if (!empty($firstname)) {
		$firstname = $firstname;
		$filter .= "(givenname=$firstname)";
	} else
		$firstname = '';

	if (!empty($filter)) {
		$filter = "(&$filter)";

		$ldap = ldap_connect($ldap_host, $ldap_port) or die("Could not connect to LDAP server.");;

		ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
		ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);

		$bind = @ldap_bind($ldap, $bind_dn, $bind_password);

		if ($bind) {
			$dn = $base_dn;

			$attr = array("cn", "sn", "givenname", "mail", "title", "employeeid", "telephonenumber", "initials", "useraccountcontrol");

			$sr = ldap_search($ldap, $dn, $filter, $attr) or die("Error in search query: " . ldap_error($ldap));
			$info = ldap_get_entries($ldap, $sr) or die("Could not get LDAP entries.");
		} else {
			echo 'Bind failed';
		}
	} else {
		$info = array();
	}


	return $info;
}

function getClientHostname()
{
	$hostname = strtoupper(gethostbyaddr($_SERVER['REMOTE_ADDR']));
	return $hostname;
}

function isValidDate2($date)
{
	return $date !== '0000-00-00' && DateTime::createFromFormat('Y-m-d', $date) !== false;
}

function isValidDate($date) {
	$format = 'Y-m-d';
    if (!is_string($date) || empty($date)) {
        return false;
    }
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) === $date;
}

function domainFromDN($dn)
{
	// Remove all spaces
	$dn = str_replace(' ', '', $dn);

	$parts = explode(',', $dn);
	$domainParts = [];

	foreach ($parts as $part) {
		if (stripos($part, 'DC=') === 0) {
			$domainParts[] = substr($part, 3);
		}
	}

	return implode('.', $domainParts);
}
function formuleBienvenue($nomEtablissement) {
    $nomEtablissement = trim($nomEtablissement);
    $premierMot = strtok($nomEtablissement, " ");
    $premiereLettre = mb_strtolower(mb_substr($premierMot, 0, 1));
    $voyelles = ['a', 'e', 'i', 'o', 'u', 'y', 'é', 'è', 'ê'];

    // Liste de mots courants féminins ou masculins
    $motsFeminins = ['école', 'université', 'académie', 'institution', 'faculté'];
    $motsMasculins = ['centre', 'institut', 'collège', 'lycée', 'complexe'];

    $premierMotMin = mb_strtolower($premierMot);

    if (in_array($premierMotMin, $motsFeminins)) {
        $genre = 'f';
    } elseif (in_array($premierMotMin, $motsMasculins)) {
        $genre = 'm';
    } else {
        $genre = null; // inconnu
    }

    if (in_array($premiereLettre, $voyelles)) {
        $article = "Bienvenue à l’";
    } else {
        if ($genre === 'f') {
            $article = "Bienvenue à la ";
        } elseif ($genre === 'm') {
            $article = "Bienvenue au ";
        } else {
            // Cas inconnu : par défaut on met "à l’" s’il commence par une voyelle, sinon "à"
            $article = "Bienvenue à ";
        }
    }

    return $article . $nomEtablissement;
}


