<?php
function acf_set_language()
{
	return apply_filters('wpml_current_language', null);
}

add_action('rest_api_init', function () {


	register_rest_route('lhoist-datas/screen', '/play/latest', array(
		'methods' => 'GET',
		'callback' => 'get_latest_game_datas',
		'permission_callback' => '__return_true',
	));
	register_rest_route('lhoist-datas/screen', '/play/all', array(
		'methods' => 'GET',
		'callback' => 'get_all_games_datas',
		'permission_callback' => '__return_true',
	));
	register_rest_route('lhoist-datas/screen', '/play/(?P<id>\d+)', array(
		'methods' => 'GET',
		'callback' => 'get_game_datas',
		'permission_callback' => '__return_true',
	));

	register_rest_route('lhoist-datas/page', '/(?P<id>\d+)', array(
		'methods' => 'GET',
		'callback' => 'get_interface_page_screen',
		'permission_callback' => '__return_true',
	));

	register_rest_route('lhoist-datas/statistics', '/post', array(
		'methods' => 'POST',
		'callback' => 'lhoist_post_game_datas_statistics',
		'permission_callback' => 'lhoist_datas_permission_callback',

	));
	register_rest_route('lhoist-datas/rating', '/post', array(
		'methods' => 'POST',
		'callback' => 'lhoist_post_rating',
		'permission_callback' => 'lhoist_datas_permission_callback',

	));
});

function lhoist_datas_permission_callback(
	WP_REST_Request $request
) {
	$origin = $request->get_header('origin');
	$referer = $request->get_header('referer');

	// $isLocalHost = $origin === 'http://localhost:3000' && $referer === 'http://localhost:3000/';
	// $isVercelApp = $origin === 'https://lhoist-stay-safe.vercel.app' && $referer === 'https://lhoist-stay-safe.vercel.app/';
	$isFrontEndApp = $origin === 'https://stay-safe-lhoist.com' && $referer === 'https://stay-safe-lhoist.com/';


	if ($isFrontEndApp) {
		return true;
	}
	return false;
	exit;
}

// ################ GET GAME DATAS ################

