<?php

namespace Formatrica\Admin;

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

/**
 * Prefills the editor when a builder quick action (Pro forms.quick_actions)
 * deep-links to post-new.php?formatrica_form_id=N — the WP deep-link
 * that threads the form id into the create screen.
 *
 * Runs through WP's default_content filter, so it only seeds the initial
 * editor content of a NEW page/post draft; nothing is created or saved by the
 * link itself. Capability-blind on purpose: the param is just an int and the
 * output just a shortcode block — harmless even if crafted manually.
 */
final class Quick_Action_Prefill
{
    public function register(): void
    {
        add_filter('default_content', [$this, 'prefill'], 10, 2);
    }

    /**
     * @param string $content
     * @param \WP_Post $post
     */
    public function prefill($content, $post): string
    {
        $content = is_string($content) ? $content : '';

        if (!isset($_GET['formatrica_form_id'])) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            return $content;
        }

        // Plain int cast (not absint — that would turn "-5" into 5). The cast
        // IS the sanitizer; read-only prefill hint, so no nonce either.
        $form_id = (int) wp_unslash($_GET['formatrica_form_id']); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- int cast sanitizes
        if ($form_id <= 0 || $content !== '') {
            return $content;
        }

        // Gutenberg shortcode block; degrades to a plain shortcode in the
        // classic editor.
        return "<!-- wp:shortcode -->\n[formatrica id=\"{$form_id}\"]\n<!-- /wp:shortcode -->";
    }
}
