<?php
/**
 * CustomerCreatedTrigger — fires when a new WordPress user account is registered
 * on a WooCommerce store (covers standard registration and checkout registration).
 *
 * @package CartCue\Triggers
 */

namespace CartCue\Triggers;

defined( 'ABSPATH' ) || exit;

class CustomerCreatedTrigger extends AbstractTrigger {

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

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

	public function get_description(): string {
		return __( 'Someone creates a new account.', 'cartcue-sales-automation' );
	}
	public function get_sentence(): string {
		return __( 'a new customer registers', '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', '' ), 'source' => 'register', '_is_test' => true ];
	}

	public function get_settings_fields(): array {
		return [
			[
				'key'     => 'registration_source',
				'label'   => __( 'Registration Source', 'cartcue-sales-automation' ),
				'type'    => 'select',
				'default' => 'any',
				'options' => [
					'any'      => __( 'Any (registration page + checkout)', 'cartcue-sales-automation' ),
					'checkout' => __( 'During checkout only', 'cartcue-sales-automation' ),
					'register' => __( 'My Account / Register page only', 'cartcue-sales-automation' ),
				],
			],
		];
	}

	public function register_hooks(): void {
		// woocommerce_created_customer fires for both checkout and my-account registration.
		add_action( 'woocommerce_created_customer', [ $this, 'handle' ], 10, 3 );
	}

	/**
	 * @param int   $customer_id
	 * @param array $new_customer_data
	 * @param bool  $password_generated
	 */
	public function handle( int $customer_id, array $new_customer_data, bool $password_generated ): void {
		$user = get_user_by( 'id', $customer_id );
		if ( ! $user ) {
			return;
		}

		// Determine registration context.
		$source = is_checkout() ? 'checkout' : 'register';

		$workflows = $this->plugin->runner->get_active_workflows_for_trigger( $this->get_slug() );

		foreach ( $workflows as $workflow ) {
			$cfg_source = $workflow['trigger_settings']['registration_source'] ?? 'any';

			if ( 'any' !== $cfg_source && $cfg_source !== $source ) {
				continue;
			}

			$data = [
				'trigger'        => $this->get_slug(),
				'customer_id'    => $customer_id,
				'customer_email' => $user->user_email,
				'first_name'     => $user->first_name,
				'last_name'      => $user->last_name,
				'username'       => $user->user_login,
				'source'         => $source,
			];

			$this->plugin->runner->trigger( (int) $workflow['id'], $data );
		}
	}
}
