<?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 submitter confirmation email (emails.submitter_confirmation).
 *
 * On Free the `options.submitter_email.enabled` flag is frozen: it cannot be
 * flipped on, and a grandfathered "on" is preserved (turning it off is always
 * allowed). Copy fields (subject/body/sender) stay editable — they are harmless
 * while disabled, and the runtime dispatcher re-checks the capability before ever
 * sending. Mirrors com_nxpeasyforms SubmitterEmailRule (preserve-existing).
 */
final class Submitter_Email_Rule implements Premium_Config_Rule_Interface
{
    public function capability(): string
    {
        return Capabilities::EMAILS_SUBMITTER_CONFIRMATION;
    }

    public function enforce(array &$config, array $existing): array
    {
        $incoming = !empty($config['options']['submitter_email']['enabled']);
        $previous = !empty($existing['options']['submitter_email']['enabled']);

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

        if (!isset($config['options']['submitter_email']) || !is_array($config['options']['submitter_email'])) {
            $config['options']['submitter_email'] = [];
        }
        $config['options']['submitter_email']['enabled'] = false;

        return [[
            'key'        => 'options.submitter_email.enabled',
            'reason'     => __('The submitter confirmation email is a Pro feature; the toggle was reverted.', 'formatrica'),
            'capability' => $this->capability(),
            'feature'    => 'submitter_email',
        ]];
    }
}
