<?php

// Valider seulement les codes postaux de la région de Bruxelles-Capitale

add_filter('gform_field_validation_18', 'brussels_postal_code_validation', 10, 4);
function brussels_postal_code_validation($result, $value, $form, $field)
{

	$allowed_postal_codes = [
		1000,	// Bruxelles-Ville
		1020, // Laeken
		1120, // Neder-Over-Heembeek
		1130, // Haren
		1030, // Schaerbeek
		1040, // Etterbeek
		1050, // Ixelles
		1060, // Saint-Gilles
		1070, // Anderlecht
		1080, // Molenbeek-Saint-Jean
		1081, // Koekelberg
		1082, // Berchem-Sainte-Agathe
		1083, // Ganshoren
		1090, // Jette
		1140, // Evere
		1150, // Woluwe-Saint-Pierre
		1160, // Auderghem
		1170, // Watermael-Boitsfort
		1180, // Uccle
		1190, // Forest
		1200, // Woluwe-Saint-Lambert
		1210  // Saint-Josse-ten-Noode
	];


	// Check if the field is the adress field
	if ($field->id == 9) {

		$user_postal_code = sanitize_text_field($value['9.5']);
		$numeric_user_postal_code = intval($user_postal_code);

		$isBrusselsZipCode = in_array($numeric_user_postal_code, $allowed_postal_codes) ?? false;

		if (!$isBrusselsZipCode) {
			$result['is_valid'] = false;
			$result['message'] = __("Veuillez entrer un code postal valide pour la région de Bruxelles-Capitale.", "homegrade-theme__texte-fonctionnel");
		}
	}

	return $result;
}


// Limit countries for the paper publication order form

add_filter('gform_pre_render_18', 'homegrade_paper_publications_form_limit_countries');
add_filter('gform_pre_validation_18', 'homegrade_paper_publications_form_limit_countries');
add_filter('gform_pre_submission_filter_18', 'homegrade_paper_publications_form_limit_countries');
add_filter('gform_admin_pre_render_18', 'homegrade_paper_publications_form_limit_countries');


function homegrade_paper_publications_form_limit_countries($form)
{

	add_filter('gform_countries', function ($countries) {
		return array("Belgique" => __("Belgique", "homegrade_theme--texte-fonctionnel"));
	});

	return $form;
}

// Add user language to the form submission
add_filter('gform_pre_submission_18', 'set_hidden_field_value');
function set_hidden_field_value($form)
{
	// ID du champ caché
	$user_language_field = 27;
	$current_language = apply_filters('wpml_current_language', NULL);


	// Remplir le champ caché avec la valeur
	foreach ($form['fields'] as &$field) {
		if ($field->id == $user_language_field) {
			$_POST["input_{$field->id}"] = $current_language;
		}
	}

	return $form;
}


add_action('gform_after_submission', 'add_user_language_to_submission', 10, 2);
function add_user_language_to_submission($entry, $form)
{
	// Obtenir la langue actuelle via WPML
	$current_language = apply_filters('wpml_current_language', NULL);

	// Ajouter la langue à l'entrée de formulaire
	GFAPI::update_entry_field($entry['id'], 'language', 'lol ' . $current_language);
}


add_filter('gform_field_value_user_language', 'fill_user_language');
function fill_user_language($value)
{
	return apply_filters('wpml_current_language', NULL);
}
