<?php

function populate_note_comment_based_on_rating($form)
{




	if ($form['id'] != 24) return;

	$commented_string_notes = array(
		1 => 'Pas du tout utile',
		2 => 'Peu utile',
		3 => 'Moyennement utile',
		4 => 'Assez utile',
		5 => 'Très utile'
	);

	// ## GLOBAL RATING
	$original_global_rating_field_id = 22;
	$hidden_copy_global_rating_field_id = 20;
	$global_user_rating = rgpost("input_{$original_global_rating_field_id}");

	$stringified_global_rating = isset($commented_string_notes[$global_user_rating]) ? $commented_string_notes[$global_user_rating] : '';
	$_POST["input_{$hidden_copy_global_rating_field_id}"] = $stringified_global_rating;


	// ## INFORMATION ACCESSIBILITY RATING
	$original_information_accessibility_rating_field_id = 15;
	$hidden_copy_information_accessibility_rating_field_id = 21;
	$information_accessibility_user_rating = rgpost("input_{$original_information_accessibility_rating_field_id}");

	$stringified_information_accessibility_rating = isset($commented_string_notes[$information_accessibility_user_rating]) ? $commented_string_notes[$information_accessibility_user_rating] : '';
	$_POST["input_{$hidden_copy_information_accessibility_rating_field_id}"] = $stringified_information_accessibility_rating;




	// write_log($form['fields']);
	foreach ($form['fields'] as $key => $field) {
		if ($field->type !== "homegrade-rating") continue;

		$global_user_rating = rgpost("input_{$field->id}");

		$nextHiddenLabelField = $form["fields"][$key + 1] ?? null;
		if (!$nextHiddenLabelField || $nextHiddenLabelField->type !== "hidden") continue;

		$stringified_information_accessibility_rating = isset($field["choices"][$global_user_rating - 1]['text']) ? $field["choices"][$global_user_rating - 1]['text'] : '';


		$_POST["input_{$nextHiddenLabelField->id}"] = $stringified_information_accessibility_rating;
	}
}
add_action('gform_pre_submission', 'populate_note_comment_based_on_rating');
