<?php

namespace Formatrica\Capability\Rules;

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

use Formatrica\Capability\Capabilities;
use Formatrica\Capability\Premium_Config_Rule_Interface;

/**
 * Save-path gate for the price field (payments.basic) — but a GRANDFATHERING one,
 * unlike the payments hard gate. An existing price field (matched by stable key)
 * survives a license lapse so a live product page doesn't lose its price tag; only
 * a NEWLY introduced price field is stripped on Free. Mirrors com_nxpeasyforms
 * PriceFieldRule.
 */
final class Price_Field_Rule implements Premium_Config_Rule_Interface
{
    public function capability(): string
    {
        return Capabilities::PAYMENTS_BASIC;
    }

    public function enforce(array &$config, array $existing): array
    {
        $existing_keys = [];
        foreach (($existing['fields'] ?? []) as $field) {
            if (is_array($field) && ($field['type'] ?? '') === 'price' && !empty($field['key'])) {
                $existing_keys[(string) $field['key']] = true;
            }
        }

        $fields   = isset($config['fields']) && is_array($config['fields']) ? $config['fields'] : [];
        $rejected = [];

        foreach ($fields as $index => $field) {
            if (!is_array($field) || ($field['type'] ?? '') !== 'price') {
                continue;
            }
            $key = (string) ($field['key'] ?? '');
            if ($key !== '' && isset($existing_keys[$key])) {
                continue; // grandfathered — keep it
            }

            unset($fields[$index]);
            $rejected[] = [
                'key'        => 'fields.price',
                'reason'     => __('Price fields are a Pro feature; the field was removed.', 'formatrica'),
                'capability' => $this->capability(),
                'feature'    => 'price_field',
            ];
        }

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

        return $rejected;
    }
}
