<?php
/**
 * Helper database class.
 *
 * @package SaveToWishlist\Helpers
 * @since 1.0.0
 */
namespace SaveToWishlist\Helpers;

use SaveToWishlist\Abstracts\Singleton;

/**
 * Class Helper_Functions
 *
 * This class serves as the helper functions class.
 */
class Helper_Functions extends Singleton {
    /**
     * The basename of the pro plugin.
     *
     * @since 1.0.3
     * @access public
     * @var string
     */
    public $plugin_pro_basename = 'saveto-wishlist-pro-for-woocommerce/saveto-wishlist-pro-for-woocommerce.php';

    /**
     * Constructor.
     *
     * @since 1.0.0
     * @access public
     */
    public function __construct() {}

    /**
     * Get array values.
     *
     * @param array $allowed_html Allowed HTML.
     *
     * @since  1.0.0
     * @access public
     * @return array
     */
    public function get_array_values( $allowed_html ) {
        $values = array_values( $allowed_html );

        $arrays = array();
        foreach ( $values as $key => $value ) {
            if ( ! empty( $value ) && is_array( $value ) ) {
                array_push( $arrays, array_keys( $value ) );
            }
        }

        return $arrays;
    }

    /**
     * Get all published WordPress pages and add them as options.
     *
     * @since  1.0.0
     * @access public
     * @return array
     */
    public function get_all_published_pages() {
        $pages = get_posts(
            array(
                'post_type'      => 'page',
                'post_status'    => 'publish',
                'posts_per_page' => -1,
                'orderby'        => 'title',
                'order'          => 'ASC',
            )
        );

        $page_options = array( '' => __( 'Select Page', 'saveto-wishlist-lite-for-woocommerce' ) );
        if ( ! empty( $pages ) ) {
            foreach ( $pages as $page ) {
                $page_options[ $page->ID ] = $page->post_title;
            }
        }

        // Filter to modify page options.
        $page_options = apply_filters( 'stwlite_get_all_published_pages', $page_options );

        return $page_options;
    }

    /**
     * Get products.
     *
     * @param array $params Parameters.
     *
     * @since  1.0.0
     * @access public
     * @return array
     */
    public function get_products( $params = array() ) {
        $default_params = array(
            'status'   => 'publish',
            'limit'    => -1,
            'paginate' => false,
            'return'   => 'objects',
            'orderby'  => 'date',
            'order'    => 'DESC',
        );

        $params = wp_parse_args( $params, $default_params );
        $params = apply_filters( 'stwlite_get_products_params', $params );

        // Get products.
        $products = wc_get_products( $params );

        // Filter to modify products.
        $products = apply_filters( 'stwlite_get_products', $products );

        return $products;
    }

    /**
     * Get WooCommerce currency.
     *
     * @since  1.0.0
     * @access public
     * @return array
     */
    public function get_wc_currency() {
        return array(
            'currency'        => get_woocommerce_currency(),
            'currency_symbol' => get_woocommerce_currency_symbol(),
            'decimals'        => wc_get_price_decimals(),
        );
    }

    /**
     * Format attributes.
     *
     * @param array $attributes The attributes.
     *
     * @since 1.0.0
     * @access public
     * @return string
     */
    public function format_attributes( $attributes ) {
        $attribute_string = '';
        if ( ! empty( $attributes ) ) {
            foreach ( $attributes as $key => $value ) {
                $attribute_string .= ' ' . $key . '="' . esc_attr( $value ) . '"';
            }
        }

        return $attribute_string;
    }

    /**
     * Filter array by params.
     *
     * @param array $data The data.
     * @param array $params The params.
     *
     * @since 1.0.0
     * @access public
     * @return array
     */
    public function filter_array_by_params( $data, $params ) {
        return array_filter(
            $data,
            function ( $key ) use ( $params ) {
                return in_array( $key, array_keys( $params ), true );
            },
            ARRAY_FILTER_USE_KEY
        );
    }

    /**
     * Get admin user ids.
     *
     * @since 1.0.0
     * @access public
     * @return array
     */
    public function get_admin_user_ids() {
        $admin_users = get_users(
            array(
                'role'   => 'administrator',
                'fields' => 'ID',
            )
        );

        $admin_user_ids = apply_filters( 'stwlite_get_admin_user_ids', $admin_users );

        return $admin_user_ids;
    }

