<?php

namespace EasyLinkAutomations\Triggers\WooCommerce;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a new WooCommerce customer account is created.
 */
final class CustomerCreatedTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'woocommerce/customer_created';
    }

    public static function getName(): string
    {
        return __('Customer created', 'easylink-automations');
    }

    public static function getDescription(): string
    {
        return __('Triggers when a new WooCommerce customer account is created', 'easylink-automations');
    }

    public static function getCategory(): string
    {
        return 'WooCommerce';
    }

    public static function getIcon(): string
    {
        return 'woocommerce';
    }


    public static function isAvailable(): bool
    {
        return class_exists('WooCommerce');
    }

    public static function getOutputFields(): array
    {
        return [
            'user_id'      => ['label' => 'Customer User ID', 'type' => 'number'],
            'user_login'   => ['label' => 'Username', 'type' => 'string'],
            'user_email'   => ['label' => 'Email', 'type' => 'email'],
            'display_name' => ['label' => 'Display Name', 'type' => 'string'],
            'first_name'   => ['label' => 'First Name', 'type' => 'string'],
            'last_name'    => ['label' => 'Last Name', 'type' => 'string'],
            'role'         => ['label' => 'Role', 'type' => 'string'],
            'billing_city' => ['label' => 'Billing City', 'type' => 'string'],
            'billing_country' => ['label' => 'Billing Country', 'type' => 'string'],
        ];
    }

    public static function getConfigFields(): array
    {
        return [];
    }

    public function register(callable $callback): void
    {
        $this->callback = $callback;

        add_action('woocommerce_created_customer', function (int $customerId, array $newCustomerData, bool $passwordGenerated): void {
            $data = $this->handle($customerId);
            $this->fire($data);
        }, 10, 3);
    }

    public function handle(mixed ...$args): array
    {
        $customerId = (int) $args[0];

        $user = get_userdata($customerId);

        if (!$user) {
            return [];
        }

        $roles    = $user->roles ?? [];
        $customer = new \WC_Customer($customerId);

        return [
            'user_id'         => $customerId,
            'user_login'      => $user->user_login,
            'user_email'      => $user->user_email,
            'display_name'    => $user->display_name,
            'first_name'      => $user->first_name,
            'last_name'       => $user->last_name,
            'role'            => $roles[0] ?? '',
            'billing_city'    => $customer->get_billing_city(),
            'billing_country' => $customer->get_billing_country(),
        ];
    }
}
