<?php

namespace Formatrica\Capability\Rules;

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

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

/**
 * Save-path gate for multi-step forms (forms.multi_step).
 *
 * Multi-step is driven purely by step_break fields (fields between breaks form
 * a step). On Free, a NEW step_break is removed while existing ones are
 * grandfathered by stable key, so a form authored as multi-step keeps its steps
 * after a licence lapse (the renderer is capability-blind, in core).
 */
final class Multi_Step_Rule implements Premium_Config_Rule_Interface
{
    public function capability(): string
    {
        return Capabilities::FORMS_MULTI_STEP;
    }

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

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

        // Keys of step_break fields that already existed (grandfathered).
        $existing_keys = [];
        foreach (($existing['fields'] ?? []) as $ef) {
            if (is_array($ef) && ($ef['type'] ?? '') === 'step_break' && isset($ef['key'])) {
                $existing_keys[$ef['key']] = true;
            }
        }

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

            $field_key = $field['key'] ?? null;

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

            // New step break the saved form didn't have — remove it.
            unset($config['fields'][$i]);
            $rejected[] = [
                'key' => 'fields[' . $i . '].type=step_break',
                'reason' => __('Multi-step forms are a Pro feature; the new page break was removed.', 'formatrica'),
                'capability' => $this->capability(),
                'feature' => 'multi_step',
            ];
        }

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

        return $rejected;
    }
}
