<?php

// Active les erreurs PHP.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Se connecte à la BDD (identifiants cachés)
// Charge les paramètres de tnt dans $tntconfig
include_once 'dbinit.php';

if(isset($_GET["salle"])) {

	$idSalle = $_GET["salle"];

	$aliaz = array();

	$stmt = $conn->prepare("SELECT nom FROM salleAlias WHERE salleID=?");
	$stmt->execute([$idSalle]);
	$resA = $stmt->fetchAll();

	for($i=0;$i<count($resA);$i++)
		$aliaz[$i] = $resA[$i]['nom'];

	$fichiers = array();

	$stmt = $conn->prepare("SELECT fichier FROM salleFichier WHERE salleID=?");
	$stmt->execute([$idSalle]);
	$resF = $stmt->fetchAll();

	for($i=0;$i<count($resF);$i++)
		$fichiers[$i] = $resF[$i]['fichier'];

	$locataires = array();

	$stmt = $conn->prepare("SELECT personne FROM locataires WHERE salleID=?");
	$stmt->execute([$idSalle]);
	$resP = $stmt->fetchAll();

	for($i=0;$i<count($resP);$i++)
		$locataires[$i] = $resP[$i]['personne'];


	$stmt = $conn->prepare("SELECT id, description FROM salles WHERE id=?");
	$stmt->execute([$idSalle]);
	$resS = $stmt->fetchAll();


	if(count($resS)==0){
		echo "404";
	}else {
		$out = array("id" => $resS[0]["id"], "description" => $resS[0]["description"], "aliaz" => $aliaz, "locataires" => $locataires, "fichiers" => $fichiers);
		echo (json_encode($out));
	}

} else if (isset($_GET["search"])) {
	$searchText = $_GET["search"];
	$rescount = isset($_GET["rescount"])?$_GET["rescount"]:7;
	
	include_once 'setupTntsearch.php';
	
	$tnt->selectIndex("salleSearch.index");
	$tnt->fuzziness = true;
	$tnt->fuzzy_prefix_length  = 2;
	$tnt->fuzzy_max_expansions = 50;
	$tnt->fuzzy_distance       = 2; //represents the Levenshtein distance;
	
	$res = $tnt->search($searchText,$rescount);
	
	$out = array();
	
	for($i=0; $i<count($res['ids']); $i++){
		$theid = $res['ids'][$i];
		$stmt = $conn->prepare("SELECT nom FROM salleAlias WHERE salleID=?");
		$stmt->execute([$theid]);
		$resS = $stmt->fetchAll();
		
		$nomz = array();
		for($j=0;$j<count($resS);$j++)
			$nomz[$j] = $resS[$j]['nom'];

		$out[$theid] = array('noms' => $nomz);
	}
	
	for($i=0; $i<count($res["ids"]); $i++){
		$theid = $res['ids'][$i];
		$stmt = $conn->prepare("SELECT personne FROM locataires WHERE salleID=?");
		$stmt->execute([$theid]);
		$resL = $stmt->fetchAll();
		
		$locatairez = array();
		for($j=0;$j<count($resL);$j++)
			$locatairez[$j] = $resL[$j]['personne'];
			
		$out[$theid]['locataires'] = $locatairez;
	}
	
	
	echo (json_encode($out));

} else {
	echo "Je ne connais pas cette commande ...";
}
