<?php

namespace Formatrica\Capability\Rules;

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

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

/**
 * Save-path gate for redirect-on-submit (submissions.redirect).
 *
 * On Free, submit_action is frozen at its saved value (preserve-existing): a new
 * redirect can't be set, and a grandfathered one can't be edited away. The
 * runtime that performs the redirect lives in CORE (Success_Response_Stage +
 * frontend), so a lapsed form keeps redirecting — only authoring is blocked
 * here.
 */
final class Submit_Redirect_Rule implements Premium_Config_Rule_Interface
{
    public function capability(): string
    {
        return Capabilities::SUBMISSIONS_REDIRECT;
    }

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

        $incoming = self::normalize($config['options']['submit_action'] ?? null);
        $existing_value = self::normalize($existing['options']['submit_action'] ?? null);

        if ($incoming === $existing_value) {
            return $rejected;
        }

        // Restore the previously-saved value (or the Free baseline on a new form).
        $config['options']['submit_action'] = $existing_value;
        $rejected[] = [
            'key' => 'options.submit_action',
            'reason' => __('Redirect-on-submit is a Pro feature; reverted.', 'formatrica'),
            'capability' => $this->capability(),
            'feature' => 'submit_redirect',
        ];

        return $rejected;
    }

    /**
     * @param mixed $value
     * @return array{type:string,url:string}
     */
    private static function normalize($value): array
    {
        if (!is_array($value)) {
            return ['type' => 'same_page', 'url' => ''];
        }
        $type = isset($value['type']) && $value['type'] === 'url' ? 'url' : 'same_page';
        $url = isset($value['url']) && is_scalar($value['url']) ? trim((string) $value['url']) : '';
        return ['type' => $type, 'url' => $url];
    }
}