    /**
     * Get allowed html for wishlist button.
     *
     * @since 1.0.0
     * @access public
     * @return array
     */
    public function get_allowed_button_html() {
        $allowed_html = array(
            'div'    => array(
                'class'           => true,
                'data-product-id' => true,
                'id'              => true,
            ),
            'button' => array(
                'class'           => true,
                'data-product-id' => true,
                'style'           => true,
                'disabled'        => true,
                'title'           => true,
            ),
            'span'   => array(
                'class'      => true,
                'data-label' => true,
            ),
            'i'      => array(
                'class' => true,
            ),
            'select' => array(
                'name'            => true,
                'id'              => true,
                'class'           => true,
                'data-product-id' => true,
            ),
            'option' => array(
                'value' => true,
            ),
            'svg'    => array(
                'class'   => true,
                'viewBox' => true,
                'width'   => true,
                'height'  => true,
            ),
            'path'   => array(
                'fill'      => true,
                'fill-rule' => true,
                'd'         => true,
                'clip-rule' => true,
                'xmlns'     => true,
            ),
        );

        $allowed_html = apply_filters( 'stwlite_allowed_button_html', $allowed_html );

        return $allowed_html;
    }

    /**
     * Get allowed html for wishlist cart button.
     *
     * @since 1.0.0
     * @access public
     * @return array
     */
    public function get_allowed_cart_button_html() {
        $allowed_html = array(
            'div'      => array(
                'class'           => true,
                'data-product-id' => true,
            ),
            'button'   => array(
                'class'           => true,
                'data-product-id' => true,
                'style'           => true,
                'disabled'        => true,
                'title'           => true,
            ),
            'span'     => array(
                'class'      => true,
                'data-label' => true,
            ),
            'i'        => array(
                'class' => true,
            ),
            'select'   => array(
                'name'            => true,
                'id'              => true,
                'class'           => true,
                'data-product-id' => true,
            ),
            'option'   => array(
                'value' => true,
            ),
            'svg'      => array(
                'class'   => true,
                'viewbox' => true,
                'width'   => true,
                'height'  => true,
                'xmlns'   => true,
                'fill'    => true,
            ),
            'g'        => array(
                'clip-path' => true,
            ),
            'defs'     => array(),
            'clippath' => array(
                'id' => true,
            ),
            'rect'     => array(
                'width'  => true,
                'height' => true,
                'fill'   => true,
            ),
            'path'     => array(
                'fill'      => true,
                'fill-rule' => true,
                'd'         => true,
                'clip-rule' => true,
                'xmlns'     => true,
            ),
        );

        $allowed_html = apply_filters( 'stwlite_allowed_cart_button_html', $allowed_html );

        return $allowed_html;
    }

    /**
     * Check if a plugin exists on WordPress.org
     *
     * @param string $plugin_slug The plugin slug.
     *
     * @since 1.0.0.2
     * @access public
     *
     * @return bool
     */
    public static function plugin_exists_on_wporg( $plugin_slug ) {
        // These plugins are known to exist on WordPress.org.
        $known_plugins = array(
            'advanced-coupons-for-woocommerce-free' => true,
            'woocommerce-wholesale-prices'          => true,
            'wc-vendors'                            => true,
            'storeagent-ai-for-woocommerce'         => true,
            'invoice-gateway-for-woocommerce'       => true,
            'woo-product-feed-pro'                  => true,
            'funnelkit-stripe-woo-payment-gateway'  => true,
            'woocommerce-store-toolkit'             => true,
            'woocommerce-exporter'                  => true,
            // Add more as needed.
        );

        // If it's a known plugin, return true.
        if ( isset( $known_plugins[ $plugin_slug ] ) ) {
            return true;
        }

        // For unknown plugins, we'll assume they exist.
        return true;
    }

