<?php

namespace Formatrica\Capability\Rules;

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

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

/**
 * Save-path gate for Save & Resume drafts (submissions.drafts).
 *
 * On Free the per-form `options.drafts.enabled` toggle is frozen: it cannot be
 * flipped on, and a grandfathered "on" is preserved (turning it off is always
 * allowed). The runtime gate that actually blocks draft saves lives in
 * Draft_Save_Service; this only prevents authoring the toggle on. Mirrors
 * com_nxpeasyforms DraftsRule (soft revert-and-report).
 */
final class Drafts_Rule implements Premium_Config_Rule_Interface
{
    public function capability(): string
    {
        return Capabilities::SUBMISSIONS_DRAFTS;
    }

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

        // Unchanged, or turning it off → allowed, preserve everything else.
        if ($incoming === $previous || !$incoming) {
            return [];
        }

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

        return [[
            'key'        => 'options.drafts.enabled',
            'reason'     => __('Save & Resume is a Pro feature; the toggle was reverted.', 'formatrica'),
            'capability' => $this->capability(),
            'feature'    => 'drafts',
        ]];
    }
}
