<?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\Submission_Repository;

/**
 * Generate the submission UUID and store the submission when enabled.
 */
final class Persistence_Stage implements Submission_Stage
{
    public function __construct(private Submission_Repository $submissions)
    {
    }

    public function handle(Submission_Context $ctx): void
    {
        // A paid form may have set the uuid already in Payment_Gate_Stage so the
        // order row can link to it before persistence.
        if ($ctx->uuid === '') {
            $ctx->uuid = wp_generate_uuid4();
        }

        // Always store when a payment is pending — the webhook needs a row to flip.
        if (!empty($ctx->options['store_submissions']) || $ctx->early_payment_response !== null) {
            $ctx->submission_id = $this->submissions->create(
                $ctx->form_id,
                $ctx->uuid,
                $ctx->sanitised,
                [
                    'status' => 'new',
                    'ip_address' => $ctx->stored_ip,
                    'user_agent' => $ctx->context['user_agent'],
                ]
            );
        }
    }
}
