<?php
/**
 * PurchasedProductTrigger — fires when an order includes a specific product.
 *
 * @package CartCue\Triggers
 */

namespace CartCue\Triggers;

use CartCue\OrderLineMatch;

defined( 'ABSPATH' ) || exit;

class PurchasedProductTrigger extends AbstractTrigger {

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

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

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

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

	public function get_settings_fields(): array {
		return [
			[
				'key'           => 'product_id',
				'label'         => __( 'Product', 'cartcue-sales-automation' ),
				'type'          => 'async_select',
				'value_source'  => 'products',
				'placeholder'   => __( 'Search products', '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;
		}

		$workflows = $this->plugin->runner->get_active_workflows_for_trigger( $this->get_slug() );
		if ( empty( $workflows ) ) {
			return;
		}

		foreach ( $workflows as $wf ) {
			$product_id = (int) ( $wf['trigger_settings']['product_id'] ?? 0 );
			if ( ! $product_id || ! OrderLineMatch::order_matches( $order_id, 'product', (string) $product_id ) ) {
				continue;
			}
			$this->fire_for_order( $order, $product_id );
		}
	}

	private function fire_for_order( \WC_Order $order, int $product_id ): void {
		$dedup_key = '_cartcue_purchased_product_' . $product_id;
		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_id'     => $product_id,
			]
		);
	}
}
