<?php

namespace GriffinForms\Frontend\Security\FieldValidations;

class SelectField extends Format
{
    /**
     * Perform custom validation for the select field.
     * Ensures the selected value is among the valid field options.
     *
     * @param mixed $value The value to validate.
     * @return void
     * @throws \Exception If validation fails.
     */
    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 options from the field options array.
     *
     * @param array $fieldOptions The field options stored in the database.
     * @return array The valid option values.
     */
    private function extractValidOptions($fieldOptions)
    {
        $validValues = [];
        foreach ($fieldOptions as $group => $options) {
            if (is_array($options)) {
                $validValues = array_merge($validValues, array_values($options));
            }
        }
        return $validValues;
    }
}