<?php
$theme_namespace = 'homegrade-theme__texte-fonctionnel';

/* -------------------------------------------
 	GET THEMATIQUE FAMILY (FOR COLOR SCHEME)
 ---------------------------------------------*/
function getThematiqueFamilySlug($thematique_slug)
{

	if (!$thematique_slug) {
		return null;
	}

	switch ($thematique_slug) {
		case "energie":
		case "urbanisme":
		case "stedenbouw":
			return "energies-urbanisme";

		case "acoustique":
		case "akoestiek":
		case "petites-coproprietes":
		case "coproprietes":
		case "mede-eigendommen":
			return "acoustique-coproprietes";

		case "isolation":
		case "isolatie":
		case "au-quotidien":
		case "dagelijks":
			return "isolation-quotidien";

		case "energies":
		case "urbanisme":
		case "stedenbouw":
			return "energies-urbanisme";

		case "patrimoine":
		case "erfgoed":
		case "sante-securite-salubrite":
		case "gezondheid-veiligheid-hygiene":
		case "aides-financieres":
		case "financiele-steun":
			return "patrimoine-sante-securite";

		case "gerer-ses-travaux":
		case "werkzaamheden-beheren":
		case "location-achat":
		case "verhuur-ankoop":
		case "duurzaamheid":
		case "durabilite":
			return "location-durabilite";
	}
}

/* -------------------------------------------
 	GETTING MAIN ROOT THEMATIQUE
 ---------------------------------------------*/
function getParentThematique($thematique)
{
	if (!$thematique) {
		return null;
	}

	if ($thematique->parent == 0) {
		return $thematique;
	} else {
		return get_term($thematique->parent, 'thematiques');
	}
}

// DOES THE SAME THING AS ABOVE BUT RENAMED
function getMainThematique($thematique)
{
	if (!$thematique) {
		return null;
	}

	if ($thematique->parent == 0) {
		return $thematique;
	} else {
		return get_term($thematique->parent, 'thematiques');
	}
}
// Retriev the main thematique for a spefic postID
function getPostMainThematique($post)
{
	$terms = get_the_terms($post, "thematiques");
	if (!$terms) return null;

	$mainThematique = getMainThematique(get_the_terms($post, "thematiques")[0]);
	if (!$mainThematique) return null;

	return $mainThematique;
}

// TO GET ARCHIVE RELATED PAGES BY TEMPLATE
function get_page_by_template($template = '')
{
	$args = array(
		'meta_key' => '_wp_page_template',
		'meta_value' => $template
	);
	return get_pages($args);
}

function show_post_type_label_name($post_type)
{

	switch ($post_type) {
		case 'questions':
			return __("Question", "homegrade-theme__texte-backoffice");

		case 'conseils':
			return __("Conseil", "homegrade-theme__texte-backoffice");

		case 'page':
			return __("Page", "homegrade-theme__texte-backoffice");

		case 'post':
			return __("News", "homegrade-theme__texte-backoffice");

		case 'jobs':
			return __("Offre d'emploi", "homegrade-theme__texte-backoffice");

		case 'brochures':
			return __("Brochures", "homegrade-theme__texte-backoffice");

		case 'fiches-infos':
			return __("Fiche info", "homegrade-theme__texte-backoffice");

		default:
			return null;
	}
}


/* ---------
SORT BY THEMATIQUE PRIORITY
-----------------*/

// Fonction de comparaison pour trier par 'thematique_priority' utilisé par la fonction supérieur
function compareThematiquePriority($postA, $postB)
{

	$priorityA = $postA->thematique_priority ?? 0;
	$priorityB = $postB->thematique_priority ?? 0;

	$thematiqueA = getPostMainThematique($postA);
	$thematiqueB = getPostMainThematique($postB);

	$DocumentA = get_field('brochure_pdf', $postA->ID);
	$DocumentB = get_field('brochure_pdf', $postB->ID);

	$titleA = $DocumentA['title'] ?? null;
	$titleB = $DocumentB['title'] ?? null;


	if ($priorityA == $priorityB && $thematiqueA->name != $thematiqueB->name) {
		return strcmp($thematiqueA->name, $thematiqueB->name);
	}
	if ($priorityA == $priorityB && $thematiqueA->name == $thematiqueB->name && $titleA && $titleB) {
		return strcmp($titleA, $titleB);
	}
	if ($priorityA < $priorityB) {
		return 1;
	}
	if ($priorityA > $priorityB) {
		return -1;
	}
}


function sort_posts_per_thematiques_priority($postsQuery)
{

	foreach ($postsQuery->posts as $key => $post) {
		$thematique = getPostMainThematique($post);
		$post->thematique_priority = get_field('thematique_order', $thematique) ?? 0;
	}


	// Tri du tableau en utilisant la fonction de comparaison
	usort($postsQuery->posts, 'compareThematiquePriority');
	return $postsQuery;
}



/* -------------------------------------------
 	Build The page chaptering index
 ---------------------------------------------*/

