<?php

namespace RTMCustomMails\Preview;

use RTMCustomMails\Email\RTMCustomEmail;
use WC_Email;
use WC_Email_Customer_Reset_Password;
use WordpressModels\Traits\SingletonTrait;
use WP_User;

/**
 * Generates dummy/preview data for email trigger functions
 */
class PreviewTriggerArguments
{

    use SingletonTrait;

    public function __construct()
    {
        add_filter('wrce_preview_trigger_args', [$this, 'getArguments'], 10, 4);
        add_filter('wrce_preview_trigger_args/email_id=customer_note', [$this, 'getCustomerNoteArgs'], 10, 2);

        add_filter('wrce_preview_trigger_args/email_id=customer_reset_password', [$this, 'getLostPasswordArgs'], 10, 4);

        add_filter('wrce_preview_trigger_args/object_type=order', [$this, 'provideOrderId'], 10, 2);
        add_filter('wrce_preview_trigger_args/object_type=user', [$this, 'provideUserId'], 10, 2);
    }

    public function provideOrderId(mixed $value, mixed $objectId): array
    {
        return ['order_id' => $objectId];
    }

    public function provideUserId(mixed $value, mixed $objectId): array
    {
        return ['user_id' => $objectId];
    }

    public static function getArguments(mixed $defaultValue, string $emailClass, mixed $objectId, WC_Email $email)
    {
        $value = $defaultValue;
        if ($email instanceof RTMCustomEmail) {
            $value = apply_filters('wrce_preview_trigger_args/object_type=' . $email->getObjectType(), $value, $objectId, $email);
            $value = apply_filters('wrce_preview_trigger_args/email_id=' . $email->id, $value, $objectId, $email);
        }

        return $value;
    }

    public function getLostPasswordArgs(mixed $current, int $userId, WC_Email_Customer_Reset_Password $email): array
    {
        return ['user_login' => (new WP_User($userId))->user_login, 'reset_key' => 'preview_key'];
    }

    /**
     * @param $default
     * @param $orderId
     * @return array[]
     */
    public function getCustomerNoteArgs($default, $orderId): array
    {
        return [
            [
                'order_id' => $orderId,
                'customer_note' => wc_get_order($orderId)->get_customer_note()
            ]
        ];
    }

}