<?php



add_action('rest_api_init', function () {

	/* ----------------
		BUILDING ROUTES
 	-----------------*/

	// ################ NEWS ################

	// * BUILD MORE NEWS CARDS 
	register_rest_route('homegrade-datas/v1/build', '/news', array(
		'methods' => 'GET',
		'callback' => 'build_news_posts_cards',
		'permission_callback' => '__return_true',
	));

	// * BUILD ALL NEWS CARDS 
	// register_rest_route('homegrade-datas/v1/build', '/news/all', array(
	// 	'methods' => 'GET',
	// 	'callback' => 'build_news_posts_feed_all',
	// 	'permission_callback' => '__return_true',
	// ));

	// * BUILD NEWS CARDS BY NEWS TYPE
	// register_rest_route('homegrade-datas/v1/build', '/news/type/(?P<typeId>\d+)', array(
	// 	'methods' => 'GET',
	// 	'callback' => 'build_news_posts_feed_per_type_id',
	// 	'permission_callback' => '__return_true',
	// ));

	// ################ PUBLICATIONS ################

	// * BUILD BROCHURES ARCHIVE ROWS
	register_rest_route('homegrade-datas/v1/build', '/brochures-archive-rows', array(
		'methods' => 'GET',
		'callback' => 'build_brochure_archive_rows',
		'permission_callback' => '__return_true',
	));
	// * BUILD FICHE INFOS ARCHIVE ROWS
	register_rest_route('homegrade-datas/v1/build', '/fiche-info-archive-rows', array(
		'methods' => 'GET',
		'callback' => 'build_fiches_info_archive_rows',
		'permission_callback' => '__return_true',

	));
	//* BUILD WEBINAIRE ARCHIVE ROWS
	register_rest_route('homegrade-datas/v1/build', '/webinaire-archive-rows', array(
		'methods' => 'GET',
		'callback' => 'build_webinaires_archive_rows',
		'permission_callback' => '__return_true',

	));

	// ################ FAQ ################

	// * BUILD FAQ DETAILS ROWS
	register_rest_route('homegrade-datas/v1/build', '/faq-details-rows', array(
		'methods' => 'GET',
		'callback' => 'build_faq_details_rows',
		'permission_callback' => '__return_true',

	));
	// * BUILD ALL FAQ DETAILS ROWS
	register_rest_route('homegrade-datas/v1/build', '/faq-details-rows-all', array(
		'methods' => 'GET',
		'callback' => 'build_faq_details_rows_all_from_one_thematique',
		'permission_callback' => '__return_true',

	));
});


// ################ NEWS ################

function build_news_posts_cards($request)
{
	$currentLanguage = esc_html($request->get_param('current-page-language')) ?? 'fr';
	$previousActivePage = esc_html($request->get_param('active-page')) ?? 1;
	$activeTermID = esc_html($request->get_param('active-term-id'));
	$postsPerPage = esc_html($request->get_param('posts-per-page')) ?? 12;

	$activePage = is_numeric($previousActivePage) ?  $previousActivePage + 1 : 1;

	$taxQuery = $activeTermID && is_numeric($activeTermID) ? array(
		array(
			'taxonomy' => 'news_type',
			'field' => 'term_id',
			'terms' => $activeTermID
		)
	) : null;


	do_action('wpml_switch_language', $currentLanguage);

	$args = array(
		"status" => "publish",
		"post_type" => "post",
		"posts_per_page" => $postsPerPage,
		"paged" => $activePage,
		"tax_query" => $taxQuery
	);
	$newsPostsDatas = new WP_Query($args);

	ob_start();
	foreach ($newsPostsDatas->posts as $key => $post) {
		$post_thumbnail = get_the_post_thumbnail($post->ID, 'full', array('class' => 'card-news__thumbnail card-post__thumbnail')) ?? null;
		$news_type = get_the_terms($post->ID, "news_type") ?? null;
		$post_date = get_the_date('j.m.Y', $post->ID) ?? null;

		get_template_part(
			'template-components/cards/card-news',
			null,
			array(
				'card_variant' => 'activite',
				'post_ID' => $post->ID,
				'post_title' => get_the_title($post->ID),
				'post_thumbnail' => $post_thumbnail,
				'news_type' => $news_type,
				'post_date' => $post_date,
			)
		);
	}

	$html_template = ob_get_clean();

	$response_data = array(
		'html_template' => $html_template,
		'total_posts_found' => $newsPostsDatas->found_posts,
		'active_page' => $activePage,
		'max_num_pages' => $newsPostsDatas->max_num_pages,
	);


	$response = new WP_REST_Response($response_data);

	$response->set_status(200);

	return $response;
}




// ################ PUBLICATIONS ################

