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

add_action('rest_api_init', function () {

	// ################ SCREENS ################
	register_rest_route('lhoist-datas/screen', '/welcome', array(
		'methods' => 'GET',
		'callback' => 'get_interface_welcome_screen_datas',
		'permission_callback' => '__return_true',
		// 'permission_callback' => 'lhoist_datas_permission_callback',


	));
	register_rest_route('lhoist-datas/screen', '/profile', array(
		'methods' => 'GET',
		'callback' => 'get_interface_profile_screen_datas',
		'permission_callback' => '__return_true',
	));
	// ################ GAME ################
	register_rest_route('lhoist-datas/screen', '/play/latest', array(
		'methods' => 'GET',
		'callback' => 'get_interface_play_screen_datas',
		'permission_callback' => '__return_true',
	));


	// ################ UTILS ################
	register_rest_route('lhoist-datas', '/available-countries', array(
		'methods' => 'GET',
		'callback' => 'get_interface_available_countries',
		'permission_callback' => '__return_true',
	));



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

	));
});

function lhoist_datas_permission_callback(
	WP_REST_Request $request
) {
	$user_ip = $request->get_header('x_real_ip');

	if ($user_ip === API_GILLES_AUTHORIZED_IP || $user_ip === API_ANTOINE_AUTHORIZED_IP) {
		return true;
	}

	return false;
}
// ################ RETURN GAME STATISTICS ################

function lhoist_post_game_datas_statistics(WP_REST_Request $request)
{

	$data = $request->get_json_params(); // Récupération des données envoyées avec la requête POST
	$user_locale = $data['user_locale'] ?? null;
	$user_country = $data['user_country'] ?? null;
	$level_post_id = $data['level_post_id'] ?? null;
	$level_is_completed = $data['level_is_completed'] ?? null;
	$level_completion_time = $data['level_completion_time'] ?? null;
	$level_score = $data['level_score'] ?? null;

	if (!$data) {
		return rest_ensure_response(array('success' => false, 'message' => 'yooo Erreur lors de l\'enregistrement des données.'));
		exit;
	}


	global $wpdb;

	$table_name = 'wp_app_users_statistics';
	$post_id = uniqid();
	$datetime = new DateTime("now", new DateTimeZone('Europe/Brussels'));

	$gameStats = array(
		'session_ID' => $post_id,
		'user_locale' => $user_locale,
		'user_country' => $user_country,
		'level_post_id' => $level_post_id,
		'level_is_completed' => $level_is_completed ?? "0",
		'level_completion_time' => $level_completion_time,
		'level_score' => $level_score,
		'date' => $datetime->format('Y-m-d H:i:s'),
	);

	$result_check = $wpdb->insert(
		$table_name,
		$gameStats
	);

	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.'));
	}
}



// ################ INTERFACE SCREEN DATAS ################

function get_interface_welcome_screen_datas($request)
{
	$user_ip = $request->get_header('x_real_ip');
	write_log("API_TOKEN :" . API_TOKEN);
	write_log("API_AUTHORIZED_IP :" . API_AUTHORIZED_IP);
	write_log("USER_IP :" . $user_ip);
	// write_log($request);
	// $language = sanitize_text_field($request['language']);
	$currentLanguage = $request->get_param('current-language') ?? 'fr';

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

	// GET SCREEN FIELDS CONTENT
	$applicationTitle = get_field('application_title', 'option');
	$applicationSubtitle = get_field('application_subtitle', 'option');
	$applicationDescription = get_field('application_description', 'option');

	$response_data = array(
		'applicationTitle' =>  $applicationTitle,
		'applicationSubtitle' =>  $applicationSubtitle,
		'applicationDescription' =>  $applicationDescription,
	);

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

	return $response;
}

function get_interface_profile_screen_datas($request)
{
	// $language = sanitize_text_field($request['language']);
	$currentLanguage = $request->get_param('current-language') ?? 'fr';

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


	// GET SCREEN FIELDS CONTENT
	$profile_screen_title = get_field('profile_screen_title', 'option');

	$profile_select_title = get_field('profile_select_title', 'option');
	$profile_country_select_title = get_field('profile_country_select_title', 'option');
	$profile_options = get_field('profile_options', 'option');

	// $profile_options = array(
	// 	"lhoist_employee" => __("Employé Lhoist", "lhoist-stay-safe_theme"),
	// 	"subcontractor_employee" => __("Employé sous-traitant", "lhoist-stay-safe_theme"),
	// 	"driver" => __("Chauffeur de camion", "lhoist-stay-safe_theme"),
	// 	"civilian" => __("Civil", "lhoist-stay-safe_theme"),
	// );

	$response_data = array(
		'profileScreenTitle' =>  $profile_screen_title,
		'profileOptions' =>  $profile_options,
		'profileSelectTitle' =>  $profile_select_title,
		'profileCountrySelectTitle' =>  $profile_country_select_title,
	);

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

	return $response;
}

function get_interface_play_screen_datas($request)
{

	// $language = sanitize_text_field($request['language']);
	$currentLanguage = $request->get_param('current-language') ?? 'fr';

	// 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);
	// 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_interface_available_countries($request)
{

	$currentLanguage = $request->get_param('current-language');
	$json_current_lang_file_path = get_template_directory() . '/languages/countries_' . $currentLanguage . '.json' ?? null;
	$json_french_file_path = get_template_directory() . '/languages/countries_fr.json';

	if (!file_exists($json_current_lang_file_path) && !file_exists($json_french_file_path)) return rest_ensure_response(array('error' => 'impossible de trouver les fichiers de traductions'));

	$json_content = file_exists($json_current_lang_file_path) ? file_get_contents($json_current_lang_file_path) : file_get_contents($json_french_file_path);
	$translations = json_decode($json_content);

	if (!$json_content) 	return rest_ensure_response(array('error' => 'impossible de trouver les traductions'));

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

	return $response;
}
