<?php

namespace Formatrica\Capability\Rules;

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

use Formatrica\Capability\Premium_Config_Rule_Interface;

/**
 * Base save-path gate for a Pro-only field TYPE. On Free it removes NEWLY-added
 * fields of the type while grandfathering existing ones by stable key, then
 * re-indexes. The field's renderer/validator live in CORE, so grandfathered
 * fields keep working after a licence lapse — only authoring a NEW one is
 * blocked.
 */
abstract class Pro_Field_Type_Rule implements Premium_Config_Rule_Interface
{
    abstract public function capability(): string;

    /** The field `type` this rule gates. */
    abstract protected function field_type(): string;

    /** Short slug for the rejection entry's `feature`. */
    abstract protected function feature_slug(): string;

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

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

        $type = $this->field_type();

        $existing_keys = [];
        foreach (($existing['fields'] ?? []) as $ef) {
            if (is_array($ef) && ($ef['type'] ?? '') === $type && isset($ef['key'])) {
                $existing_keys[$ef['key']] = true;
            }
        }

        foreach ($config['fields'] as $i => $field) {
            if (!is_array($field) || ($field['type'] ?? '') !== $type) {
                continue;
            }

            $field_key = $field['key'] ?? null;
            if ($field_key !== null && isset($existing_keys[$field_key])) {
                continue; // grandfathered
            }

            unset($config['fields'][$i]);
            $rejected[] = [
                'key' => 'fields[' . $i . '].type=' . $type,
                /* translators: %s: field type */
                'reason' => sprintf(__('The %s field is a Pro feature; the new field was removed.', 'formatrica'), $type),
                'capability' => $this->capability(),
                'feature' => $this->feature_slug(),
            ];
        }

        if ($rejected !== []) {
            $config['fields'] = array_values($config['fields']);
        }

        return $rejected;
    }
}