function build_page_chapter_index($blocks)
{
	$chapterBlockIndex  = [];
	foreach ($blocks as $key => $block) {

		if ($block['blockName'] == 'homegrade-content-blocks/content-heading'  && isset($block['attrs']['title']) && isset($block['attrs']['headingLevel']) && $block['attrs']['headingLevel'] == "h2") {
			array_push($chapterBlockIndex, [
				'block-type' =>  $block['blockName'],
				'anchor' => 	"#" . strip_tags($block['attrs']['idName']),
				'title' => strip_tags($block['attrs']['title']),
			]);
		}
		if ($block['blockName'] == 'homegrade-content-blocks/chapitrage-thematique') {
			foreach ($block['innerBlocks'] as $key => $innerBlock) {
				if (!$innerBlock['attrs']['chapterTitle']) continue;

				$cleanedTitle = strtolower(preg_replace("/[^a-zA-Z]/", "", $innerBlock['attrs']['chapterTitle']));

				array_push($chapterBlockIndex, [
					'block-type' =>  $block['blockName'],
					'anchor' => '#' . $cleanedTitle,
					'title' => $innerBlock['attrs']['chapterTitle'],
				]);
			}
		}
		if ($block['blockName'] == 'homegrade-content-blocks/post-content-container') {

			if (!$block || !$block['attrs'] || $block['attrs']['relatedPostId'] == 0) continue;
			$shortTitle = get_field('short_title', $block['attrs']['relatedPostId']);

			$anchor = $block['attrs'] && !empty($block['attrs']['anchor']) ? esc_html($block['attrs']['anchor']) : "post-content-container-" .  $block['attrs']['relatedPostId'];
			array_push($chapterBlockIndex, [
				'block-type' =>  $block['blockName'],
				'anchor' => 	"#" . $anchor,
				'title' => $shortTitle ? $shortTitle : get_the_title($block['attrs']['relatedPostId']),
			]);
		}
		if ($block['blockName'] == 'homegrade-content-blocks/questions-container') {
			if (!$block || !$block['attrs'] || $block['attrs']['relatedPostId'] == 0) continue;
			$shortTitle = get_field('short_title', $block['attrs']['relatedPostId']);

			$anchor = isset($block['attrs']['anchor']) ? esc_html($block['attrs']['anchor']) : "questions-container-" .  $block['attrs']['relatedPostId'];

			array_push($chapterBlockIndex, [
				'block-type' =>  $block['blockName'],
				'anchor' => '#' . $anchor,
				'title' => $shortTitle ? $shortTitle : get_the_title($block['attrs']['relatedPostId']),
			]);
		}
		if ($block['blockName'] == 'homegrade-content-blocks/vocabulaire-summary') {
			array_push($chapterBlockIndex, [
				'block-type' =>  $block['blockName'],
				'anchor' => "#vocabulaire-summary",
				'title' => __("Vocabulaire", "homegrade-theme__texte-fonctionnel") . " " . get_the_terms(get_the_ID(), "thematiques")[0]->name,
			]);
		}
		if ($block['blockName'] == 'homegrade-content-blocks/help-homegrade') {
			array_push($chapterBlockIndex, [
				'block-type' =>  $block['blockName'],
				'anchor' => "#homegrade-vous-aide",
				'title' => __("Homegrade vous aide", "homegrade-blocks__texte-fonctionnel"),
			]);
		}
		if ($block['blockName'] == 'homegrade-content-blocks/partners-other-services') {
			array_push($chapterBlockIndex, [
				'block-type' =>  $block['blockName'],
				'anchor' => "#partenaires-autres-services",
				'title' => __("Partenaires & autres services", "homegrade-blocks__texte-fonctionnel"),
			]);
		}
		if ($block['blockName'] == 'homegrade-content-blocks/plus-loin') {
			array_push($chapterBlockIndex, [
				'block-type' =>  $block['blockName'],
				'anchor' => "#aller-plus-loin",
				'title' => __("Publications et liens utiles", "homegrade-blocks__texte-fonctionnel"),
			]);
		}
	}
	return $chapterBlockIndex;
}

/* -------------------------------------------
	 GET ALL THEMATIQUES ORGANIZED BY PARENTS
 ---------------------------------------------*/
function getAllThematiquesTermsByParents()
{
	// Récupérer tous les termes de la taxonomie 'thematiques' avec une hiérarchie
	$ThematiquesTerms = get_terms([
		'taxonomy' => 'thematiques',
		'orderby' => 'name',
		'order' => 'ASC',
		'hide_empty' => true,
	]);

	$terms_by_parent = [];
	$child_terms = [];

	if ($ThematiquesTerms) {

		// Boucle pour organiser les termes en fonction de leurs parents
		foreach ($ThematiquesTerms as $term) {
			if ($term->parent == 0) {
				// Si c'est un parent, on le place dans le tableau des parents
				$terms_by_parent[$term->term_id] = ['term' => $term, 'children' => []];
			} else {
				$child_terms[$term->parent][] = $term;
			}
		}


		// Réunir les termes parents et leurs enfants
		foreach ($terms_by_parent as $parent_id => &$parent_data) {
			// Ajouter les enfants au parent
			if (isset($child_terms[$parent_id])) {
				$parent_data['children'] = $child_terms[$parent_id];
			}
		}
	}
	return $terms_by_parent;
}

/* -------------------------------------------
	 GET PARCOURS PREVIOUS/NEXT POSTS
 ---------------------------------------------*/

function get_parcours_previous_next_posts($post)
{

	$prev_post = get_previous_post() ?? null;
	$next_post = get_next_post() ?? null;
	$test_next = get_adjacent_post(false, '', false, 'thematiques');
	$test  = new WP_Query(array('orderby' => 'menu_order', 'order' => 'ASC'));

	return [
		'prev_post' => $prev_post,
		'next_post' => $next_post,
		'test' => $test_next
	];
}
