get_settings(); if ( 'yes' !== $s['enabled'] ) { return; } if ( did_action( 'woocommerce_init' ) && function_exists( 'woocommerce_register_additional_checkout_field' ) ) { $this->register_field( $s ); } elseif ( ! did_action( 'woocommerce_init' ) ) { add_action( 'woocommerce_init', function () use ( $s ) { $this->register_field( $s ); }, 20 ); } else { add_action( 'woocommerce_blocks_loaded', function () use ( $s ) { $this->register_field( $s ); } ); } if ( 'yes' === $s['default_checked'] ) { add_filter( 'woocommerce_get_default_value_for_' . self::FIELD_ID, array( $this, 'default_checked_value' ), 10, 3 ); } add_action( 'woocommerce_store_api_checkout_order_processed', array( $this, 'apply_from_order' ), 20, 1 ); } private function register_field( $s ) { try { woocommerce_register_additional_checkout_field( array( 'id' => self::FIELD_ID, 'label' => (string) $s['text'], 'location' => 'order', 'type' => 'checkbox', 'required' => false, ) ); } catch ( \Throwable $e ) { unset( $e ); } } public function default_checked_value( $value, $group, $wc_object ) { if ( ! is_user_logged_in() ) { return '1'; } $u = wp_get_current_user(); $email = (string) ( $u->user_email ?? '' ); if ( '' !== $email && class_exists( 'AIEO_Contact_Consent' ) && ! AIEO_Contact_Consent::is_opted_in( $email ) ) { return $value; } return '1'; } public function apply_from_order( $order ) { if ( ! is_a( $order, 'WC_Order' ) ) { return; } if ( '1' !== (string) $order->get_meta( self::META_KEY ) ) { return; } if ( 'done' === (string) $order->get_meta( self::DONE_META ) ) { return; } $email = (string) $order->get_billing_email(); if ( '' === $email ) { return; } if ( class_exists( 'AIEO_Contact_Consent' ) ) { AIEO_Contact_Consent::set_email_marketing( $email, true, 'checkout' ); } $s = $this->get_settings(); if ( 'yes' === $s['subscribe_newsletter'] && class_exists( 'AIEO_Newsletter_Manager' ) && AIEO_Newsletter_Manager::available() && ! AIEO_Newsletter_Manager::exists( $email ) ) { $lists = array_map( 'strval', (array) $s['newsletter_lists'] ); AIEO_Newsletter_Manager::save( $email, true, $lists, array( 'first' => (string) $order->get_billing_first_name(), 'last' => (string) $order->get_billing_last_name(), ) ); } $order->update_meta_data( self::DONE_META, 'done' ); $order->save(); } private function get_settings() { $stored = get_option( self::OPTION_KEY, array() ); if ( ! is_array( $stored ) ) { $stored = array(); } return self::fill_i18n_defaults( array_merge( array( 'enabled' => 'no', 'default_checked' => 'no', 'subscribe_newsletter' => 'no', 'newsletter_lists' => array(), 'text' => '', ), $stored ) ); } private static function fill_i18n_defaults( array $s ) { if ( ! did_action( 'init' ) ) { return $s; } $i18n = array( 'text' => __( 'I want to receive updates about new products and offers!', 'ai-eshop-optimizer' ), ); foreach ( $i18n as $k => $v ) { if ( ! isset( $s[ $k ] ) || '' === trim( (string) $s[ $k ] ) ) { $s[ $k ] = $v; } } return $s; } } }