<?php
namespace CartCue\Triggers;

use CartCue\CampaignRecipient;
use CartCue\MarketingConsent;

defined( 'ABSPATH' ) || exit;

/**
 * ManualTrigger — never fires automatically.
 * Used by the Campaign page to run a play on selected customers right now.
 */
class ManualTrigger extends AbstractTrigger {

	public function get_slug(): string {
		return 'manual';
	}

	public function get_label(): string {
		return __( 'Manual / Campaign', 'cartcue-sales-automation' );
	}

	public function get_sentence(): string {
		return __( 'you run this campaign manually', 'cartcue-sales-automation' );
	}

	public function get_description(): string {
		return __( 'Run this play on a chosen customer segment right now from the Campaign page. Never fires automatically.', 'cartcue-sales-automation' );
	}

	public function get_test_data(): array {
		return [
			'trigger'        => $this->get_slug(),
			'customer_id'    => get_current_user_id(),
			'customer_email' => get_option( 'admin_email', '' ),
			'_is_test'       => true,
		];
	}

	public function register_hooks(): void {
		/* Never auto-fires. */
	}

	public function show_in_picker(): bool {
		return false;
	}

	/**
	 * @param int   $workflow_id
	 * @param int[] $user_ids
	 * @return array{queued: int, skipped: int}
	 */
	public function run_for_customers( int $workflow_id, array $user_ids ): array {
		return $this->run_for_recipients( $workflow_id, CampaignRecipient::from_user_ids( $user_ids ) );
	}

	/**
	 * @param int   $workflow_id
	 * @param list<array{user_id?: int, email?: string, first_name?: string, last_name?: string}>|array<int|string|array<string, mixed>> $recipients
	 * @return array{queued: int, skipped: int}
	 */
	public function run_for_recipients( int $workflow_id, array $recipients ): array {
		$queued  = 0;
		$skipped = 0;

		foreach ( CampaignRecipient::normalize_chunk( $recipients ) as $recipient ) {
			$email = $recipient['email'];
			if ( ! MarketingConsent::can_send_to( $email ) ) {
				$skipped++;
				continue;
			}

			$this->plugin->runner->trigger(
				$workflow_id,
				[
					'trigger'        => $this->get_slug(),
					'customer_id'    => (int) $recipient['user_id'],
					'customer_email' => $email,
					'first_name'     => $recipient['first_name'],
					'last_name'      => $recipient['last_name'],
				]
			);
			$queued++;
		}

		return [
			'queued'  => $queued,
			'skipped' => $skipped,
		];
	}
}
