<?php

namespace GriffinForms\Frontend\Security\FieldValidations;

/**
 * Class TextArea
 * Handles validation for textarea input fields in GriffinForms.
 */
class TextArea extends Format
{
    /**
     * Perform custom validation for the textarea field.
     *
     * @param string $value The user-inputted text.
     */
    protected function customValidate($value, $iteration_index)
    {
        $validations = $this->field->getProp('validations');
        if (!$validations) return;
    
        // Skip validation for empty fields unless required validation is handled in validateAllIterations()
        if (empty($value)) {
            return;
        }
    
        // Min characters validation
        if (!empty($validations['min_chars']) && is_numeric($validations['min_chars'])) {
            $this->validateMinChars($value, (int) $validations['min_chars']);
        }
    
        // Max characters validation
        if (!empty($validations['max_chars']) && is_numeric($validations['max_chars'])) {
            $this->validateMaxChars($value, (int) $validations['max_chars']);
        }
    }

    /**
     * Validate minimum number of characters.
     *
     * @param string $value The text to validate.
     * @param int $min_chars The minimum character length allowed.
     */
    private function validateMinChars($value, $min_chars)
    {
        $trimmed_value = trim($value);

        if ($trimmed_value === '' || mb_strlen($trimmed_value, 'UTF-8') < $min_chars) {
            /* translators: %d is the minimum number of characters required in the textarea field */
            $this->addError(sprintf(__('The text must be at least %d characters long.', 'griffinforms-form-builder'), $min_chars));
        }
    }

    /**
     * Validate maximum number of characters.
     *
     * @param string $value The text to validate.
     * @param int $max_chars The maximum character length allowed.
     */
    private function validateMaxChars($value, $max_chars)
    {
        if (mb_strlen(trim($value), 'UTF-8') > $max_chars) {
            /* translators: %d is the maximum number of characters allowed in the textarea field */
            $this->addError(sprintf(__('The text must not exceed %d characters.', 'griffinforms-form-builder'), $max_chars));
        }
    }
}