    /**
     * Get the WordPress.org plugin icon URL
     *
     * @param string $plugin_slug The plugin slug.
     * @param int    $size        The icon size (default: 128).
     *
     * @since 1.0.0.2
     * @access public
     *
     * @return string
     */
    public static function get_wp_org_plugin_icon_url( $plugin_slug, $size = 128 ) {
        // Default fallback icon.
        $default_icon = STWLITE_IMG_URL . 'savetowishlist-sm-logo.svg';

        // If the plugin doesn't exist on WordPress.org, return the default icon.
        if ( ! self::plugin_exists_on_wporg( $plugin_slug ) ) {
            return $default_icon;
        }

        // Known plugins with specific icon formats.
        $icon_formats = array(
            'invoice-gateway-for-woocommerce' => 'jpg',
            'woocommerce-wholesale-prices'    => 'jpg',
            // Add more as needed.
        );

        // Determine the file extension based on our known list or default to PNG.
        $extension = isset( $icon_formats[ $plugin_slug ] ) ? $icon_formats[ $plugin_slug ] : 'png';

        // Build the icon URL with dimensions.
        $icon_url = sprintf(
            'https://ps.w.org/%s/assets/icon-%dx%d.%s',
            $plugin_slug,
            $size,
            $size,
            $extension
        );

        return $icon_url;
    }

    /**
     * Check if ACFWF is installed
     *
     * @since 1.0.0.2
     *
     * @return bool
     */
    public static function is_acfwf_installed() {

        $plugin_file = 'advanced-coupons-for-woocommerce-free/advanced-coupons-for-woocommerce-free.php';
        $acfwf_file  = trailingslashit( WP_PLUGIN_DIR ) . plugin_basename( $plugin_file );

        return file_exists( $acfwf_file );
    }

    /**
     * Check if WWP is installed
     *
     * @since  1.0.0.2
     * @access public
     *
     * @return bool
     */
    public static function is_wwp_installed() {

        $plugin_file = 'woocommerce-wholesale-prices/woocommerce-wholesale-prices.bootstrap.php';
        $wwp_file    = trailingslashit( WP_PLUGIN_DIR ) . plugin_basename( $plugin_file );

        return file_exists( $wwp_file );
    }

    /**
     * Check if WWPP is installed
     *
     * @since  1.0.0.2
     * @access public
     *
     * @return bool
     */
    public static function is_wwpp_installed() {

        $plugin_file = 'woocommerce-wholesale-prices-premium/woocommerce-wholesale-prices-premium.bootstrap.php';
        $wwpp_file   = trailingslashit( WP_PLUGIN_DIR ) . plugin_basename( $plugin_file );

        return file_exists( $wwpp_file );
    }

    /**
     * Check if WWOF is installed
     *
     * @since  1.0.0.2
     * @access public
     *
     * @return bool
     */
    public static function is_wwof_installed() {

        $plugin_file = 'woocommerce-wholesale-order-form/woocommerce-wholesale-order-form.bootstrap.php';
        $wwof_file   = trailingslashit( WP_PLUGIN_DIR ) . plugin_basename( $plugin_file );

        return file_exists( $wwof_file );
    }

    /**
     * Check if WWLC is installed
     *
     * @since  1.0.0.2
     * @access public
     *
     * @return bool
     */
    public static function is_wwlc_installed() {

        $plugin_file = 'woocommerce-wholesale-lead-capture/woocommerce-wholesale-lead-capture.bootstrap.php';
        $wwlc_file   = trailingslashit( WP_PLUGIN_DIR ) . plugin_basename( $plugin_file );

        return file_exists( $wwlc_file );
    }

    /**
     * Check if WPAY is installed
     *
     * @since   1.0.0.2
     *
     * @return bool
     */
    public static function is_wpay_installed() {

        $plugin_file = 'woocommerce-wholesale-payments/woocommerce-wholesale-payments.php';
        $wpay_file   = trailingslashit( WP_PLUGIN_DIR ) . plugin_basename( $plugin_file );

        return file_exists( $wpay_file ) ? true : false;
    }

    /**
     * Check if WC Vendors is installed
     *
     * @since 1.0.0.2
     *
     * @return bool
     */
    public static function is_wcvendors_installed() {

        $plugin_file    = 'wc-vendors/class-wc-vendors.php';
        $wcvendors_file = trailingslashit( WP_PLUGIN_DIR ) . plugin_basename( $plugin_file );

        return file_exists( $wcvendors_file );
    }

