<?php

namespace GriffinForms\Frontend\Security\FieldValidations;

/**
 * Class InputRadio
 * Handles validation for radio input fields in GriffinForms.
 */
class InputRadio extends Format
{
    /**
     * Perform custom validation for the input radio field.
     *
     * @param string $value The selected radio value.
     */
    protected function customValidate($value, $iteration_index)
    {
        $fieldOptions = $this->field->getProp('field_options');
    
        // Validate against available options ONLY if a value is selected
        if (!empty($value) && !empty($fieldOptions) && is_array($fieldOptions)) {
            $validValues = $this->extractValidOptions($fieldOptions);
    
            if (!in_array($value, $validValues, true)) {
                $this->addError(__('Invalid selection: The selected value is not a valid option.', 'griffinforms-form-builder'));
            }
        }
    }

    /**
     * Extracts valid radio button options from field_options.
     *
     * @param array $fieldOptions The field options stored in the database.
     * @return array The valid option values.
     */
    private function extractValidOptions($fieldOptions)
    {
        $validValues = [];

        foreach ($fieldOptions as $optionGroup) {
            if (is_array($optionGroup)) {
                foreach ($optionGroup as $label => $value) {
                    $validValues[] = $value; // Extract value from associative array
                }
            }
        }

        return $validValues;
    }
}