<?php
/**
 * Billing actions and middleware integration helpers for SiteStaffr admin.
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/admin
 */

if ( ! defined( 'WPINC' ) ) {
    die;
}

trait SiteStaffr_Admin_Billing_Trait {

    /**
     * Handle explicit admin-requested billing cache refresh.
     *
     * Uses a nonce-protected admin-post action so cache refresh is on-demand
     * instead of forced on every render path request.
     *
     * @since 0.14.256
     * @return void
     */
    public function handle_refresh_billing_cache_action() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'sitestaffr' ) );
        }

        check_admin_referer( 'sitestaffr_refresh_billing_cache' );

        $return_page = isset( $_POST['return_page'] ) ? sanitize_key( wp_unslash( $_POST['return_page'] ) ) : 'sitestaffr-usage';
        if ( ! in_array( $return_page, array( 'sitestaffr', 'sitestaffr-usage' ), true ) ) {
            $return_page = 'sitestaffr-usage';
        }

        $redirect_url = admin_url( 'admin.php?page=' . $return_page );
        if ( 'sitestaffr-usage' === $return_page ) {
            $cycle_offset = isset( $_POST['cycle_offset'] ) ? absint( wp_unslash( $_POST['cycle_offset'] ) ) : 0;
            if ( $cycle_offset > 0 ) {
                $redirect_url = add_query_arg( 'cycle_offset', $cycle_offset, $redirect_url );
            }
        }

        $refreshed = false;
        if ( class_exists( 'SiteStaffr_Billing_State' ) ) {
            $refreshed = SiteStaffr_Billing_State::maybe_refresh_cache( true );
        }

        if ( 'sitestaffr' === $return_page ) {
            $redirect_url = add_query_arg( 'message', $refreshed ? 'billing_cache_refreshed' : 'billing_cache_refresh_failed', $redirect_url );
        } else {
            $redirect_url = add_query_arg( $refreshed ? 'billing_message' : 'billing_error', $refreshed ? 'cache_refreshed' : 'cache_refresh_failed', $redirect_url );
            $redirect_url = wp_nonce_url( $redirect_url, 'sitestaffr_usage_nav' );
        }

        wp_safe_redirect( $redirect_url );
        exit;
    }

    /**
     * Handle Usage page billing checkout requests.
     *
     * Creates a Stripe Checkout session via middleware and redirects admin to Stripe.
     *
     * @since 0.14.12
     * @return void
     */
    public function handle_billing_checkout_action() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'sitestaffr' ) );
        }

        check_admin_referer( 'sitestaffr_billing_checkout' );

        $checkout_type = isset( $_POST['checkout_type'] ) ? sanitize_key( wp_unslash( $_POST['checkout_type'] ) ) : '';
        $account_id    = get_option( 'sitestaffr_account_id', '' );

        if ( empty( $account_id ) ) {
            wp_safe_redirect( $this->get_billing_admin_redirect_url( array( 'billing_error' => 'missing_account' ) ) );
            exit;
        }

        if ( ! in_array( $checkout_type, array( 'subscription', 'addon' ), true ) ) {
            wp_safe_redirect( $this->get_billing_admin_redirect_url( array( 'billing_error' => 'invalid_request' ) ) );
            exit;
        }

        $usage_url = admin_url( 'admin.php?page=sitestaffr-usage' );
        $payload   = array(
            'account_id'  => sanitize_text_field( $account_id ),
            'installation_id' => sanitize_text_field( get_option( 'sitestaffr_installation_id', '' ) ),
            'site_url'    => esc_url_raw( get_site_url() ),
            'type'        => $checkout_type,
            'success_url' => wp_nonce_url( add_query_arg( 'billing_message', 'checkout_success', $usage_url ), 'sitestaffr_usage_nav' ),
            'cancel_url'  => wp_nonce_url( add_query_arg( 'billing_message', 'checkout_canceled', $usage_url ), 'sitestaffr_usage_nav' ),
        );

        if ( 'subscription' === $checkout_type ) {
            $plan_name   = isset( $_POST['plan_name'] ) ? sanitize_key( wp_unslash( $_POST['plan_name'] ) ) : '';
            $valid_plans = array( 'starter', 'business', 'pro' );
            if ( ! in_array( $plan_name, $valid_plans, true ) ) {
                wp_safe_redirect( $this->get_billing_admin_redirect_url( array( 'billing_error' => 'invalid_plan' ) ) );
                exit;
            }
            $payload['plan_name'] = $plan_name;
        } else {
            $addon_type   = isset( $_POST['addon_type'] ) ? sanitize_key( wp_unslash( $_POST['addon_type'] ) ) : '';
            $valid_addons = array( 'minutes_50' );
            if ( ! in_array( $addon_type, $valid_addons, true ) ) {
                wp_safe_redirect( $this->get_billing_admin_redirect_url( array( 'billing_error' => 'invalid_addon' ) ) );
                exit;
            }
            $payload['addon_type'] = $addon_type;

            // Optional quantity (1–10). Defaults to 1 when not supplied or out of range.
            $quantity = isset( $_POST['quantity'] ) ? absint( wp_unslash( $_POST['quantity'] ) ) : 1;
            $quantity = max( 1, min( 10, $quantity ) );
            if ( $quantity > 1 ) {
                $payload['quantity'] = $quantity;
            }
        }

        $result = $this->post_billing_middleware_endpoint( '/api/billing/create-checkout-session', $payload );
        if ( is_wp_error( $result ) ) {
            wp_safe_redirect(
                $this->get_billing_admin_redirect_url(
                    array(
                        'billing_error' => 'request_failed',
                        'billing_code'  => sanitize_key( $result->get_error_code() ),
                    )
                )
            );
            exit;
        }

        $checkout_url = isset( $result['checkout_url'] ) ? esc_url_raw( $result['checkout_url'] ) : '';
        if ( empty( $checkout_url ) ) {
            wp_safe_redirect( $this->get_billing_admin_redirect_url( array( 'billing_error' => 'invalid_response' ) ) );
            exit;
        }

        $this->redirect_to_billing_url_or_fallback( $checkout_url );
    }

    /**
     * Handle Usage page billing portal requests.
     *
     * Creates a Stripe Customer Portal session via middleware and redirects admin.
     *
     * @since 0.14.12
     * @return void
     */
    public function handle_billing_portal_action() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'sitestaffr' ) );
        }

        check_admin_referer( 'sitestaffr_billing_portal' );

        $account_id = get_option( 'sitestaffr_account_id', '' );
        if ( empty( $account_id ) ) {
            wp_safe_redirect( $this->get_billing_admin_redirect_url( array( 'billing_error' => 'missing_account' ) ) );
            exit;
        }

        $payload = array(
            'account_id'      => sanitize_text_field( $account_id ),
            'installation_id' => sanitize_text_field( get_option( 'sitestaffr_installation_id', '' ) ),
            'site_url'        => esc_url_raw( get_site_url() ),
            'return_url'      => wp_nonce_url( add_query_arg( 'billing_message', 'portal_return', admin_url( 'admin.php?page=sitestaffr-usage' ) ), 'sitestaffr_usage_nav' ),
        );

        $result = $this->post_billing_middleware_endpoint( '/api/billing/create-portal-session', $payload );
        if ( is_wp_error( $result ) ) {
            wp_safe_redirect(
                $this->get_billing_admin_redirect_url(
                    array(
                        'billing_error' => 'request_failed',
                        'billing_code'  => sanitize_key( $result->get_error_code() ),
                    )
                )
            );
            exit;
        }

        $portal_url = isset( $result['portal_url'] ) ? esc_url_raw( $result['portal_url'] ) : '';
        if ( empty( $portal_url ) ) {
            wp_safe_redirect( $this->get_billing_admin_redirect_url( array( 'billing_error' => 'invalid_response' ) ) );
            exit;
        }

        $this->redirect_to_billing_url_or_fallback( $portal_url );
    }

    /**
     * Handle cancel-downgrade form submission.
     *
     * Proxies to middleware `POST /api/billing/cancel-downgrade` which reverts
     * the Stripe subscription price and clears `scheduled_downgrade_plan` in
     * Firestore. Redirects back to Usage & Billing page.
     *
     * @since 0.14.257
     * @return void
     */
    public function handle_cancel_downgrade_action() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'sitestaffr' ) );
        }

        check_admin_referer( 'sitestaffr_cancel_downgrade' );

        $account_id      = get_option( 'sitestaffr_account_id', '' );
        $installation_id = get_option( 'sitestaffr_installation_id', '' );

        if ( empty( $account_id ) ) {
            wp_safe_redirect( $this->get_billing_admin_redirect_url( array( 'billing_error' => 'missing_account' ) ) );
            exit;
        }

        $payload = array(
            'account_id'      => sanitize_text_field( $account_id ),
            'installation_id' => sanitize_text_field( $installation_id ),
            'site_url'        => esc_url_raw( get_site_url() ),
        );

        $result = $this->post_billing_middleware_endpoint( '/api/billing/cancel-downgrade', $payload );

        if ( is_wp_error( $result ) ) {
            wp_safe_redirect( $this->get_billing_admin_redirect_url( array( 'billing_error' => 'request_failed' ) ) );
            exit;
        }

        // Force-refresh billing cache so the page shows updated state
        if ( class_exists( 'SiteStaffr_Billing_State' ) ) {
            SiteStaffr_Billing_State::maybe_refresh_cache( true );
        }

        wp_safe_redirect( $this->get_billing_admin_redirect_url( array( 'billing_message' => 'downgrade_canceled' ) ) );
        exit;
    }

    /**
     * Build Usage page redirect URL for billing actions.
     *
     * @since 0.14.12
     * @param array $query_args Optional query args.
     * @return string
     */
    private function get_billing_admin_redirect_url( $query_args = array() ) {
        $url = admin_url( 'admin.php?page=sitestaffr-usage' );
        if ( ! empty( $query_args ) ) {
            $url = add_query_arg( $query_args, $url );
        }

        return wp_nonce_url( $url, 'sitestaffr_usage_nav' );
    }

    /**
     * AJAX handler: create a Stripe hosted Checkout session for the Setup Wizard.
     *
     * Expected POST fields: nonce, plan_name.
     *
     * @since 0.14.195
     * @return void Sends JSON response and exits.
     */
    public function ajax_create_wizard_checkout() {
        $nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
        if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, 'sitestaffr_setup_wizard' ) ) {
            wp_send_json_error( array( 'message' => __( 'Security check failed. Please refresh the page and try again.', 'sitestaffr' ) ) );
            return;
        }

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'sitestaffr' ) ), 403 );
            return;
        }

        $plan_name   = isset( $_POST['plan_name'] ) ? sanitize_key( wp_unslash( $_POST['plan_name'] ) ) : '';
        $valid_plans = array( 'starter', 'business', 'pro' );

        if ( ! in_array( $plan_name, $valid_plans, true ) ) {
            wp_send_json_error( array( 'message' => 'Invalid plan selected.' ) );
            return;
        }

        $account_id      = get_option( 'sitestaffr_account_id', '' );
        $installation_id = get_option( 'sitestaffr_installation_id', '' );
        $wizard_url      = admin_url( 'admin.php?page=sitestaffr-setup' );
        $payload = array(
            'account_id'      => sanitize_text_field( $account_id ),
            'installation_id' => sanitize_text_field( $installation_id ),
            'site_url'        => esc_url_raw( get_site_url() ),
            'type'            => 'subscription',
            'plan_name'       => $plan_name,
            'success_url'     => add_query_arg( 'checkout_complete', '1', $wizard_url ),
            'cancel_url'      => $wizard_url,
        );

        $result = $this->post_billing_middleware_endpoint( '/api/billing/create-checkout-session', $payload );

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
            return;
        }

        $checkout_url = isset( $result['checkout_url'] ) ? esc_url_raw( $result['checkout_url'] ) : '';
        if ( empty( $checkout_url ) ) {
            wp_send_json_error( array( 'message' => 'Failed to create checkout session.' ) );
            return;
        }

        wp_send_json_success(
            array(
                'checkoutUrl' => $checkout_url,
            )
        );
    }

    /**
     * AJAX handler: fetch a proration preview for a plan upgrade.
     *
     * Proxies to middleware `POST /api/billing/preview-upgrade` and returns the
     * preview data (proration amount, next renewal figures, minutes delta) as a
     * JSON success payload for the frontend upgrade modal.
     *
     * Expected POST fields: nonce, plan_name (starter|business|pro).
     *
     * @since 0.14.89
     * @return void Sends JSON response and exits.
     */
    public function ajax_preview_upgrade() {
        $nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
        if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, 'sitestaffr_billing_upgrade' ) ) {
            wp_send_json_error( array( 'message' => __( 'Security check failed. Please refresh the page and try again.', 'sitestaffr' ) ), 403 );
            return;
        }

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'sitestaffr' ) ), 403 );
            return;
        }

        $plan_name   = isset( $_POST['plan_name'] ) ? sanitize_key( wp_unslash( $_POST['plan_name'] ) ) : '';
        $valid_plans = array( 'starter', 'business', 'pro' );
        if ( ! in_array( $plan_name, $valid_plans, true ) ) {
            wp_send_json_error( array( 'message' => __( 'Invalid plan selected.', 'sitestaffr' ) ) );
            return;
        }

        $account_id      = get_option( 'sitestaffr_account_id', '' );
        $installation_id = get_option( 'sitestaffr_installation_id', '' );

        if ( empty( $account_id ) ) {
            wp_send_json_error( array( 'message' => __( 'Account not found. Please complete site registration.', 'sitestaffr' ) ) );
            return;
        }

        $payload = array(
            'account_id'      => sanitize_text_field( $account_id ),
            'installation_id' => sanitize_text_field( $installation_id ),
            'site_url'        => esc_url_raw( get_site_url() ),
            'target_plan'     => $plan_name,
        );

        $result = $this->post_billing_middleware_endpoint( '/api/billing/preview-upgrade', $payload );

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
            return;
        }

        // Strip the outer success wrapper — pass only the data object to the frontend.
        $preview = isset( $result['data'] ) ? $result['data'] : $result;
        wp_send_json_success( $preview );
    }

    /**
     * AJAX handler: initiate upgrade via Stripe Checkout session.
     *
     * Creates a new Stripe Checkout session for the target plan. The middleware
     * calculates prorated credit and applies it to the customer balance. On
     * checkout completion, the webhook cancels the old subscription.
     *
     * Expected POST fields: nonce, plan_name (starter|business|pro).
     *
     * @since 0.14.248
     * @return void Sends JSON response and exits.
     */
    public function ajax_execute_upgrade() {
        $nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
        if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, 'sitestaffr_billing_upgrade' ) ) {
            wp_send_json_error( array( 'message' => __( 'Security check failed. Please refresh the page and try again.', 'sitestaffr' ) ), 403 );
            return;
        }

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'sitestaffr' ) ), 403 );
            return;
        }

        $plan_name   = isset( $_POST['plan_name'] ) ? sanitize_key( wp_unslash( $_POST['plan_name'] ) ) : '';
        $valid_plans = array( 'starter', 'business', 'pro' );
        if ( ! in_array( $plan_name, $valid_plans, true ) ) {
            wp_send_json_error( array( 'message' => __( 'Invalid plan selected.', 'sitestaffr' ) ) );
            return;
        }

        $account_id      = get_option( 'sitestaffr_account_id', '' );
        $installation_id = get_option( 'sitestaffr_installation_id', '' );

        if ( empty( $account_id ) ) {
            wp_send_json_error( array( 'message' => __( 'Account not found. Please complete site registration.', 'sitestaffr' ) ) );
            return;
        }

        $usage_url = admin_url( 'admin.php?page=sitestaffr-usage' );
        $payload   = array(
            'account_id'      => sanitize_text_field( $account_id ),
            'installation_id' => sanitize_text_field( $installation_id ),
            'site_url'        => esc_url_raw( get_site_url() ),
            'type'            => 'subscription',
            'plan_name'       => $plan_name,
            'success_url'     => wp_nonce_url( add_query_arg( 'billing_message', 'checkout_success', $usage_url ), 'sitestaffr_usage_nav' ),
            'cancel_url'      => wp_nonce_url( add_query_arg( 'billing_message', 'checkout_canceled', $usage_url ), 'sitestaffr_usage_nav' ),
        );

        $result = $this->post_billing_middleware_endpoint( '/api/billing/create-checkout-session', $payload );

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
            return;
        }

        $checkout_url = isset( $result['checkout_url'] ) ? esc_url_raw( $result['checkout_url'] ) : '';
        if ( empty( $checkout_url ) ) {
            wp_send_json_error( array( 'message' => __( 'Failed to create checkout session.', 'sitestaffr' ) ) );
            return;
        }

        wp_send_json_success( array( 'checkout_url' => $checkout_url ) );
    }

    /**
     * AJAX handler: execute an instant subscription downgrade.
     *
     * Proxies to middleware `POST /api/billing/downgrade-subscription`. The plan
     * changes immediately via Stripe API with no proration. Customer keeps current
     * included minutes until the next renewal.
     *
     * Expected POST fields: nonce, plan_name (starter|business|pro).
     *
     * @since 0.14.248
     * @return void Sends JSON response and exits.
     */
    public function ajax_execute_downgrade() {
        $nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
        if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, 'sitestaffr_billing_upgrade' ) ) {
            wp_send_json_error( array( 'message' => __( 'Security check failed. Please refresh the page and try again.', 'sitestaffr' ) ), 403 );
            return;
        }

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'sitestaffr' ) ), 403 );
            return;
        }

        $plan_name   = isset( $_POST['plan_name'] ) ? sanitize_key( wp_unslash( $_POST['plan_name'] ) ) : '';
        $valid_plans = array( 'starter', 'business', 'pro' );
        if ( ! in_array( $plan_name, $valid_plans, true ) ) {
            wp_send_json_error( array( 'message' => __( 'Invalid plan selected.', 'sitestaffr' ) ) );
            return;
        }

        $account_id      = get_option( 'sitestaffr_account_id', '' );
        $installation_id = get_option( 'sitestaffr_installation_id', '' );

        if ( empty( $account_id ) ) {
            wp_send_json_error( array( 'message' => __( 'Account not found. Please complete site registration.', 'sitestaffr' ) ) );
            return;
        }

        $payload = array(
            'account_id'      => sanitize_text_field( $account_id ),
            'installation_id' => sanitize_text_field( $installation_id ),
            'site_url'        => esc_url_raw( get_site_url() ),
            'target_plan'     => $plan_name,
        );

        $result = $this->post_billing_middleware_endpoint( '/api/billing/downgrade-subscription', $payload );

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
            return;
        }

        wp_send_json_success( array( 'message' => __( 'Plan downgraded successfully. You keep your current minutes until renewal.', 'sitestaffr' ) ) );
    }

    /**
     * Post a signed billing request to middleware.
     *
     * @since 0.14.12
     * @param string $path    Endpoint path.
     * @param array  $payload Request payload.
     * @return array|WP_Error
     */
    private function post_billing_middleware_endpoint( $path, $payload ) {
        $api_secret = $this->get_billing_api_secret();
        if ( empty( $api_secret ) ) {
            return new WP_Error( 'missing_api_secret', __( 'Billing API secret is missing.', 'sitestaffr' ) );
        }

        $middleware_url = defined( 'SITESTAFFR_MIDDLEWARE_URL' ) ? SITESTAFFR_MIDDLEWARE_URL : '';
        if ( empty( $middleware_url ) ) {
            return new WP_Error( 'missing_middleware_url', __( 'Middleware URL is missing.', 'sitestaffr' ) );
        }

        $payload_json = wp_json_encode( $payload );
        if ( false === $payload_json ) {
            return new WP_Error( 'encode_failed', __( 'Failed to encode billing request payload.', 'sitestaffr' ) );
        }

        $timestamp     = (string) time();
        $payload_to_sign = $timestamp . '.' . $payload_json;
        $signature_raw = hash_hmac( 'sha256', $payload_to_sign, $api_secret, true );
        $signature_b64 = base64_encode( $signature_raw );

        $site_url_header = '';
        if ( ! empty( $payload['site_url'] ) ) {
            $site_url_header = esc_url_raw( $payload['site_url'] );
        } else {
            $site_url_header = esc_url_raw( get_site_url() );
        }

        $response = wp_remote_post(
            rtrim( $middleware_url, '/' ) . $path,
            array(
                'timeout' => 12,
                'headers' => array(
                    'Content-Type'          => 'application/json',
                    'X-SiteStaffr-Signature' => $signature_b64,
                    'X-SiteStaffr-Timestamp' => $timestamp,
                    'X-SiteStaffr-Site-URL'  => $site_url_header,
                ),
                'body'    => $payload_json,
            )
        );

        if ( is_wp_error( $response ) ) {
            return $response;
        }

        $code = wp_remote_retrieve_response_code( $response );
        $body = wp_remote_retrieve_body( $response );
        $data = json_decode( $body, true );

        if ( $code < 200 || $code >= 300 ) {
            return new WP_Error(
                'http_' . $code,
                sprintf(
                    /* translators: %d: HTTP status code */
                    __( 'Billing middleware returned HTTP %d.', 'sitestaffr' ),
                    (int) $code
                ),
                is_array( $data ) ? $data : array( 'raw' => $body )
            );
        }

        if ( ! is_array( $data ) || empty( $data['success'] ) ) {
            return new WP_Error( 'invalid_payload', __( 'Billing middleware returned an invalid payload.', 'sitestaffr' ) );
        }

        return $data;
    }

    /**
     * Redirect to Stripe-hosted billing URL with host validation.
     *
     * Uses wp_safe_redirect with an explicit per-request host allowlist.
     *
     * @since 0.14.14
     * @param string $url Destination URL from middleware.
     * @return void
     */
    private function redirect_to_billing_url_or_fallback( $url ) {
        $clean_url = esc_url_raw( $url );
        $host      = wp_parse_url( $clean_url, PHP_URL_HOST );
        $host      = is_string( $host ) ? strtolower( $host ) : '';

        // Allow Stripe-hosted checkout/portal links only.
        if ( ! empty( $host ) && preg_match( '/(^|\\.)stripe\\.com$/', $host ) ) {
            $allow_stripe_host = static function( $allowed_hosts ) use ( $host ) {
                if ( ! is_array( $allowed_hosts ) ) {
                    $allowed_hosts = array();
                }
                $allowed_hosts[] = $host;
                return array_values( array_unique( array_filter( $allowed_hosts ) ) );
            };

            add_filter( 'allowed_redirect_hosts', $allow_stripe_host );
            $did_redirect = wp_safe_redirect( $clean_url );
            remove_filter( 'allowed_redirect_hosts', $allow_stripe_host );

            if ( $did_redirect ) {
                exit;
            }
        }

        wp_safe_redirect(
            $this->get_billing_admin_redirect_url(
                array(
                    'billing_error' => 'invalid_redirect_host',
                )
            )
        );
        exit;
    }

    /**
     * Resolve API secret used for middleware HMAC signing.
     *
     * @since 0.14.12
     * @return string
     */
    private function get_billing_api_secret() {
        $site_api_secret = get_option( 'sitestaffr_site_api_secret' );
        if ( ! empty( $site_api_secret ) ) {
            return $site_api_secret;
        }

        $global_api_secret = get_option( 'sitestaffr_api_secret' );
        if ( ! empty( $global_api_secret ) ) {
            return $global_api_secret;
        }

        return '';
    }

}