    /**
     * Check if AdTribes is installed
     *
     * @since 1.0.0.2
     *
     * @return bool
     */
    public static function is_adtribes_installed() {

        $plugin_file   = 'woo-product-feed-pro/woocommerce-sea.php';
        $adtribes_file = trailingslashit( WP_PLUGIN_DIR ) . plugin_basename( $plugin_file );

        return file_exists( $adtribes_file );
    }

    /**
     * Check if Invoice Gateway is installed
     *
     * @since 1.0.0.2
     *
     * @return bool
     */
    public static function is_invoice_gateway_installed() {

        $plugin_file          = 'invoice-gateway-for-woocommerce/invoice-gateway-for-woocommerce.php';
        $invoice_gateway_file = trailingslashit( WP_PLUGIN_DIR ) . plugin_basename( $plugin_file );

        return file_exists( $invoice_gateway_file );
    }

    /**
     * Check if Store Toolkit is installed
     *
     * @since 1.0.0.2
     *
     * @return bool
     */
    public static function is_store_toolkit_installed() {

        $plugin_file        = 'woocommerce-store-toolkit/store-toolkit.php';
        $store_toolkit_file = trailingslashit( WP_PLUGIN_DIR ) . plugin_basename( $plugin_file );

        return file_exists( $store_toolkit_file );
    }

    /**
     * Check if Store Exporter is installed
     *
     * @since 1.0.2
     *
     * @return bool
     */
    public static function is_store_exporter_installed() {

        $plugin_file         = 'woocommerce-exporter/exporter.php';
        $store_exporter_file = trailingslashit( WP_PLUGIN_DIR ) . plugin_basename( $plugin_file );

        return file_exists( $store_exporter_file );
    }

    /**
     * Check if StoreAgent AI is installed
     *
     * @since 1.0.0.2
     *
     * @return bool
     */
    public static function is_storeagent_installed() {

        $plugin_file     = 'storeagent-ai-for-woocommerce/storeagent-ai-for-woocommerce.php';
        $storeagent_file = trailingslashit( WP_PLUGIN_DIR ) . plugin_basename( $plugin_file );

        return file_exists( $storeagent_file );
    }

    /**
     * Check if FunnelKit Stripe is installed
     *
     * @since 1.0.0.2
     *
     * @return bool
     */
    public static function is_funnelkit_stripe_installed() {

        $plugin_file           = 'funnelkit-stripe-woo-payment-gateway/funnelkit-stripe-woo-payment-gateway.php';
        $funnelkit_stripe_file = trailingslashit( WP_PLUGIN_DIR ) . plugin_basename( $plugin_file );

        return file_exists( $funnelkit_stripe_file );
    }

    /**
     * Check if any plugin is installed
     *
     * @param string $plugin_name Plugin name.
     *
     * @since 1.0.0.2
     *
     * @return bool
     */
    public static function is_wp_plugin_installed( $plugin_name ) {
        return file_exists( trailingslashit( WP_PLUGIN_DIR ) . $plugin_name );
    }

    /**
     * Get data about the current woocommerce installation.
     *
     * @since  1.0.0.2
     * @access public
     *
     * @return array Array of data about the current woocommerce installation.
     */
    public static function get_woocommerce_data() {

        return self::get_plugin_data( 'woocommerce/woocommerce.php' );
    }

    /**
     * Get the URL with UTM parameters.
     *
     * @param string $url_path     URL path from main.
     * @param string $utm_source   UTM source.
     * @param string $utm_medium   UTM medium.
     * @param string $utm_campaign UTM campaign.
     * @param string $site_url     URL - defaults to `https://savetowishlist.com/`.
     *
     * @since 1.0.0.2
     * @return string
     */
    public static function get_utm_url( $url_path = '', $utm_source = 'stwl', $utm_medium = 'action', $utm_campaign = 'default', $site_url = 'https://savetowishlist.com/' ) {

        $utm_content = get_option( 'stwlite_installed_by', false );
        $url         = trailingslashit( $site_url ) . $url_path;

        return add_query_arg(
            array(
                'utm_source'   => $utm_source,
                'utm_medium'   => $utm_medium,
                'utm_campaign' => $utm_campaign,
                'utm_content'  => $utm_content,
            ),
            trailingslashit( $url )
        );
    }

