<?php


namespace CreativeMail\Managers;

use CreativeMail\CreativeMail;
use CreativeMail\Helpers\EnvironmentHelper;
use CreativeMail\Helpers\OptionsHelper;
use CreativeMail\Modules\Api\Models\ApiRequestItem;
use stdClass;

/**
 * Class EmailManager
 *
 * @package CreativeMail\Managers
 */
class EmailManager
{
    /**
     * Email ids being managed by CreativeMail
     *
     * @var array
     */
    protected $managed_email_notifications;

    private $valid_email_notification_names = [
        'customer_completed_order',
        'customer_refunded_order',
        'customer_processing_order',
        'customer_on_hold_order',
        'customer_new_account',
        'customer_reset_password',
        'customer_invoice',
        'customer_note'
    ];

    public function __construct()
    {

    }

    public function add_hooks()
    {
        // check if woocommerce is active
        if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
            add_action('init', array($this, 'manage_emails'));

            // email settings table customizations
            add_filter('woocommerce_email_setting_columns', array($this, 'customize_email_setting_columns'));
            add_action('woocommerce_email_setting_column_wc_ce_status', array($this, 'render_email_status_column'));
            add_action('woocommerce_email_settings_before', array($this, 'redirect_managed_email_settings_to_creative_mail'));

            //woocommerce hooks
            add_action('woocommerce_new_order', array($this, 'ce_email_notification_new_order'), 10, 2);
            add_action('woocommerce_order_status_cancelled', array($this, 'ce_email_notification_cancelled'), 10, 2);
            add_action('woocommerce_order_status_failed', array($this, 'ce_email_notification_failed'), 10, 2);
            add_action('woocommerce_order_status_on-hold', array($this, 'ce_email_notification_hold'), 10, 2);
            add_action('woocommerce_order_status_processing', array($this, 'ce_email_notification_processing'), 10, 2);
            add_action('woocommerce_order_status_completed', array($this, 'ce_email_notification_completed'), 10, 2);
            add_action('woocommerce_order_status_refunded', array($this, 'ce_email_notification_refunded'), 10, 2);
            add_action('woocommerce_after_resend_order_email', array($this, 'ce_email_notification_invoice'), 10, 2);
            //payment complete
            add_action('woocommerce_payment_complete', array( $this, 'ce_email_notification_payment_complete'), 10, 1);
            //
            add_action('woocommerce_new_customer_note', array( $this, 'ce_email_notification_new_customer_note'), 10, 2);
            //
            add_action('woocommerce_reset_password_notification', array( $this, 'ce_email_notification_customer_reset_password' ), 10, 2);
            add_action('woocommerce_created_customer', array( $this, 'ce_email_notification_customer_new_account' ), 10, 3);
            // replace wc email settings
            add_filter('woocommerce_email_settings', array($this, 'replace_wc_email_settings'));
            add_action('woocommerce_admin_field_ce_manage_button', array($this, 'print_ce_manage_button'));
            // add checkbox to checkout if enabled
            if (OptionsHelper::get_checkout_checkbox_enabled() === '1') {
                add_filter('woocommerce_after_order_notes', array($this, 'add_checkout_field'));
                add_action('woocommerce_checkout_update_order_meta', array($this, 'ce_checkout_order_meta'));
            }
        }
    }

    public function ce_checkout_order_meta( $order_id )
    {
        if ($_POST['ce_checkout_consent_checkbox']) {
            $checkbox_value = esc_attr($_POST['ce_checkout_consent_checkbox']);
            update_post_meta($order_id, 'ce_checkout_consent', $checkbox_value);
        }
    }

    public function add_checkout_field( $checkout)
    {
        $checked = $checkout->get_value('ce_checkout_consent_checkbox') ? $checkout->get_value('ce_checkout_consent_checkbox') : 1;
        $checkbox_text = stripslashes(OptionsHelper::get_checkout_checkbox_text());

        woocommerce_form_field(
            'ce_checkout_consent_checkbox', array(
            'type'    => 'checkbox',
            'class'    => array('ce-field form-row-wide'),
            'label'    => $checkbox_text,
            ), $checked
        );
    }

    public function replace_wc_email_settings($settings)
    {
        $default_setting_replacement = array(
            'woocommerce_email_header_image'            => 'header_image',
            'woocommerce_email_footer_text'             => 'footer_content_text',
            'woocommerce_email_base_color'              => null,
            'woocommerce_email_background_color'        => 'background_color',
            'woocommerce_email_body_background_color'   => 'email_background_color',
            'woocommerce_email_text_color'              => 'text_color'
        );

        // Define options that need to be replaced
        $replace = array_merge(array_keys($default_setting_replacement), array('email_template_options'));

        // remove settings
        foreach ($settings as $setting_key => $setting) {
            if (isset($setting['id']) && in_array($setting['id'], $replace, true)) {
                unset($settings[$setting_key]);
            }
        }

        $settings[] = array(
            'id'    => 'ce_manage',
            'type'  => 'title',
            'title' => __('Creative Mail', 'ce4wp'),
        );

        $settings[] = array(
            'id'    => 'ce_manage_button',
            'type'  => 'ce_manage_button',
        );

        $settings[] = array(
            'id'    => 'ce_manage',
            'type'  => 'sectionend',
        );
        return $settings;
    }

    public function print_ce_manage_button($options)
    {
        ?><tr valign="top">
            <th scope="row" class="titledesc">Customize Emails</th>
            <td class="forminp forminp-<?php echo sanitize_title($options['type']); ?>">
                <a href="admin.php?page=creativemail">
                    <button type="button" class="button button-secondary" value="<?php _e('Manage', 'ce4wp'); ?>">Manage</button>
                </a>
                <p class="description">Manage all your email settings and templates with Creative Mail</p>
            </td>
            </tr><?php
    }

    public function get_managed_email_notifications()
    {
        return OptionsHelper::get_managed_email_notifications();
    }

    public function set_managed_email_notifications($body)
    {
        if (empty($body) || $body === null ) {
            return null;
        }

        if (property_exists($body, 'name') ) {
            if (in_array($body->name, $this->valid_email_notification_names) ) {
                OptionsHelper::set_managed_email_notification($body->name, $body->active == true ? 'true' : 'false');
                return $body;
            }
        }

        return null;
    }

    /**
     * Renders the custom email status column.
     *
     * @param \WC_Email $email the email
     *
     * @internal
     * @since    1.1.0
     */
    public function render_email_status_column( \WC_Email $email )
    {

        echo '<td class="wc-email-settings-table-status">';

        if ($this->is_email_managed($email->id) ) {
            echo '<span class="status-creativemail tips" data-tip="' . esc_attr__('Managed by Creative Mail', 'ce4wp') . '">' . esc_html__('Managed by CreativeMail', 'ce4wp') . '</span>';
        } elseif ($email->is_manual() ) {
            echo '<span class="status-manual tips" data-tip="' . esc_attr__('Manually sent', 'woocommerce') . '">' . esc_html__('Manual', 'woocommerce') . '</span>';
        } elseif ($email->is_enabled() ) {
            echo '<span class="status-enabled tips" data-tip="' . esc_attr__('Enabled', 'woocommerce') . '">' . esc_html__('Yes', 'woocommerce') . '</span>';
        } else {
            echo '<span class="status-disabled tips" data-tip="' . esc_attr__('Disabled', 'woocommerce') . '">-</span>';
        }

        echo '</td>';
    }

    public function customize_email_setting_columns( $columns )
    {

        $column_keys = array_keys($columns);

        // replace the status column, or put at the beginning if status isn't found
        $status_index = array_search('status', $column_keys, true);
        array_splice($column_keys, is_numeric($status_index) ? $status_index : 0, is_numeric($status_index) ? 1 : 0, 'wc_ce_status');

        $new_columns = array();
        $columns['wc_ce_status']      = '';

        foreach ( $column_keys as $column_key )
        {
            if (isset($columns[ $column_key ]) ) {
                $new_columns[ $column_key ] = $columns[ $column_key ];
            }
        }

        return $new_columns;
    }

    public function ce_email_notification_new_customer_note($array)
    {
        $data = new stdClass();
        $data->order_id = $array['order_id'];
        $data->note = $array['customer_note'];
        $data->order_url = $this->get_view_order_url($data->order_id, null);

        $this->execute_trigger("customer_note", $data, wc_get_order($data->order_id));
    }

    public function ce_email_notification_customer_new_account($customer_id, $new_customer_data, $password_generated)
    {
        $data = new stdClass();
        $data->customer_id = $customer_id;
        $data->account_url = $this->get_my_account_url();
        $data->customer = $this->get_customer_data($customer_id);

        if ($password_generated && key_exists("user_pass", $new_customer_data)) {
            try {
                $generated_password = $new_customer_data['user_pass'];
                $key = sha1(OptionsHelper::get_instance_api_key() . OptionsHelper::get_instance_uuid());
                $salt = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
                $salted = '';
                $dx = '';
                while (strlen($salted) < 48) {
                    $dx = md5($dx . $key . $salt, true);
                    $salted .= $dx;
                }
                $key = substr($salted, 0, 32);
                $iv = substr($salted, 32, 16);
                $gp = openssl_encrypt($generated_password, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
                $data->salt = bin2hex($salt);
                $data->generated_password = base64_encode($gp);
            } catch (\Exception $ex) {
                // the great logging experience
            }
        }

        $this->execute_trigger("customer_new_account", $data,null, true);
    }

    public function ce_email_notification_customer_reset_password($user_login = '', $reset_key = '')
    {
        if ($user_login && $reset_key ) {
            $data              = new stdClass();
            $user              = get_user_by('login', $user_login);
            $data->customer_id = $user->ID;
            $data->customer = $this->get_customer_data($user->ID);
            $data->account_url = $this->get_my_account_url();
            $data->reset_url   = add_query_arg(
                array(
                'key' => $reset_key,
                'id'  => $data->customer_id
                ), wc_get_endpoint_url('lost-password', '', $data->account_url)
            );

            $this->execute_trigger("customer_reset_password", $data, null, true);
        }
    }

    public function ce_email_notification_payment_complete( $order_id )
    {
        $data = new stdClass();
        $data->order_id = $order_id;
        $data->order_url = $this->get_view_order_url($order_id, null);

        $this->execute_trigger("payment_received", $data, wc_get_order($order_id));
    }

    public function ce_email_notification_failed($order_id, $order)
    {
        $data = new stdClass();
        $data->order_id = $order_id;
        $data->order_url = $this->get_view_order_url($order_id, $order);

        $this->execute_trigger("failed_order", $data, $order);
    }
    public function ce_email_notification_hold($order_id, $order)
    {
        $data = new stdClass();
        $data->order_id = $order_id;
        $data->order_url = $this->get_view_order_url($order_id, $order);

        $this->execute_trigger("customer_on_hold_order", $data, $order);
    }
    public function ce_email_notification_processing($order_id, $order)
    {
        $data = new stdClass();
        $data->order_id = $order_id;
        $data->order_url = $this->get_view_order_url($order_id, $order);

        $this->execute_trigger("customer_processing_order", $data, $order);
    }
    public function ce_email_notification_completed($order_id, $order)
    {
        $data = new stdClass();
        $data->order_id = $order_id;
        $data->order_url = $this->get_view_order_url($order_id, $order);

        $this->execute_trigger("customer_completed_order", $data, $order);
    }
    public function ce_email_notification_refunded($order_id, $order)
    {
        $data = new stdClass();
        $data->order_id = $order_id;
        $data->order_url = $this->get_view_order_url($order_id, $order);

        $this->execute_trigger("customer_refunded_order", $data, $order);
    }
    public function ce_email_notification_cancelled($order_id, $order)
    {
        $data = new stdClass();
        $data->order_id = $order_id;
        $data->order_url = $this->get_view_order_url($order_id, $order);

        $this->execute_trigger("cancelled_order", $data, $order);
    }

    public function ce_email_notification_new_order($order_id, $order)
    {
        $data = new stdClass();
        $data->order_id = $order_id;
        $data->order_url = $this->get_view_order_url($order_id, $order);

        $this->execute_trigger("new_order", $data, $order);
    }

    public function ce_email_notification_invoice($order, $type)
    {
        if ($type === 'new_order' ) {
            $this->ce_email_notification_new_order($order->id, $order);
            return;
        }

        $data            = new stdClass();
        $data->order_id  = $order->get_id();
        $data->order_url = $this->get_view_order_url($order->get_id(), $order);

        $this->execute_trigger("customer_invoice", $data, $order);
    }

    public function execute_trigger($type, $data, $order = null, $with_data = false)
    {
        // if not managed do not trigger
        if (!$this->is_email_managed($type)) {
            return;
        }

        $requestItem = new stdClass();
        $requestItem->type = $type;

        if(!is_null($order)) {
            try {
                $dp = 2; // decimal point
                $order_data = array(
                    'id' => $order->get_id(),
                    'number' => $order->get_order_number(),
                    'date_created' => $order->get_date_created() ? $order->get_date_created()->getTimestamp() : 0,
                    'date_modified' => $order->get_date_modified() ? $order->get_date_modified()->getTimestamp() : 0,
                    'date_completed' => $order->get_date_completed() ? $order->get_date_completed()->getTimestamp() : 0,
                    'status' => $order->get_status(),
                    'currency' => $order->get_currency(),
                    'total' => wc_format_decimal($order->get_total(), $dp),
                    'subtotal' => wc_format_decimal($order->get_subtotal(), $dp),
                    'total_line_items_quantity' => $order->get_item_count(),
                    'total_tax' => wc_format_decimal($order->get_total_tax(), $dp),
                    'shipping_total' => wc_format_decimal($order->get_shipping_total(), $dp),
                    'cart_tax' => wc_format_decimal($order->get_cart_tax(), $dp),
                    'shipping_tax' => wc_format_decimal($order->get_shipping_tax(), $dp),
                    'discount_total' => wc_format_decimal($order->get_total_discount(), $dp),
                    'shipping_methods' => $order->get_shipping_method(),
                    'payment_details' => array(
                        'method_id' => $order->get_payment_method(),
                        'method_title' => $order->get_payment_method_title(),
                        'paid' => !is_null($order->get_date_paid()),
                    ),
                    'billing' => array(
                        'first_name' => $order->get_billing_first_name(),
                        'last_name' => $order->get_billing_last_name(),
                        'company' => $order->get_billing_company(),
                        'address_1' => $order->get_billing_address_1(),
                        'address_2' => $order->get_billing_address_2(),
                        'city' => $order->get_billing_city(),
                        'state' => $order->get_billing_state(),
                        'postcode' => $order->get_billing_postcode(),
                        'country' => $order->get_billing_country(),
                        'email' => $order->get_billing_email(),
                        'phone' => $order->get_billing_phone(),
                    ),
                    'shipping' => array(
                        'first_name' => $order->get_shipping_first_name(),
                        'last_name' => $order->get_shipping_last_name(),
                        'company' => $order->get_shipping_company(),
                        'address_1' => $order->get_shipping_address_1(),
                        'address_2' => $order->get_shipping_address_2(),
                        'city' => $order->get_shipping_city(),
                        'state' => $order->get_shipping_state(),
                        'postcode' => $order->get_shipping_postcode(),
                        'country' => $order->get_shipping_country(),
                    ),
                    'customer_note' => $order->get_customer_note(),
                    'customer_ip' => $order->get_customer_ip_address(),
                    'customer_user_agent' => $order->get_customer_user_agent(),
                    'customer_id' => $order->get_user_id(),
                    'view_order_url' => $order->get_view_order_url(),
                    'line_items' => array(),
                    'shipping_lines' => array(),
                    'tax_lines' => array(),
                    'fee_lines' => array(),
                    'coupon_lines' => array()
                );

                // add line items
                foreach ($order->get_items() as $item_id => $item) {
                    $product = $item->get_product();
                    $item_meta = $item->get_formatted_meta_data();

                    foreach ($item_meta as $key => $values) {
                        $item_meta[$key]->label = $values->display_key;
                        unset($item_meta[$key]->display_key);
                        unset($item_meta[$key]->display_value);
                    }

                    try {

                        $product_data = array(
                            'images' => array(),
                            'downloads' => array()
                        );
                        $attachment_ids = $product->get_gallery_image_ids();
                        foreach ($attachment_ids as $attachment_id) {
                            $product_data['images'][] = wp_get_attachment_url($attachment_id);
                        }

                        $product_data["on_sale"] = $product->is_on_sale();
                        $product_data["sale_price"] = $product->get_sale_price();
                        $product_data["regular_price"] = $product->get_regular_price();

                        if ($product->is_downloadable()) {
                            $item_downloads = $item->get_item_downloads();
                            foreach ($item_downloads as $item_download)
                            {
                                $product_data["downloads"][] = array(
                                    'line_item_id' => $item->get_id(),
                                    'product_id' => $item->get_product_id(),
                                    'download_url' => $item_download["download_url"],
                                    'download_file' => $item_download["file"],
                                    'download_name' => $item_download["name"],
                                    'download_id' => $item_download["id"],
                                    'downloads_remaining' => $item_download["downloads_remaining"],
                                    'download_access_expires' => wc_format_datetime($item_download["access_expires"], 'U'),
                                    'download_limit' => $product->get_download_limit(),
                                    'download_expiry' => $product->get_download_expiry(),
                                );
                            }
                        }

                    } catch (\Exception $exc)
                    {
                        // unable to get this data
                    }

                    $src = wc_placeholder_img_src();
                    if ($image_id = $product->get_image_id() ) {
                        list( $src ) = wp_get_attachment_image_src($image_id, 'full');
                    }

                    $order_data['line_items'][] = array(
                        'id' => $item_id,
                        'subtotal' => wc_format_decimal($order->get_line_subtotal($item, false, false), $dp),
                        'subtotal_tax' => wc_format_decimal($item->get_subtotal_tax(), $dp),
                        'total' => wc_format_decimal($order->get_line_total($item, false, false), $dp),
                        'total_tax' => wc_format_decimal($item->get_total_tax(), $dp),
                        'price' => wc_format_decimal($order->get_item_total($item, false, false), $dp),
                        'quantity' => $item->get_quantity(),
                        'tax_class' => $item->get_tax_class(),
                        'name' => $item->get_name(),
                        'product_id' => $item->get_product_id(),
                        'product_image' => $src,
                        'product_data' => $product_data,
                        'sku' => is_object($product) ? $product->get_sku() : null,
                        'meta' => array_values($item_meta),
                        'product_url' => get_the_permalink($item->get_product_id()),
                        'variation_id' => $item->get_variation_id()
                    );
                }

                // add shipping
                foreach ($order->get_shipping_methods() as $shipping_item_id => $shipping_item) {
                    $order_data['shipping_lines'][] = array(
                        'id' => $shipping_item_id,
                        'method_id' => $shipping_item->get_method_id(),
                        'method_title' => $shipping_item->get_name(),
                        'total' => wc_format_decimal($shipping_item->get_total(), $dp),
                    );
                }

                // add taxes
                foreach ($order->get_tax_totals() as $tax_code => $tax) {
                    $order_data['tax_lines'][] = array(
                        'id' => $tax->id,
                        'rate_id' => $tax->rate_id,
                        'code' => $tax_code,
                        'title' => $tax->label,
                        'total' => wc_format_decimal($tax->amount, $dp),
                        'compound' => (bool)$tax->is_compound,
                    );
                }

                // add fees
                foreach ($order->get_fees() as $fee_item_id => $fee_item) {
                    $order_data['fee_lines'][] = array(
                        'id' => $fee_item_id,
                        'title' => $fee_item->get_name(),
                        'tax_class' => $fee_item->get_tax_class(),
                        'total' => wc_format_decimal($order->get_line_total($fee_item), $dp),
                        'total_tax' => wc_format_decimal($order->get_line_tax($fee_item), $dp),
                    );
                }

                // add coupons
                foreach ($order->get_items('coupon') as $coupon_item_id => $coupon_item) {
                    $order_data['coupon_lines'][] = array(
                        'id' => $coupon_item_id,
                        'code' => $coupon_item->get_code(),
                        'amount' => wc_format_decimal($coupon_item->get_discount(), $dp),
                    );
                }
                $data->order = $order_data;
                $with_data = true;
            }
            catch (\Exception $ex) {
                // something failed here
                $with_data = false;
            }
        }

        $requestItem->data = wp_json_encode($data);
        $endpoint = EnvironmentHelper::get_app_gateway_url('wordpress').'/v1.0/wc/trigger';
        if ($with_data)
        {
            $endpoint = EnvironmentHelper::get_app_gateway_url('wordpress') . '/v1.0/wc/trigger-with-data';
        }

        wp_remote_post(
            $endpoint, array(
            'method' => 'POST',
            'timeout' => 10,
            'headers' => array(
                'x-account-id' => OptionsHelper::get_connected_account_id(),
                'x-api-key' => OptionsHelper::get_instance_api_key(),
                'content-type' => 'application/json'
            ),
            'body' => wp_json_encode($requestItem)
            )
        );
    }

    /**
     * Initializes email management.
     *
     * @internal
     *
     * @since 1.1.0
     */
    public function manage_emails()
    {

        $this->managed_email_notifications = $this->get_managed_email_notifications();

        if (empty($this->managed_email_notifications) || ! is_array($this->managed_email_notifications) ) {
            return;
        }

        // disable managed emails
        foreach ( $this->managed_email_notifications as $notification )
        {
            if ($this->is_email_managed($notification->name) ) {
                add_filter("woocommerce_email_enabled_". $notification->name ."", '__return_false');
            }
        }

        add_filter('woocommerce_email_title',       array( $this, 'override_managed_email_title' ), 10, 2);
        add_filter('woocommerce_email_description', array( $this, 'override_managed_email_description' ), 10, 2);
    }


    /**
     * Overrides email titles for managed emails.
     *
     * @param string    $title the email title
     * @param \WC_Email $email the email object
     *
     * @internal
     * @since    1.1.0
     *
     * @return string
     */
    public function override_managed_email_title( $title, $email )
    {

        if (isset($email->id) && $this->is_email_managed($email->id) ) {

            $title .= __(' (Managed by Creative Mail)', 'ce4wp');
        }

        return $title;
    }


    /**
     * Overrides email description for managed emails.
     *
     * @param string    $description description text
     * @param \WC_Email $email       the email object
     *
     * @internal
     * @since    1.1.0
     * @return   string
     */
    public function override_managed_email_description( $description, $email )
    {

        if (isset($email->id) && $this->is_email_managed($email->id) ) {

            $description .= __(' This email is being managed and sent by Creative Mail.', 'ce4wp');
        }

        return $description;
    }

    /**
     * Redirects the settings page of a managed email to the CreativeMail transactional notification for that email.
     *
     * @param \WC_Email $email the email object
     *
     * @since 1.1.0
     */
    public function redirect_managed_email_settings_to_creative_mail( $email )
    {

        if ($this->is_email_managed($email->id)) {
            wp_redirect(admin_url('admin.php?page=creativemail'));
            exit;
        }
    }

    /**
     * Checks if a given email ID is being managed by CreativeMail and is active.
     *
     * @param string $email_id woocommerce email ID
     *
     * @since  1.1.0
     * @return bool
     */
    public function is_email_managed( $email_id )
    {
        return (bool) $this->get_managed_notification_param($email_id, 'active');
    }

    /**
     * Gets a param from the managed email notification for the given email ID.
     *
     * @param string $email_id woocommerce email ID
     * @param string $param    param name
     *
     * @since 1.1.0
     *
     * @return mixed|null
     */
    public function get_managed_notification_param( $email_id, $param )
    {

        foreach($this->managed_email_notifications as $managed_email_notification) {
            if ($email_id == $managed_email_notification->name && property_exists($managed_email_notification, $param)) {
                return $managed_email_notification->$param;
            }
        }
        return null;
    }

    /**
     * Gets the managed email notification for the given email ID.
     *
     * @param array  $items    managed email notifications
     * @param string $email_id woocommerce email ID
     *
     * @since  1.1.0
     * @return mixed|null
     */
    public function get_managed_notification( $items, $email_id )
    {

        foreach($items as $managed_email_notification) {
            if ($email_id == $managed_email_notification->name) {
                return $managed_email_notification;
            }
        }
        return null;
    }

    /**
     * Gets the transactional notification ID for a given notification.
     *
     * @param string $email_id woocommerce email ID
     *
     * @since 1.1.0
     *
     * @return int|null
     */
    public function get_transactional_notification_id( $email_id )
    {

        return $this->get_managed_notification_param($email_id, 'transactional_notification_id');
    }

    /**
     * Gets the transactional notification state.
     *
     * @param string $email_id woocommerce email ID
     *
     * @return string|null
     * @since  1.1.0
     */
    public function get_managed_notification_state( $email_id )
    {

        return $this->get_managed_notification_param($email_id, 'state');
    }

    public function get_valid_email_notification_names()
    {
        return $this->valid_email_notification_names;
    }

    private function get_view_order_url($order_id, $order)
    {
        try {
            if (!isset($order)) {
                $order = wc_get_order($order_id);
            }

            if (isset($order) && method_exists($order, 'get_view_order_url') ) {
                return $order->get_view_order_url();
            }
        } catch ( \Exception $exception ) {
            // silent exception
        }

        return null;
    }

    private function get_my_account_url()
    {
        try {
            return wc_get_page_permalink('myaccount');
        } catch ( \Exception $exception ) {
            // silent exception
        }

        return null;
    }

    private function get_customer_data($customer_id)
    {
        try {
            $customer = new \WC_Customer( $customer_id );

            $data = $customer->get_data();

            if ($data['date_created'] != null) {
                $data['date_created'] = $customer->get_date_created()->getTimestamp();
            }
            if ($data['date_modified'] != null) {
                $data['date_modified'] = $customer->get_date_modified()->getTimestamp();
            }

            return $data;
        } catch ( \Exception $exception ) {
            // silent exception
        }
        return null;
    }
}
