<?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 Pro theme presets (forms.themes, P17). Reverts ONLY
 * `options.theme.preset` when a NEW Pro preset (material/clean/card/underline)
 * arrives on Free; the same Pro preset as already stored passes
 * (preserve-existing — a downgraded install re-saving keeps its authored
 * preset). Brand colour and mode are Free and always flow through. The
 * renderer (Theme_Overlay_Resolver) is capability-blind by design — this
 * save-guard is the sole gate.
 */
final class Theme_Preset_Rule implements Premium_Config_Rule_Interface
{
    private const PRO_PRESETS = ['material', 'clean', 'card', 'underline'];

    public function capability(): string
    {
        return Capabilities::FORMS_THEMES;
    }

    public function enforce(array &$config, array $existing): array
    {
        $incoming = $config['options']['theme'] ?? null;
        if (!is_array($incoming)) {
            return [];
        }

        $incoming_preset = is_string($incoming['preset'] ?? null) ? $incoming['preset'] : 'classic';
        $existing_preset = is_string($existing['options']['theme']['preset'] ?? null)
            ? $existing['options']['theme']['preset']
            : 'classic';

        // Classic (or unknown) is the Free baseline — always allowed.
        if (!in_array($incoming_preset, self::PRO_PRESETS, true)) {
            return [];
        }

        // Same Pro preset as before — grandfathered.
        if ($incoming_preset === $existing_preset) {
            return [];
        }

        // New/changed Pro preset on Free: revert only the preset; brand colour
        // and mode (Free features) stay as submitted.
        $config['options']['theme']['preset'] = in_array($existing_preset, self::PRO_PRESETS, true)
            ? $existing_preset
            : 'classic';

        return [[
            'key' => 'options.theme.preset',
            'reason' => __('Theme presets are a Pro feature; the preset was reverted.', 'formatrica'),
            'capability' => $this->capability(),
            'feature' => 'theme_presets',
        ]];
    }
}
