<?php

namespace GriffinForms\Frontend\Security\FieldValidations;

class InputAddress extends Format
{
    protected function customValidate($value, $iteration_index)
    {
        if (!is_array($value)) {
            return;
        }

        $country = isset($value['country']) ? strtoupper(trim($value['country'])) : '';
        if ($country === '') {
            return;
        }

        $validations = $this->field->getProp('validations');

        if (!is_array($validations) || ($validations['type'] ?? '') !== 'custom-parameters') {
            return;
        }

        $mode = isset($validations['country_filter_mode']) ? $validations['country_filter_mode'] : 'all_countries';

        if ($mode === 'limit_to_countries') {
            $allowed = array_map('strtoupper', (array) ($validations['allowed_countries'] ?? array()));
            if (!empty($allowed) && !in_array($country, $allowed, true)) {
                $this->addError($this->lang->getText('country_filter_error', $validations), $iteration_index);
            }
        }

        if ($mode === 'exclude_countries') {
            $excluded = array_map('strtoupper', (array) ($validations['excluded_countries'] ?? array()));
            if (in_array($country, $excluded, true)) {
                $this->addError($this->lang->getText('country_filter_error', $validations), $iteration_index);
            }
        }
    }
}
