<?php

namespace Formatrica\Capability\Rules;

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

use Formatrica\Capability\Capabilities;
use Formatrica\Capability\Premium_Config_Rule_Interface;
use Formatrica\Submission\Validation\Rule_Validator;

/**
 * Save-path gate for the 8 Pro validation rules (fields.validation_pro_rules,
 * P12). Reverts an attempt to set a Pro `validation.rule` on a field when the
 * capability is unavailable, preserving any existing Pro-rule config by stable
 * key (a lapsed install keeps enforcing what it already saved — evaluators are
 * capability-blind in core). Free rules + the disabled state pass through.
 */
final class Advanced_Validations_Rule implements Premium_Config_Rule_Interface
{
    public function capability(): string
    {
        return Capabilities::FIELDS_VALIDATION_PRO_RULES;
    }

    public function enforce(array &$config, array $existing): array
    {
        $rejected = [];

        if (!isset($config['fields']) || !is_array($config['fields'])) {
            return $rejected;
        }

        // Index existing fields by key for O(1) per-field lookup.
        $existing_by_key = [];
        foreach (($existing['fields'] ?? []) as $ef) {
            if (is_array($ef) && isset($ef['key']) && is_string($ef['key'])) {
                $existing_by_key[$ef['key']] = $ef;
            }
        }

        foreach ($config['fields'] as $i => $field) {
            if (!is_array($field)) {
                continue;
            }
            $incoming = $field['validation'] ?? null;
            if (!is_array($incoming) || empty($incoming['advanced_enabled'])) {
                continue;
            }
            $rule = $incoming['rule'] ?? '';
            if (!is_string($rule) || !in_array($rule, Rule_Validator::PRO_RULES, true)) {
                continue; // Free rule — allowed.
            }

            // A Pro rule was selected. Preserve if it's the same one already
            // stored for this field (grandfathered); otherwise revert.
            $field_key = $field['key'] ?? null;
            $existing_validation = ($field_key !== null && isset($existing_by_key[$field_key]))
                ? ($existing_by_key[$field_key]['validation'] ?? null)
                : null;
            $existing_rule = (is_array($existing_validation) && isset($existing_validation['rule']))
                ? (string) $existing_validation['rule']
                : '';

            if ($existing_rule === $rule) {
                continue; // same Pro rule as before — grandfathered.
            }

            if (is_array($existing_validation)) {
                $config['fields'][$i]['validation'] = $existing_validation;
            } else {
                unset($config['fields'][$i]['validation']);
            }

            $rejected[] = [
                'key' => 'fields[' . $i . '].validation',
                'reason' => __('Advanced validation rules are a Pro feature; the change was reverted.', 'formatrica'),
                'capability' => $this->capability(),
                'feature' => 'validation_pro_rules',
            ];
        }

        return $rejected;
    }
}
