<?php
/**
 * Registers the daily-digest WC_Email and fans the digest summary out to
 * email + Slack.
 *
 * @package StoreSheet
 */

declare( strict_types=1 );

namespace StoreSheet\Notifications;

defined( 'ABSPATH' ) || exit;

use StoreSheet\Emails\SyncDigestEmail;

class DigestNotifier {

	public function init(): void {
		add_filter( 'woocommerce_email_classes', array( $this, 'register_email' ) );
	}

	/**
	 * @param array<string, \WC_Email> $emails
	 * @return array<string, \WC_Email>
	 */
	public function register_email( array $emails ): array {
		$emails['StoreSheet_Sync_Digest'] = new SyncDigestEmail();
		return $emails;
	}

	/**
	 * Dispatch the daily digest to email (via the WC_Email that listens on
	 * storesheet_sync_digest) and Slack (when a webhook is configured).
	 *
	 * @param array<string,mixed> $summary Canonical digest summary.
	 */
	public function send( array $summary ): void {
		// Make sure WooCommerce has instantiated its email classes (including
		// SyncDigestEmail) so the storesheet_sync_digest listener is live
		// before we fire it — otherwise, in a bare Action Scheduler request,
		// the email object may not exist yet.
		if ( function_exists( 'WC' ) ) {
			WC()->mailer();
		}

		/**
		 * Fires with the daily sync digest summary. SyncDigestEmail sends off
		 * this; add-ons may hook it for additional digest channels.
		 *
		 * @since 1.2.0
		 * @param array<string,mixed> $summary Digest summary.
		 */
		do_action( 'storesheet_sync_digest', $summary );

		$settings = get_option( 'storesheet_settings', array() );
		if ( ! empty( $settings['slack_webhook_url'] ) ) {
			( new SlackNotifier() )->digest( $summary );
		}
	}
}