function build_brochure_archive_rows(WP_REST_Request $request)
{
	$thematiquesIds = $request->get_param('thematiques-ids');
	$thematiquesIdsArray = $thematiquesIds ? explode(',', $thematiquesIds) : array();
	$thematiquesIdsArray = array_filter($thematiquesIdsArray, 'is_numeric');

	// Conditionnal tax_query if thematiquesIds passed in request
	$tax_query = array();
	if (!empty($thematiquesIdsArray)) {
		$tax_query = array(
			array(
				'taxonomy' => 'thematiques',
				'field' => 'term_id',
				'terms' => $thematiquesIdsArray,
			)
		);
	}

	$currentLanguage = $request->get_param('current-page-language') ?? 'fr';
	do_action('wpml_switch_language', $currentLanguage);

	$args = array(
		'post_type' => 'brochures',
		'posts_per_page' => -1,
		'post_status' => 'publish',
		'order' => 'DESC',
		'orderby' => 'date',
		'meta_key'      => 'brochure_pdf',
		'meta_value' => false,
		'meta_compare' => '!=',
		'tax_query' => $tax_query,
	);
	$brochuresPosts = new WP_Query($args);
	$sortedBrochuresPosts = sort_posts_per_thematiques_priority($brochuresPosts);

	ob_start();
	get_template_part(
		'template-components/archives/brochure-rows',
		null,
		array(
			'brochuresPosts' => $sortedBrochuresPosts,
		)
	);
	$html_template = ob_get_clean();


	$response_data = array(
		// 'posts' => $brochuresPosts->posts,
		'html_template' => $html_template,
		'total_posts_found' => count($brochuresPosts->posts),
	);

	$response = new WP_REST_Response($response_data);
	$response->set_status(200);

	return $response;
}
function build_fiches_info_archive_rows(WP_REST_Request $request)
{
	$thematiquesIds = $request->get_param('thematiques-ids');
	$thematiquesIdsArray = $thematiquesIds ? explode(',', $thematiquesIds) : array();
	$thematiquesIdsArray = array_filter($thematiquesIdsArray, 'is_numeric');

	// Conditionnal tax_query if thematiquesIds passed in request
	$tax_query = array();
	if (!empty($thematiquesIdsArray)) {
		$tax_query = array(
			array(
				'taxonomy' => 'thematiques',
				'field' => 'term_id',
				'terms' => $thematiquesIdsArray,
			)
		);
	}

	$currentLanguage = $request->get_param('current-page-language') ?? 'fr';
	do_action('wpml_switch_language', $currentLanguage);

	$args = array(
		'post_type' => 'fiches-infos',
		'posts_per_page' => -1,
		'post_status' => 'publish',
		'order' => 'DESC',
		'orderby' => 'date',
		'meta_key'      => 'brochure_pdf',
		'meta_value' => '',
		'meta_compare' => '!=',
		'tax_query' => $tax_query,
	);
	$ficheInfoPosts = new WP_Query($args);
	$sortedficheInfoPosts = sort_posts_per_thematiques_priority($ficheInfoPosts);

	ob_start();
	get_template_part(
		'template-components/archives/fiche-info-rows',
		null,
		array(
			'fichesInfosPosts' => $sortedficheInfoPosts,
		)
	);
	$html_template = ob_get_clean();


	$response_data = array(
		'posts' => $ficheInfoPosts->posts,
		'html_template' => $html_template,
		'total_posts_found' => count($ficheInfoPosts->posts),
	);

	$response = new WP_REST_Response($response_data);
	$response->set_status(200);

	return $response;
}

function build_webinaires_archive_rows(WP_REST_Request $request)
{
	$thematiquesIds = $request->get_param('thematiques-ids');
	$thematiquesIdsArray = $thematiquesIds ? explode(',', $thematiquesIds) : array();
	$thematiquesIdsArray = array_filter($thematiquesIdsArray, 'is_numeric');

	// Conditionnal tax_query if thematiquesIds passed in request
	$tax_query = array();
	if (!empty($thematiquesIdsArray)) {
		$tax_query = array(
			array(
				'taxonomy' => 'thematiques',
				'field' => 'term_id',
				'terms' => $thematiquesIdsArray,
			)
		);
	}

	$currentLanguage = $request->get_param('current-page-language') ?? 'fr';
	do_action('wpml_switch_language', $currentLanguage);

	$args = array(
		'post_type' => 'videos-webinaires',
		'posts_per_page' => -1,
		'post_status' => 'publish',
		'order' => 'DESC',
		'meta_key' => 'video_publication_date',
		'orderby' => 'meta_value_num',
		'tax_query' => $tax_query,
	);
	$webinairesPosts = new WP_Query($args);

	ob_start();
	get_template_part(
		'template-components/archives/webinaire-rows',
		null,
		array(
			'videosWebinairesPosts' => $webinairesPosts,
		)
	);
	$html_template = ob_get_clean();

	$response_data = array(
		// 'posts' => $webinairesPosts->posts,
		'html_template' => $html_template,
		'total_posts_found' => count($webinairesPosts->posts),
	);

	$response = new WP_REST_Response($response_data);
	$response->set_status(200);

	return $response;
}


// ################ FAQ ################

