<?php
/**
 * Formidable submission generation controller.
 *
 * @package EntryFoundry
 */

namespace EntryFoundry\Core\Controllers;

// Constructor and hook method types define this focused controller contract.
// phpcs:disable Squiz.Commenting, Generic.Commenting.DocComment

use EntryFoundry\Core\Models\Template\TemplateRepository;
use EntryFoundry\Core\Services\Generation\DocumentGenerationService;
use RuntimeException;

/** Generates the form's active template and attaches it to request-time mail. */
final class SubmissionController {
	/** @var TemplateRepository */ private $templates;
	/** @var DocumentGenerationService */ private $generation;
	/** @var string[] */ private $attachments = array();

	public function __construct( TemplateRepository $templates, DocumentGenerationService $generation ) {
		$this->templates  = $templates;
		$this->generation = $generation;
	}

	public function register(): void {
		add_action( 'frm_after_create_entry', array( $this, 'after_create_entry' ), 10, 2 );
		add_filter( 'wp_mail', array( $this, 'attach_to_mail' ) );
	}

	public function after_create_entry( int $entry_id, int $form_id ): void {
		$template = $this->templates->find_active_for_form( $form_id );
		if ( ! $template ) {
			return; }
		try {
			$this->attachments[] = $this->generation->generate_pdf( $template['id'], $entry_id );
			do_action( 'entryfoundry_pdf_generated', end( $this->attachments ), $template['id'], $entry_id );
		} catch ( RuntimeException $exception ) {
			do_action( 'entryfoundry_pdf_generation_failed', $template['id'], $entry_id, $exception );
		}
	}

	/** @param array<string,mixed> $mail WordPress mail arguments. @return array<string,mixed> */
	public function attach_to_mail( array $mail ): array {
		$current             = isset( $mail['attachments'] ) ? (array) $mail['attachments'] : array();
		$mail['attachments'] = array_values( array_unique( array_merge( $current, array_filter( $this->attachments, 'is_file' ) ) ) );
		return $mail;
	}
}
