<?php

namespace Formatrica\Submission\Pipeline\Stages;

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

use Formatrica\Submission\Pipeline\Submission_Context;
use Formatrica\Submission\Pipeline\Submission_Stage;
use Formatrica\Submission\Rendering\Template_Renderer;

/**
 * Resolve the success-message placeholders and assemble the response payload.
 */
final class Success_Response_Stage implements Submission_Stage
{
    public function handle(Submission_Context $ctx): void
    {
        // Paid form: the response is a redirect to the gateway, not the success
        // message (which the return-terminal shows after the payment confirms).
        if ($ctx->early_payment_response !== null) {
            $ctx->result = array_merge(['success' => true, 'payment_required' => true], $ctx->early_payment_response);

            return;
        }

        $success_message = $ctx->options['success_message'] ?? __('Thanks! Your message has been sent.', 'formatrica');
        $success_message = (new Template_Renderer())
            ->render((string) $success_message, $ctx->form, $ctx->sanitised, $ctx->field_meta);
        if ($success_message === '') {
            $success_message = __('Thanks! Your message has been sent.', 'formatrica');
        }

        $ctx->success_message = $success_message;

        $ctx->result = [
            'success' => true,
            'message' => $success_message,
            'data' => [
                'submission_id' => $ctx->submission_id,
                'fields' => $ctx->sanitised,
            ],
            'email' => $ctx->email_result,
        ];

        // Redirect-on-submit (Pro submissions.redirect) moved to the Pro-owned
        // Redirect_Response_Stage (Phase-5 completion) - the Free package
        // preserves the submit_action config but never executes the redirect.
    }
}
