<?php
/**
 * PurchasedTagTrigger — fires when an order includes a product with a tag.
 *
 * @package CartCue\Triggers
 */

namespace CartCue\Triggers;

use CartCue\OrderLineMatch;

defined( 'ABSPATH' ) || exit;

class PurchasedTagTrigger extends AbstractTrigger {

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

	public function get_label(): string {
		return __( 'Customer Purchased Product with Tag', 'cartcue-sales-automation' );
	}

	public function get_sentence(): string {
		return __( 'a customer buys a product with a specific tag', 'cartcue-sales-automation' );
	}

	public function get_description(): string {
		return __( 'Runs when an order is paid and includes a product tagged as you specify.', 'cartcue-sales-automation' );
	}

	public function get_settings_fields(): array {
		return [
			[
				'key'          => 'product_tag',
				'label'        => __( 'Product tag', 'cartcue-sales-automation' ),
				'type'         => 'async_select',
				'value_source' => 'tags',
				'placeholder'  => __( 'Search tags', 'cartcue-sales-automation' ),
				'default'      => '',
			],
		];
	}

	public function register_hooks(): void {
		add_action( 'woocommerce_payment_complete', [ $this, 'handle' ], 15, 1 );
		add_action( 'woocommerce_order_status_completed', [ $this, 'handle' ], 15, 1 );
	}

	public function handle( int $order_id ): void {
		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			return;
		}

		foreach ( $this->plugin->runner->get_active_workflows_for_trigger( $this->get_slug() ) as $wf ) {
			$tag = sanitize_text_field( (string) ( $wf['trigger_settings']['product_tag'] ?? '' ) );
			if ( '' === $tag || ! OrderLineMatch::order_matches( $order_id, 'tag', $tag ) ) {
				continue;
			}
			$this->fire_for_order( $order, $tag );
		}
	}

	private function fire_for_order( \WC_Order $order, string $tag ): void {
		$dedup_key = '_cartcue_purchased_tag_' . md5( $tag );
		if ( $order->get_meta( $dedup_key ) ) {
			return;
		}
		$order->update_meta_data( $dedup_key, '1' );
		$order->save_meta_data();

		$this->fire(
			[
				'trigger'        => $this->get_slug(),
				'order_id'       => $order->get_id(),
				'customer_id'    => (int) $order->get_customer_id(),
				'customer_email' => $order->get_billing_email(),
				'product_tag'    => $tag,
			]
		);
	}
}
