<?php

namespace Formatrica\Capability\Rules;

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

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

/**
 * Save-path gate for conditional visibility logic (logic.visibility).
 *
 * On Free, strips NEWLY-enabled per-field logic while grandfathering existing
 * logic by stable key. The resolver + validation skip live in CORE, so a form
 * authored with logic keeps hiding/showing (and stays submittable) after a
 * licence lapse — only authoring NEW logic is blocked here.
 */
final class Conditional_Logic_Rule implements Premium_Config_Rule_Interface
{
    public function capability(): string
    {
        return Capabilities::LOGIC_VISIBILITY;
    }

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

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

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

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

            $logic = $field['logic'] ?? null;
            if (!is_array($logic) || empty($logic['enabled'])) {
                continue;
            }

            $field_key = $field['key'] ?? null;
            $existing_field = ($field_key !== null && isset($existing_by_key[$field_key]))
                ? $existing_by_key[$field_key]
                : null;

            $had_logic = is_array($existing_field['logic'] ?? null)
                && !empty($existing_field['logic']['enabled']);

            if ($had_logic) {
                continue; // grandfathered
            }

            // New logic activation — strip it.
            unset($config['fields'][$i]['logic']);
            $rejected[] = [
                'key' => 'fields[' . $i . '].logic',
                'reason' => __('Conditional logic is a Pro feature; the logic was removed.', 'formatrica'),
                'capability' => $this->capability(),
                'feature' => 'conditional_logic',
            ];
        }

        return $rejected;
    }
}
