<?php
/**
 * PurchasedCategoryTrigger — fires when an order includes a product from a category.
 *
 * @package CartCue\Triggers
 */

namespace CartCue\Triggers;

use CartCue\OrderLineMatch;

defined( 'ABSPATH' ) || exit;

class PurchasedCategoryTrigger extends AbstractTrigger {

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

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

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

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

	public function get_settings_fields(): array {
		return [
			[
				'key'          => 'category',
				'label'        => __( 'Category', 'cartcue-sales-automation' ),
				'type'         => 'async_select',
				'value_source' => 'categories',
				'placeholder'  => __( 'Search categories', '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 ) {
			$category = sanitize_text_field( (string) ( $wf['trigger_settings']['category'] ?? '' ) );
			if ( '' === $category || ! OrderLineMatch::order_matches( $order_id, 'category', $category ) ) {
				continue;
			}
			$this->fire_for_order( $order, $category );
		}
	}

	private function fire_for_order( \WC_Order $order, string $category ): void {
		$dedup_key = '_cartcue_purchased_cat_' . md5( $category );
		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(),
				'category'       => $category,
			]
		);
	}
}
