<?php
/**
 * OrderRefundedTrigger — fires on full or partial refunds.
 *
 * @package CartCue\Triggers
 */

namespace CartCue\Triggers;

defined( 'ABSPATH' ) || exit;

class OrderRefundedTrigger extends AbstractTrigger {

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

	public function get_label(): string {
		return __( 'Order Refunded', 'cartcue-sales-automation' );
	}

	public function get_sentence(): string {
		return __( 'an order is refunded', 'cartcue-sales-automation' );
	}

	public function get_description(): string {
		return __( 'A full or partial refund is created.', 'cartcue-sales-automation' );
	}

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

	public function register_hooks(): void {
		add_action( 'woocommerce_order_fully_refunded', [ $this, 'handle_full' ], 10, 2 );
		add_action( 'woocommerce_order_partially_refunded', [ $this, 'handle_partial' ], 10, 2 );
	}

	public function handle_full( int $order_id, int $refund_id ): void {
		$this->dispatch( $order_id, 'full', $refund_id );
	}

	public function handle_partial( int $order_id, int $refund_id ): void {
		$this->dispatch( $order_id, 'partial', $refund_id );
	}

	private function dispatch( int $order_id, string $refund_type, int $refund_id ): void {
		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			return;
		}

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