<?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 email template controls (emails.template_controls).
 *
 * On Free the whole `options.email_template` block is frozen: any edit reverts to
 * the previously-saved block (or defaults on a new form). The renderer itself is
 * capability-blind, so a Pro-authored template keeps applying after a lapse — the
 * save-guard is the sole gate. Both sides are canonicalised (accent blanked when
 * use_global_accent is on) before comparison so the always-present default block
 * never trips a false revert. Mirrors com_nxpeasyforms EmailTemplateRule.
 */
final class Email_Template_Rule implements Premium_Config_Rule_Interface
{
    public function capability(): string
    {
        return Capabilities::EMAILS_TEMPLATE_CONTROLS;
    }

    public function enforce(array &$config, array $existing): array
    {
        $incoming = self::canonical($config['options']['email_template'] ?? []);
        $previous = self::canonical($existing['options']['email_template'] ?? []);

        if ($incoming === $previous) {
            return [];
        }

        if (isset($existing['options']['email_template']) && is_array($existing['options']['email_template'])) {
            $config['options']['email_template'] = $existing['options']['email_template'];
        } else {
            // No prior block → drop it; merge_with_defaults reapplies the baseline.
            unset($config['options']['email_template']);
        }

        return [[
            'key'        => 'options.email_template',
            'reason'     => __('Email template controls are a Pro feature; changes were reverted.', 'formatrica'),
            'capability' => $this->capability(),
            'feature'    => 'email_template',
        ]];
    }

    /**
     * @param mixed $block
     * @return array<string,mixed>
     */
    private static function canonical($block): array
    {
        $b          = is_array($block) ? $block : [];
        $use_global = !array_key_exists('use_global_accent', $b) || !empty($b['use_global_accent']);

        return [
            'show_title'        => !array_key_exists('show_title', $b) || !empty($b['show_title']),
            'show_metadata'     => !array_key_exists('show_metadata', $b) || !empty($b['show_metadata']),
            'font_stack'        => (string) ($b['font_stack'] ?? 'system'),
            'use_global_accent' => $use_global,
            'accent_color'      => $use_global ? '' : strtoupper((string) ($b['accent_color'] ?? '')),
            'intro_text'        => (string) ($b['intro_text'] ?? ''),
            'footer_text'       => (string) ($b['footer_text'] ?? ''),
        ];
    }
}
