<?php
/**
 * Accounts Module Automations
 *
 * Registers automation triggers, conditions, and event handlers for account-related workflows.
 *
 * @package AmbassadorHub\Accounts
 */

namespace AmbassadorHub\Accounts;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use AmbassadorHub\Automations\AbstractAutomations;
use AmbassadorHub\Automations\ScheduleEngine;
use AmbassadorHub\Accounts\Admin\Settings\SettingsManager;

use function add_filter;
use function add_action;
use function esc_html__;
use function get_userdata;

/**
 * Consolidates automation registration and event handling for the Accounts module.
 *
 * Extends AbstractAutomations to provide a reusable pattern for automation integration.
 *
 * Registers:
 * - Automation triggers (account_created, account_updated, account_deleted, account_email_verified)
 * - Automation conditions (donations_total_eur, donations_count)
 * - Metric value providers for condition evaluation
 * - Event handlers for account lifecycle events
 */
final class Automations extends AbstractAutomations {

	/**
	 * Register module-specific event handlers.
	 *
	 * Called by AbstractAutomations::init() during initialization.
	 *
	 * @return void
	 */
	protected static function register_event_handlers(): void {

		// Register event emitters for account lifecycle
		add_action( 'ambh_profile_updated', array( self::class, 'on_profile_update' ), 10, 1 );
		add_action( 'ambh_ambassador_role_added', array( self::class, 'on_ambassador_role_added' ), 10, 1 );
		add_action( 'ambh_account_deleted', array( self::class, 'on_account_deleted' ), 10, 1 );
		add_action( 'ambh_email_verified', array( self::class, 'on_email_verified' ), 10, 1 );

		// Handle webhook payload for account-related actions
		add_filter( 'ambh_get_webhook_action_payload_user', array( self::class, 'get_account_webhook_payload' ), 10, 3 );

		// Template tokens for the variable picker in the automation UI.
		add_filter( 'ambh_automation_template_tokens', array( self::class, 'register_template_tokens' ), 10, 2 );
	}

	// ===========================
	// Trigger Registration
	// ===========================

	/**
	 * Register trigger groups for the Accounts module.
	 *
	 * @param array $groups Existing trigger groups.
	 *
	 * @return array Modified groups.
	 */
	public static function register_trigger_groups( array $groups ): array {
		$groups['accounts'] = array(
			'label' => esc_html__( 'Account updates', 'ambassadorhub' ),
			'icon'  => 'dashicons-admin-users',
		);

		return $groups;
	}

	/**
	 * Register account triggers.
	 *
	 * @param array $triggers Existing triggers.
	 *
	 * @return array Modified triggers.
	 */
	public static function register_triggers( array $triggers ): array {
		$triggers['account_created'] = array(
			'label'       => esc_html__( 'Account created', 'ambassadorhub' ),
			'description' => esc_html__( 'Triggered when a new ambassador account is created', 'ambassadorhub' ),
			'group'       => 'accounts',
			'entity_type' => 'user',
			'event'       => 'created',
			'icon'        => 'dashicons-admin-users',
		);

		$triggers['account_updated'] = array(
			'label'       => esc_html__( 'Account updated', 'ambassadorhub' ),
			'description' => esc_html__( 'Triggered when an ambassador account is updated', 'ambassadorhub' ),
			'group'       => 'accounts',
			'entity_type' => 'user',
			'event'       => 'updated',
			'icon'        => 'dashicons-update',
		);

		$triggers['account_deleted'] = array(
			'label'       => esc_html__( 'Account deleted', 'ambassadorhub' ),
			'description' => esc_html__( 'Triggered when an ambassador account is deleted', 'ambassadorhub' ),
			'group'       => 'accounts',
			'entity_type' => 'user',
			'event'       => 'deleted',
			'icon'        => 'dashicons-trash',
		);

		$triggers['account_email_verified'] = array(
			'label'       => esc_html__( 'Account email verified', 'ambassadorhub' ),
			'description' => esc_html__( 'Triggered when an ambassador account completes email verification and becomes fully active', 'ambassadorhub' ),
			'group'       => 'accounts',
			'entity_type' => 'user',
			'event'       => 'email_verified',
			'icon'        => 'dashicons-yes-alt',
		);

		return $triggers;
	}

	// ===========================
	// Condition Registration
	// ===========================

	/**
	 * Register account-related conditions.
	 *
	 * @param array $conditions Existing conditions.
	 * @param array $context    Context data.
	 *
	 * @return array
	 */
	public static function register_conditions( array $conditions, array $context ): array {
		return $conditions;
	}

	// ===========================
	// Event Handlers
	// ===========================

	/**
	 * Handle ambassador role assignment.
	 *
	 * Emits automation trigger when a user is assigned the ambassador role.
	 * Covers signup, admin assignment, imports, and programmatic role changes.
	 *
	 * @param int $user_id User ID.
	 *
	 * @return void
	 */
	public static function on_ambassador_role_added( int $user_id ): void {

		ScheduleEngine::schedule_rules_for_trigger(
			'account_created',
			$user_id,
			array(
				'role'   => Roles::ROLE_AMBASSADOR,
				'source' => 'role_added',
			)
		);
	}

	public static function on_profile_update( int $user_id ): void {

		ScheduleEngine::schedule_rules_for_trigger(
			'account_updated',
			$user_id,
			array(
				'user'   => get_userdata( $user_id ),
				'source' => 'profile_update',
			),
		);
	}

	public static function on_account_deleted( int $user_id ): void {

		ScheduleEngine::schedule_rules_for_trigger(
			'account_deleted',
			$user_id,
			array(
				'source' => 'account_deleted',
			),
		);
	}

	public static function on_email_verified( int $user_id ): void {

		ScheduleEngine::schedule_rules_for_trigger(
			'account_email_verified',
			$user_id,
			array(
				'source' => 'email_verified',
			),
		);
	}

	/**
	 * Register template tokens for the automation variable picker (user entity).
	 *
	 * @param array  $tokens      Existing tokens.
	 * @param string $entity_type Entity type being queried.
	 *
	 * @return array
	 */
	public static function register_template_tokens( array $tokens, string $entity_type ): array {
		if ( 'user' !== $entity_type ) {
			return $tokens;
		}

		return array_merge(
			$tokens,
			array(
				'{{first_name}}' => array( 'label' => __( 'First name', 'ambassadorhub' ) ),
				'{{last_name}}'  => array( 'label' => __( 'Last name', 'ambassadorhub' ) ),
				'{{email}}'      => array( 'label' => __( 'Email address', 'ambassadorhub' ) ),
			)
		);
	}

	public static function get_account_webhook_payload( array $payload, int $target_id, $action_id ): array {

		if ( ! $target_id ) {
			return $payload;
		}

		$user_info = get_userdata( $target_id );
		if ( ! $user_info ) {
			return $payload;
		}

		$payload['user'] = array(
			'ID'           => $user_info->ID,
			'user_login'   => $user_info->user_login,
			'user_email'   => $user_info->user_email,
			'first_name'   => $user_info->first_name,
			'last_name'    => $user_info->last_name,
			'display_name' => AccountFields::build_display_name( $user_info->ID ),
			'roles'        => $user_info->roles,
			'registered'   => $user_info->user_registered,
		);

		$payload['profile_fields'] = AccountFields::get_payload_fields( $user_info->ID );

		return $payload;
	}
}