function get_latest_game_datas($request)
{
	// $language = sanitize_text_field($request['language']);
	$currentLanguage = strtolower($request->get_param('current-language')) ?? 'fr';
	if ($currentLanguage === "my") {
		$currentLanguage = "ms";
	}
	if ($currentLanguage === "pt") {
		$currentLanguage = "pt-pt";
	}

	// SWITCH TO CURRENT REQUEST LANGUAGE
	do_action('wpml_switch_language', $currentLanguage);
	add_filter('acf/settings/current_language', 'acf_set_language');

	// GET LATESTS PLAY LEVEL
	$args = array(
		'post_type' => 'search-and-find',
		'posts_per_page' => 1,
	);
	$searchAndFindsQuery = new WP_Query($args);


	if (!$searchAndFindsQuery->post) {
		do_action('wpml_switch_language', "fr");
		$searchAndFindsQuery = new WP_Query($args);
	}


	// RETURN IF NO GAME DATAS
	if (!$searchAndFindsQuery->posts || !$searchAndFindsQuery->posts[0] ||  !$searchAndFindsQuery->posts[0]->post_content) return rest_ensure_response(array('error' => 'impossible de trouver les données du jeu'));


	$lastGamePageBlocks = parse_blocks($searchAndFindsQuery->posts[0]->post_content);
	$gameBlock = null;


	foreach ($lastGamePageBlocks as $block) {

		if ('lhoist-blocks/search-and-find' === $block['blockName']) {
			$gameBlock = $block;
			break;
		}
	}
	$responseDatas = array(
		'gameId' =>  $searchAndFindsQuery->posts[0]->ID,
		'gameHtmlTemplate' =>  $searchAndFindsQuery->posts[0]->post_content,
		'gameBlockDatas' =>  $gameBlock,
		'gameObjects' =>  $gameBlock['innerBlocks'],
	);

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

	return $response;
}
function get_game_datas($request)
{
	$id = $request->get_param('id');
	$currentLanguage = strtolower($request->get_param('current-language')) ?? 'fr';
	if ($currentLanguage === "my") {
		$currentLanguage = "ms";
	}
	if ($currentLanguage === "pt") {
		$currentLanguage = "pt-pt";
	}

	// SWITCH TO CURRENT REQUEST LANGUAGE
	do_action('wpml_switch_language', $currentLanguage);
	add_filter('acf/settings/current_language', 'acf_set_language');


	$pageTranslatedID = apply_filters('wpml_object_id', $id, 'search-and-find', true);
	$gamePage = get_post($pageTranslatedID);

	// RETURN IF NO GAME DATAS
	if (!$gamePage ||  !$gamePage->post_content) return rest_ensure_response(array('error' => 'impossible de trouver les données du jeu'));


	$gamePageBlocks = parse_blocks($gamePage->post_content);
	$gameBlock = null;


	foreach ($gamePageBlocks as $block) {

		if ('lhoist-blocks/search-and-find' === $block['blockName']) {
			$gameBlock = $block;
			break;
		}
	}
	$responseDatas = array(
		'gameId' =>  $gamePage->ID,
		'gameHtmlTemplate' =>  $gamePage->post_content,
		'gameBlockDatas' =>  $gameBlock,
		'gameObjects' =>  $gameBlock['innerBlocks'],
	);

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

	return $response;
}
function get_all_games_datas($request)
{


	$currentLanguage = strtolower($request->get_param('current-language')) ?? 'fr';
	if ($currentLanguage === "my") {
		$currentLanguage = "ms";
	}
	if ($currentLanguage === "pt") {
		$currentLanguage = "pt-pt";
	}
	// SWITCH TO CURRENT REQUEST LANGUAGE
	do_action('wpml_switch_language', $currentLanguage);
	add_filter('acf/settings/current_language', 'acf_set_language');

	// GET LATESTS PLAY LEVEL
	$args = array(
		'post_type' => 'search-and-find',
		'posts_per_page' => -1,
	);
	$searchAndFindsQuery = new WP_Query($args);

	if (!$searchAndFindsQuery->post) {
		do_action('wpml_switch_language', "fr");
		$searchAndFindsQuery = new WP_Query($args);
	}

	$gamesDatas = array();

	// RETURN IF NO GAME DATAS
	if (!$searchAndFindsQuery->posts || !$searchAndFindsQuery->posts[0]) return rest_ensure_response(array('error' => 'impossible de trouver les données du jeu'));



	foreach ($searchAndFindsQuery->posts as $key => $post) {

		$currentGameDatas = array(
			'gameId' =>  $post->ID,
			'gameTitle' =>  $post->post_title,
			'gameCover' =>  get_the_post_thumbnail_url($post->ID, 'full'),
			'gamePrintPdf' =>  get_field('print_pdf', $post->ID) ? get_field('print_pdf', $post->ID)['url'] : null,
		);

		if (!$post->post_content || empty($post->post_content)) continue;


		$first_block = !empty($post->post_content) && parse_blocks($post->post_content) ? parse_blocks($post->post_content)[0] : null;

		if ($first_block['blockName'] === 'lhoist-blocks/search-and-find' && !empty($first_block['attrs']['coverId'])) {
			$currentGameDatas['gameCoverId'] = $first_block['attrs']['coverId'];
			$currentGameDatas['gameCoverUrl'] = $first_block['attrs']['coverUrl'];
		}
		array_push($gamesDatas, $currentGameDatas);
	}


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

	return $response;
}


function get_interface_page_screen($request)
{

	$id = $request->get_param('id');
	$currentLanguage = strtolower($request->get_param('current-language')) ?? 'fr';
	if ($currentLanguage === "my") {
		$currentLanguage = "ms";
	}
	if ($currentLanguage === "pt") {
		$currentLanguage = "pt-pt";
	}
	// SWITCH TO CURRENT REQUEST LANGUAGE
	do_action('wpml_switch_language', $currentLanguage);

	$pageTranslatedID = apply_filters('wpml_object_id', $id, 'post', true);
	$pageContent = get_post($pageTranslatedID);

	$responseDatas = $pageContent;

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

	return $response;
}


// ################ POST GAME STATISTICS ################