    /**
     * Get plugin data.
     *
     * @param string $plugin_basename Plugin basename.
     *
     * @since  1.0.0.2
     * @access public
     *
     * @return array Array of data about the current woocommerce installation.
     */
    public static function get_plugin_data( $plugin_basename ) {

        if ( ! function_exists( 'get_plugin_data' ) ) {
            require_once ABSPATH . '/wp-admin/includes/plugin.php';
        }

        if ( file_exists( WP_PLUGIN_DIR . '/' . $plugin_basename ) ) {
            return get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin_basename, false, false );
        } else {
            return false;
        }
    }

    /**
     * Return the parent product ID for a WooCommerce product object.
     *
     * For variation products the parent (variable) product ID is returned.
     * For all other product types — including when $product_obj is null —
     * the $fallback_id is returned unchanged. This consolidates the
     * repeated "is_type('variation') → get_parent_id()" pattern.
     *
     * @since  1.0.0
     * @access public
     *
     * @param \WC_Product|null $product_obj The product object to inspect.
     * @param int              $fallback_id ID to return when the product is not a variation.
     * @return int Parent product ID for variations, $fallback_id otherwise.
     */
    public static function get_parent_product_id( ?\WC_Product $product_obj, int $fallback_id ): int {
        if ( $product_obj instanceof \WC_Product && $product_obj->is_type( 'variation' ) ) {
            return (int) $product_obj->get_parent_id();
        }
        return $fallback_id;
    }

    /**
     * Return the effective product ID for a WooCommerce cart item.
     *
     * For variable products the variation ID is the actionable identifier;
     * for simple products the base product ID is used instead.
     *
     * @since  1.0.0
     * @access public
     *
     * @param array $cart_item WooCommerce cart item array.
     * @return int Variation ID when present and non-zero, otherwise the product ID.
     */
    public static function get_effective_product_id( array $cart_item ): int {
        $variation_id = ! empty( $cart_item['variation_id'] ) ? (int) $cart_item['variation_id'] : 0;
        return $variation_id > 0 ? $variation_id : (int) $cart_item['product_id'];
    }

    /**
     * Flush rewrite rules.
     *
     * @since 1.0.2
     *
     * @return void
     */
    public static function flush_rewrite_rules() {
        if ( function_exists( 'flush_rewrite_rules' ) ) {
            flush_rewrite_rules( false );
        }
    }

    /**
     * Get string option value.
     *
     * @since 1.0.2
     * @access public
     *
     * @param string $option Option name.
     * @param string $default_value Default value.
     *
     * @return string Filtered option value.
     */
    public function get_string_option( $option, $default_value = '' ) {
        $value = get_option( $option, $default_value );
        return $value && gettype( $value ) === 'string' ? apply_filters( 'stwlite_string_option', $value, $option ) : $value;
    }

    /**
     * Check if Pro is installed
     *
     * @since 1.0.3
     *
     * @return bool
     */
    public function is_pro_installed() {
        if ( self::is_wp_plugin_installed( $this->plugin_pro_basename ) ) {
            // Check if plugin is active.
            if ( function_exists( 'is_plugin_active' ) ) {
                return is_plugin_active( $this->plugin_pro_basename );
            } else {
                include_once ABSPATH . 'wp-admin/includes/plugin.php';
                return is_plugin_active( $this->plugin_pro_basename );
            }
        }

        return false;
    }

    /**
     * Get default wishlist label.
     *
     * @since 1.0.5
     *
     * @return string Default wishlist label.
     */
    public function get_default_wishlist_label() {
        $default_label        = __( 'First Wishlist', 'saveto-wishlist-lite-for-woocommerce' );
        $option_default_label = $this->get_string_option( 'stwlite_settings_first_wishlist_label', $default_label );
        return $option_default_label ? $option_default_label : $default_label;
    }
}
