<?php

/**
 * Trait ASTGDRMSYS_Student_Custom_Field_Helper
 *
 * Normalizes student custom fields saved on student_result snapshots.
 */

if (! defined('ABSPATH')) {
	exit;
}

trait ASTGDRMSYS_Student_Custom_Field_Helper
{
	/**
	 * Parses student custom fields stored on the result snapshot.
	 *
	 * Supports the new Student Database shape, older indexed values using
	 * global labels, and associative key/value maps.
	 *
	 * @param mixed $raw_value Stored custom_fields value from student_result.
	 * @return array<int, array{name:string,value:string}>
	 */
	private function parse_student_custom_fields($raw_value): array
	{
		if (! is_string($raw_value) || trim($raw_value) === '') {
			return [];
		}

		$decoded = json_decode($raw_value, true);
		if (! is_array($decoded)) {
			$decoded = maybe_unserialize($raw_value);
		}

		if (! is_array($decoded)) {
			return [];
		}

		$global_labels = get_option('astgdrmsys_custom_field_labels', []);
		if (! is_array($global_labels)) {
			$global_labels = [];
		}

		$fields = [];
		foreach ($decoded as $key => $item) {
			$name  = '';
			$value = '';

			if (is_array($item)) {
				$name  = isset($item['name']) ? sanitize_text_field((string) $item['name']) : '';
				$value = isset($item['value']) ? sanitize_text_field((string) $item['value']) : '';
			} elseif (is_string($key) && ! is_numeric($key)) {
				$name  = sanitize_text_field($this->humanize_student_custom_field_name($key));
				$value = sanitize_text_field((string) $item);
			} else {
				$name  = isset($global_labels[$key]) ? sanitize_text_field((string) $global_labels[$key]) : '';
				$value = sanitize_text_field((string) $item);
			}

			if ($name !== '' && $value !== '') {
				$fields[] = [
					'name'  => $name,
					'value' => $value,
				];
			}
		}

		return $fields;
	}

	/**
	 * Converts machine-style custom field names to readable labels.
	 */
	private function humanize_student_custom_field_name(string $name): string
	{
		$name = str_replace(['_', '-'], ' ', $name);
		$name = preg_replace('/\s+/', ' ', $name);

		return ucwords(trim((string) $name));
	}
}