function lhoist_sanitize_statistic_datas($datas)
{
	$cleanDatas = array();

	$cleanDatas['user_locale'] = isset($datas['user_locale']) ? sanitize_text_field($datas['user_locale']) : null;
	$cleanDatas['user_country'] = isset($datas['user_country']) ? sanitize_text_field($datas['user_country']) : null;
	$cleanDatas['level_post_id'] = isset($datas['level_post_id']) ? (int) $datas['level_post_id'] : null;
	$cleanDatas['level_name'] = isset($datas['level_name']) ? sanitize_text_field($datas['level_name']) : null;
	$cleanDatas['level_score'] = isset($datas['level_score']) ? (int) $datas['level_score'] : null;
	$cleanDatas['level_completion_time'] = isset($datas['level_completion_time']) ? (int) $datas['level_completion_time'] : null;

	return $cleanDatas;
}

function lhoist_check_statistics_datas_formats($datas)
{
	if (!isset($datas['user_locale']) || !is_string($datas['user_locale']) || strlen($datas['user_locale']) > 3) {
		throw new Exception("La propriété 'user_locale' est manquante ou invalide.");
		exit;
	}
	if (!isset($datas['user_country']) || !is_string($datas['user_country'])) {
		throw new Exception("La propriété 'user_country' est manquante ou invalide.");
		exit;
	}
	if (!isset($datas['level_post_id']) || !is_numeric($datas['level_post_id'])) {
		throw new Exception("La propriété 'level_post_id' est manquante ou invalide.");
		exit;
	}
	if (!isset($datas['level_score']) || !is_numeric($datas['level_score'])) {
		throw new Exception("La propriété 'level_score' est manquante ou invalide.");
		exit;
	}
	if (!isset($datas['level_completion_time']) || !is_numeric($datas['level_completion_time'])) {
		throw new Exception("La propriété 'level_completion_time' est manquante ou invalide.");
		exit;
	}
}
function lhoist_convert_post_id($id)
{
	$convertedId = apply_filters('wpml_object_id', $id, 'search-and-find', true);
	return $convertedId;
}

function lhoist_post_game_datas_statistics(WP_REST_Request $request)
{
	$datas = $request->get_json_params();

	$datas['level_post_id'] = lhoist_convert_post_id($datas['level_post_id']);
	$datas['level_name'] = html_entity_decode(get_the_title($datas['level_post_id']), ENT_QUOTES, 'UTF-8');

	$cleanDatas = lhoist_sanitize_statistic_datas($datas);
	lhoist_check_statistics_datas_formats($cleanDatas);


	global $wpdb;

	$table_name = 'wp_app_users_statistics';
	$result_check = $wpdb->insert(
		$table_name,
		$cleanDatas
	);

	if ($result_check) {
		return rest_ensure_response(array('success' => true, 'message' => 'Données enregistrées avec succès.'));
	} else {
		return rest_ensure_response(array('success' => false, 'message' => 'Erreur lors de l\'enregistrement des données.'));
	}
}


// ################ POST APP RATING ################

function lhoist_sanitize_ratings_datas($datas)
{
	$cleanDatas = array();

	$cleanDatas['note'] = isset($datas['note']) ? (int) $datas['note'] : null;
	$cleanDatas['comment'] = isset($datas['comment']) ? sanitize_text_field($datas['comment']) : null;

	return $cleanDatas;
}

function lhoist_check_ratings_datas_formats($datas)
{

	if (!$datas['note'] || !is_numeric($datas['note'])) {
		throw new Exception("La propriété 'note' est manquante ou invalide.");
		exit;
	}
	if (isset($datas['comment']) && !is_string($datas['comment'])) {
		throw new Exception("La propriété 'commentaire' est manquante ou invalide.");
		exit;
	}
}

function lhoist_post_rating(WP_REST_Request $request)
{
	$datas = $request->get_json_params();

	$cleanDatas = lhoist_sanitize_ratings_datas($datas);
	lhoist_check_ratings_datas_formats($cleanDatas);


	global $wpdb;
	$datetime = new DateTime("now", new DateTimeZone('Europe/Brussels'));

	$ratingsDatas = array(
		'rating' => $cleanDatas['note'],
		'comment' => $cleanDatas['comment'] ?? '',
		'date' => $datetime->format('Y-m-d H:i:s'),
	);
	$table_name = 'wp_app_ratings';
	$result_check = $wpdb->insert(
		$table_name,
		$ratingsDatas
	);

	if ($result_check) {
		return rest_ensure_response(array('success' => true, 'message' => 'Données enregistrées avec succès.'));
	} else {
		return rest_ensure_response(array('success' => false, 'message' => 'Erreur lors de l\'enregistrement des données.'));
	}
}
