<?php

namespace Formatrica\Submission\Pipeline\Stages;

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

use Formatrica\Email\Email_Service;
use Formatrica\Submission\Pipeline\Submission_Context;
use Formatrica\Submission\Pipeline\Submission_Stage;

/**
 * Send the admin notification email when enabled.
 */
final class Notification_Email_Stage implements Submission_Stage
{
    public function __construct(private Email_Service $email)
    {
    }

    public function handle(Submission_Context $ctx): void
    {
        // Deferred until the payment confirms (webhook re-runs this stage).
        if ($ctx->early_payment_response !== null) {
            return;
        }

        $email_result = [
            'sent' => false,
            'message' => __('Email notifications disabled.', 'formatrica'),
        ];

        if (!empty($ctx->options['send_email'])) {
            $email_result = $this->email->dispatch_submission($ctx->form, $ctx->sanitised, [
                'ip_address' => $ctx->stored_ip,
                'fields' => $ctx->field_meta,
            ]);

            if (!$email_result['sent']) {
                $email_result['message'] = $email_result['message'] ?? __('Email delivery failed.', 'formatrica');
            }
        }

        $ctx->email_result = $email_result;
    }
}
