<?php

namespace EasyLinkAutomations\Triggers\WooCommerce;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a WooCommerce order is paid (completed with a payment method).
 */
final class OrderPaidTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'woocommerce/order_paid';
    }

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

    public static function getDescription(): string
    {
        return __('Triggers when a WooCommerce order is paid and reaches completed status', '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 [
            'order_id'                   => ['label' => 'Order ID', 'type' => 'number'],
            'order_number'               => ['label' => 'Order Number', 'type' => 'string'],
            'order_status'               => ['label' => 'Order Status', 'type' => 'string'],
            'order_total'                => ['label' => 'Order Total', 'type' => 'string'],
            'order_subtotal'             => ['label' => 'Order Subtotal', 'type' => 'string'],
            'order_tax'                  => ['label' => 'Order Tax', 'type' => 'string'],
            'order_shipping'             => ['label' => 'Order Shipping', 'type' => 'string'],
            'order_currency'             => ['label' => 'Order Currency', 'type' => 'string'],
            'order_date'                 => ['label' => 'Order Date', 'type' => 'datetime'],
            'order_payment_method'       => ['label' => 'Payment Method', 'type' => 'string'],
            'order_payment_method_title' => ['label' => 'Payment Method Title', 'type' => 'string'],
            'billing_first_name'         => ['label' => 'Billing First Name', 'type' => 'string'],
            'billing_last_name'          => ['label' => 'Billing Last Name', 'type' => 'string'],
            'billing_email'              => ['label' => 'Billing Email', 'type' => 'email'],
            'billing_phone'              => ['label' => 'Billing Phone', 'type' => 'string'],
            'billing_address_1'          => ['label' => 'Billing Address 1', 'type' => 'string'],
            'billing_address_2'          => ['label' => 'Billing Address 2', 'type' => 'string'],
            'billing_city'               => ['label' => 'Billing City', 'type' => 'string'],
            'billing_state'              => ['label' => 'Billing State', 'type' => 'string'],
            'billing_postcode'           => ['label' => 'Billing Postcode', 'type' => 'string'],
            'billing_country'            => ['label' => 'Billing Country', 'type' => 'string'],
            'shipping_first_name'        => ['label' => 'Shipping First Name', 'type' => 'string'],
            'shipping_last_name'         => ['label' => 'Shipping Last Name', 'type' => 'string'],
            'shipping_address_1'         => ['label' => 'Shipping Address 1', 'type' => 'string'],
            'shipping_address_2'         => ['label' => 'Shipping Address 2', 'type' => 'string'],
            'shipping_city'              => ['label' => 'Shipping City', 'type' => 'string'],
            'shipping_state'             => ['label' => 'Shipping State', 'type' => 'string'],
            'shipping_postcode'          => ['label' => 'Shipping Postcode', 'type' => 'string'],
            'shipping_country'           => ['label' => 'Shipping Country', 'type' => 'string'],
            'user_id'                    => ['label' => 'Customer User ID', 'type' => 'number'],
            'user_login'                 => ['label' => 'Customer Username', 'type' => 'string'],
            'user_email'                 => ['label' => 'Customer Email', 'type' => 'email'],
            'display_name'               => ['label' => 'Customer Display Name', 'type' => 'string'],
            'first_name'                 => ['label' => 'Customer First Name', 'type' => 'string'],
            'last_name'                  => ['label' => 'Customer Last Name', 'type' => 'string'],
            'role'                       => ['label' => 'Customer Role', 'type' => 'string'],
        ];
    }

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

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

        $listener = function (int $orderId): void {
            $order = wc_get_order($orderId);

            if (!$order instanceof \WC_Order) {
                return;
            }

            if ('completed' !== $order->get_status()) {
                return;
            }

            if (empty($order->get_payment_method())) {
                return;
            }

            $data = $this->handle($orderId);
            $this->fire($data);
        };

        add_action('woocommerce_new_order', $listener, 10, 1);
        add_action('woocommerce_order_status_completed', $listener, 10, 1);
    }

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

        if (!$order instanceof \WC_Order) {
            return [];
        }

        $userId  = (int) $order->get_customer_id();
        $user    = $userId ? get_userdata($userId) : null;
        $roles   = $user->roles ?? [];
        $dateObj = $order->get_date_created();

        return [
            'order_id'                   => $orderId,
            'order_number'               => $order->get_order_number(),
            'order_status'               => $order->get_status(),
            'order_total'                => $order->get_total(),
            'order_subtotal'             => $order->get_subtotal(),
            'order_tax'                  => $order->get_total_tax(),
            'order_shipping'             => $order->get_shipping_total(),
            'order_currency'             => $order->get_currency(),
            'order_date'                 => $dateObj ? $dateObj->format('Y-m-d H:i:s') : '',
            'order_payment_method'       => $order->get_payment_method(),
            'order_payment_method_title' => $order->get_payment_method_title(),
            'billing_first_name'         => $order->get_billing_first_name(),
            'billing_last_name'          => $order->get_billing_last_name(),
            'billing_email'              => $order->get_billing_email(),
            'billing_phone'              => $order->get_billing_phone(),
            'billing_address_1'          => $order->get_billing_address_1(),
            'billing_address_2'          => $order->get_billing_address_2(),
            'billing_city'               => $order->get_billing_city(),
            'billing_state'              => $order->get_billing_state(),
            'billing_postcode'           => $order->get_billing_postcode(),
            'billing_country'            => $order->get_billing_country(),
            'shipping_first_name'        => $order->get_shipping_first_name(),
            'shipping_last_name'         => $order->get_shipping_last_name(),
            'shipping_address_1'         => $order->get_shipping_address_1(),
            'shipping_address_2'         => $order->get_shipping_address_2(),
            'shipping_city'              => $order->get_shipping_city(),
            'shipping_state'             => $order->get_shipping_state(),
            'shipping_postcode'          => $order->get_shipping_postcode(),
            'shipping_country'           => $order->get_shipping_country(),
            'user_id'                    => $userId,
            'user_login'                 => $user->user_login ?? '',
            'user_email'                 => $user->user_email ?? $order->get_billing_email(),
            'display_name'               => $user->display_name ?? '',
            'first_name'                 => $user->first_name ?? $order->get_billing_first_name(),
            'last_name'                  => $user->last_name ?? $order->get_billing_last_name(),
            'role'                       => $roles[0] ?? '',
        ];
    }
}