function build_faq_details_rows(WP_REST_Request $request)
{
	$questionsIds = $request->get_param('questions-ids');
	$questionsIdsArray = explode(',', $questionsIds);
	$questionsIdsArray = array_map('intval', $questionsIdsArray);

	$currentLanguage = $request->get_param('current-page-language') ?? 'fr';


	do_action('wpml_switch_language', $currentLanguage);

	$args = array(
		'post_type' => 'questions',
		'posts_per_page' => -1,
		'post_status' => 'publish',
		'tax_query' => array(
			array(
				'taxonomy' => 'thematiques',
				'field' => 'term_id',
				'terms' => $questionsIdsArray
			)
		)
	);
	$faqPosts = new WP_Query($args);

	ob_start();

	get_template_part(
		'template-components/faq/faq-rows',
		null,
		array(
			'relatedTaxQuestions' => $faqPosts,
		)
	);

	$html_template = ob_get_clean();

	$response_data = array(
		'posts' => $faqPosts->posts,
		'html_template' => $html_template,
		'total_posts_found' => count($faqPosts->posts),
	);

	$response = new WP_REST_Response($response_data);
	$response->set_status(200);

	return $response;
}
function build_faq_details_rows_all_from_one_thematique(WP_REST_Request $request)
{
	$parentMainThematiqueId = $request->get_param('parent-thematique-id');

	$currentLanguage = $request->get_param('current-page-language') ?? 'fr';

	do_action('wpml_switch_language', $currentLanguage);

	$args = array(
		'post_type' => 'questions',
		'posts_per_page' => -1,
		'post_status' => 'publish',
		'tax_query' => array(
			array(
				'taxonomy' => 'thematiques',
				'field' => 'term_id',
				'terms' => $parentMainThematiqueId,
			)
		)
	);
	$faqPosts = new WP_Query($args);

	ob_start();

	get_template_part(
		'template-components/faq/faq-rows',
		null,
		array(
			'relatedTaxQuestions' => $faqPosts,
		)
	);

	$html_template = ob_get_clean();

	$response_data = array(
		'posts' => $faqPosts->posts,
		'html_template' => $html_template,
		'total_posts_found' => count($faqPosts->posts),
	);

	$response = new WP_REST_Response($response_data);
	$response->set_status(200);

	return $response;
}





	/* ---------------------------
		SHIPPING ROUTES
 ---------------------------*/
	// Handle exclusion parameters like http://homegrade.local/wp-json/homegrade-datas/v1/questions-thematiques/29?excluded_ids=1314,1305,1301
	// register_rest_route('homegrade-datas/v1', '/questions-thematiques/(?P<thematiqueId>\d+)', array(
	// 	'methods' => 'GET',
	// 	'callback' => 'get_questions_posts_per_thematique_id',
	// 	'permission_callback' => '__return_true',
	// 	'args' => array(
	// 		'excluded_ids' => array(
	// 			'sanitize_callback' => 'sanitize_text_field',
	// 		),
	// 	),
	// ));
	// // * SHIP ALL NEWS
	// register_rest_route('homegrade-datas/v1', '/news', array(
	// 	'methods' => 'GET',
	// 	'callback' => 'get_news',
	// 	'permission_callback' => '__return_true',

	// ));
	// // * SHIP NEWS BY TYPE
	// register_rest_route('homegrade-datas/v1', '/news/type/(?P<typeId>\d+)', array(
	// 	'methods' => 'GET',
	// 	'callback' => 'get_news_posts_per_type_id',
	// 	'permission_callback' => '__return_true',
	// ));

// function get_news($request)
// {
// 	$args = array(
// 		"status" => "publish",
// 		"post_type" => "questions",
// 		"posts_per_page" => -1,
// 	);
// 	$newsPosts = get_posts($args);
// 	$response = new WP_REST_Response($newsPosts);
// 	$response->set_status(200);

// 	return $response;
// }
// function get_news_posts_per_type_id($request)
// {

// 	$typeId = $request['typeId'];
// 	$args = array(
// 		"post_type" => "post",
// 		"posts_per_page" => -1,
// 		"tax_query" => array(
// 			array(
// 				'taxonomy' => 'news_type',
// 				'field' => 'term_id',
// 				'terms' => $typeId
// 			)
// 		)
// 	);
// 	$newsPostsDatas = get_posts($args);
// 	$response = new WP_REST_Response($newsPostsDatas);
// 	$response->set_status(200);

// 	return $response;
// }
// function get_questions_posts_per_thematique_id($request)
// {
// 	$excluded_ids = $request->get_param('excluded_ids');
// 	$excludedArray = explode(',', $excluded_ids);

// 	$thematiqueId = $request['thematiqueId'];
// 	$args = array(
// 		"post_type" => "questions",
// 		"posts_per_page" => -1,
// 		"post__not_in" => $excludedArray,
// 		'tax_query' => array(
// 			array(
// 				'taxonomy' => 'thematiques',
// 				'field' => 'term_id',
// 				'terms' => $thematiqueId
// 			)
// 		)
// 	);
// 	$postDatas = get_posts($args);
// 	$response = new WP_REST_Response($postDatas);
// 	$response->set_status(200);

// 	return $response;
// }