<?php

namespace CodeConfig\EAW\App\CartManager;

use CodeConfig\EAW\AppSettings;
use CodeConfig\EAW\Utils\Singleton;

defined('ABSPATH') || exit('No direct script access allowed');

class Frontend
{
    use Singleton;
    protected $settings;

    public function doHooks()
    {
        $this->settings = AppSettings::getInstance();

        if (
            ! $this->settings->getParams('sbEnable')
            && ! $this->settings->getParams('scEnable')
            && ! $this->settings->getParams('enableMiniCart')
            && ! $this->settings->getParams('enableViewedProducts')
            && ! $this->settings->getParams('enableVariationPopUp')
        ) {
            return;
        }

        add_action('wp_enqueue_scripts', [$this, 'enqueueScripts']);
        add_filter('woocommerce_add_to_cart_fragments', [$this, 'eawWcATCFragments'], PHP_INT_MAX, 1);
        add_action('template_redirect', [$this, 'eawRecentlyViewed']);

        // TODO: Optimize this code.
        add_action('wp_ajax_eaw_get_cart_fragments', [$this, 'eaw_get_cart_fragments']);

        self::add_ajax_events();
        add_filter('woocommerce_add_to_cart_redirect', [$this, 'eawWcAtcRedirect'], PHP_INT_MAX, 2);
        add_filter('eaw_quantity_input_args', [$this, 'eaw_quantity_input_args'], 10, 2);
        add_action('eaw_sc_pd_plus_simple_atc', [$this, 'get_pd_plus_simple_atc'], 10, 3);
        add_action('eaw_sc_pd_plus_external_atc', [$this, 'get_pd_plus_external_atc'], 10, 3);
        add_action('eaw_sc_pd_plus_grouped_atc', [$this, 'get_pd_plus_grouped_atc'], 10, 3);
        add_action('eaw_sc_pd_plus_variable_atc', [$this, 'get_pd_plus_grouped_atc'], 10, 3);
        add_action('eaw_get_sidebar_cart_content', [$this, 'get_sidebar_cart_content']);
        add_action('eaw_get_checkout_form', [$this, 'get_checkout_form'], 10, 5);
        add_action('woocommerce_checkout_update_order_review', [$this, 'cancel_update_order_review'], -1, 1);
    }

    public function enqueueScripts()
    {
        wp_enqueue_script(
            'eaw-aiocs-frontend',
            CCPEAW_ASSETS . '/js/eaw-aiocs-frontend.js',
            ['jquery'],
            CCPEAW_VERSION
        );

        wp_add_inline_style(
            'eaw-aiocs-frontend',
            html_entity_decode($this->settings->getParams('custom_css'))
        );

        if ($this->settings->getParams('atcBtnHoverEffect')) {
            wp_localize_script('eaw-aiocs-frontend', 'eaw_effect_atc', [
                'effect' => $this->settings->getParams('atcBtnHoverEffect')
            ]);
        }
    }

    public function cancel_update_order_review($post_data)
    {
        if (empty($post_data) && $this->settings->enable('sc_checkout_')) {
            wp_die();
        }
    }

    public function get_checkout_form($sidebar_cart, $checkout_cart_enable, $language, $scCheckOutKeyboardNav = '', $is_customize = '')
    {
        $sc_checkout_class        = ['eaw-sidebar-cart-checkout-wrap'];
        if (!$checkout_cart_enable) {
            $sc_checkout_class[] = 'eaw-sidebar-cart-content-wrap1 eaw-disabled';
        }
        $checkout_refresh = false;
        if (
            class_exists('THWCFE_Public_Checkout')                                                      ||
            is_plugin_active('coderockz-woocommerce-delivery-date-time-pro/coderockz-woo-delivery.php') ||
            is_plugin_active('mollie-payments-for-woocommerce/mollie-payments-for-woocommerce.php')
        ) {
            $sc_checkout_class[] = 'eaw-sidebar-cart-checkout-wrap-refresh';
            $checkout_refresh    = true;
        }
        if (!$checkout_refresh && WC()->cart->is_empty()) {
            $sc_checkout_class[] = 'eaw-sidebar-cart-checkout-wrap-empty';
        }
        $sc_checkout_class = trim(implode(' ', $sc_checkout_class));
        ?>
		<div class="<?php echo esc_attr($sc_checkout_class); ?>"
			data-use_keyboard="<?php echo esc_attr($scCheckOutKeyboardNav); ?>">
			<?php
                    if ($is_customize || (! WC()->cart->is_empty()  && !$checkout_refresh)) {
                        wc_get_template(
                            'sc-form-checkout.php',
                            [
                                'checkout'     => WC()->checkout(),
                                'is_customize' => $is_customize,
                                'settings'     => $sidebar_cart,
                                'language'     => $language,
                                'param'        => []
                            ],
                            'essential-addons-for-woocommerce' . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . 'sidebar-cart' . DIRECTORY_SEPARATOR,
                            CCPEAW_TEMPLATES . 'atc/' . 'sidebar-cart' . DIRECTORY_SEPARATOR
                        );
                    } else {
                        ?>
				<div class="eaw-checkout-step-wrap woocommerce woocommerce-checkout">
					<div class="eaw-checkout-before-checkout-form eaw-disabled"></div>
					<form name="checkout" method="post" class="checkout woocommerce-checkout" action="<?php echo esc_url(wc_get_checkout_url()); ?>" enctype="multipart/form-data">
						<?php
                                    if (function_exists('stripe_wc')) {
                                        $available_payments     = WC()->payment_gateways()->get_available_payment_gateways();
                                        $available_payments_key = array_keys($available_payments);
                                        $stripe_wc_payments     = array_intersect($available_payments_key, array_map('eaw_stripe_wc_payments', stripe_wc()->payment_gateways()));
                                        foreach ($stripe_wc_payments as $payment) {
                                            wc_stripe_token_field($available_payments[$payment]);
                                        }
                                    }
                        if (is_plugin_active('woocommerce-payments/woocommerce-payments.php')) {
                            $available_payments = $available_payments ?? WC()->payment_gateways()->get_available_payment_gateways();
                            if (!empty($available_payments['woocommerce_payments'])) {
                                wc_get_template('checkout/payment-method.php', ['gateway' => $available_payments['woocommerce_payments']]);
                            }
                        }
                        ?>
					</form>
					<div class="eaw-checkout-after-checkout-form eaw-disabled"></div>
				</div>
			<?php
                    }
        ?>
		</div>
	<?php
    }

    public function get_sidebar_cart_content()
    {
        wc_get_template(
            'sc-content.php',
            ['sidebar_cart' => SidebarCartContent::getInstance()],
            'essential-addons-for-woocommerce' . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . 'sidebar-cart' . DIRECTORY_SEPARATOR,
            CCPEAW_TEMPLATES . 'atc/' . 'sidebar-cart' . DIRECTORY_SEPARATOR
        );
    }

    public function get_pd_plus_grouped_atc($product, $settings, $language)
    {
        $product_type = $product->get_type();
        $class        = ['eaw-product-bt-atc eaw-product-bt-not-atc eaw-pd_plus-product-bt-atc button'];
        $class[]      = "eaw-product-bt-$product_type";
        $pd_id        = '';

        if ($product_type === 'variable' && $this->settings->getParams('ajax_atc_pd_variable')) {
            $class[]    = 'eaw-loop-variable-bt-atc';
            $pd_id      = $product->get_id();

            if (! wp_style_is('eaw-variable-atc', 'enqueued')) {
                wp_enqueue_style('eaw-variable-atc');
                wp_enqueue_style('eaw-nav-icons');
            }

            if (! wp_script_is('eaw-variable-atc', 'enqueued')) {
                wp_enqueue_script('eaw-variable-atc');
                wp_enqueue_script('eaw-ajax-atc');

                wp_enqueue_script('eaw-frontend-swatches');
            }
        }

        $bt_class = trim(apply_filters('eaw_sc_pd_plus_atc_class', implode(' ', $class), $product));

        do_action('eaw_sc_pd_plus_before_atc', $product);

        echo sprintf(
            '<a href="%s" class="%s" data-product_id="%s" target="_blank">%s</a>',
            esc_attr(esc_url($product->get_permalink())),
            esc_attr($bt_class),
            esc_attr($pd_id),
            esc_html(SidebarCartContent::product_get_bt_atc_html($settings, $language))
        );

        do_action('eaw_sc_pd_plus_after_atc', $product);
    }

    public function get_pd_plus_external_atc($product, $settings, $language)
    {
        $bt_class = 'eaw-product-bt-atc eaw-product-bt-not-atc eaw-product-bt-external eaw-pd_plus-product-bt-atc eaw-pd_plus-product-bt-external button';
        $bt_class = trim(apply_filters('eaw_sc_pd_plus_atc_class', $bt_class, $product));
        ?>
		<form class="eaw-pd_plus-cart-form"
			action="<?php echo esc_attr(esc_url($product->add_to_cart_url())); ?>" method="get">
			<?php do_action('eaw_sc_pd_plus_before_atc', $product); ?>

			<button type="submit" class="<?php echo esc_attr($bt_class); ?>">
				<?php echo wp_kses_post(SidebarCartContent::product_get_bt_atc_html($settings, $language)); ?>
			</button>

			<?php do_action('eaw_sc_pd_plus_after_atc', $product); ?>
		</form>

	<?php
    }

    public function get_pd_plus_simple_atc($product, $settings, $language)
    {
        $product_id = $product->get_id();
        $attr       = [
            'product_id'    => $product_id,
            'product_sku'   => $product->get_sku(),
            'product_name'  => $product->get_name(),
            'product_price' => $product->get_price(),
        ];
        $data_attr  = [];
        foreach ($attr as $k => $v) {
            $data_attr[] = sprintf('data-%s="%s"', $k, esc_attr($v));
        }
        $bt_class = trim(apply_filters('eaw_sc_pd_plus_atc_class', 'eaw-product-bt-atc eaw-pd_plus-product-bt-atc button', $product));
        do_action('eaw_sc_pd_plus_before_atc', $product);
        echo sprintf(
            '<a href="%s" class="%s" %s target="_blank">%s</a>',
            esc_attr(esc_url($product->get_permalink())),
            esc_attr($bt_class),
            //phpcs:ignore WordPress.Security.EscapeOutput
            implode(' ', $data_attr),
            esc_html(SidebarCartContent::product_get_bt_atc_html($settings, $language))
        );
        do_action('eaw_sc_pd_plus_after_atc', $product);
        ?>
		<input type="hidden" name="add-to-cart" class="eaw-add-to-cart"
			value="<?php echo esc_attr($product_id); ?>" />
		<input type="hidden" name="product_id" class="eaw-product_id"
			value="<?php echo esc_attr($product_id); ?>" />
		<?php
    }


    public static function eawWcAtcRedirect($url, $adding_to_cart)
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is a filter callback for redirect logic
        if (! empty($_REQUEST['eawAjaxAtc'])) {
            return null;
        }

        return $url;
    }

    public static function add_ajax_events()
    {
        $ajax_events = [
            'eaw_change_quantity'    => true,
            'eaw_remove_item'        => true,
            'eaw_apply_coupon'       => true,
            'eaw_remove_coupon'      => true,
            'eaw_add_to_cart'        => true,
            'eaw_show_variation'     => true,
            'eaw_get_checkout_form'  => true,
            'eaw_get_cart_fragments' => true,
        ];
        foreach ($ajax_events as $ajax_event => $nopriv) {
            add_action("wp_ajax_woocommerce_{$ajax_event}", [__CLASS__, $ajax_event]);

            if ($nopriv) {
                add_action("wp_ajax_nopriv_woocommerce_{$ajax_event}", [__CLASS__, $ajax_event]);

                // WC AJAX can be used for frontend ajax requests
                add_action("wc_ajax_{$ajax_event}", [__CLASS__, $ajax_event]);
            }
        }
    }
    public static function validate_nonce()
    {
        return apply_filters('eaw_validate_nonce', check_ajax_referer('ccpeaw', 'eaw_nonce', false));
    }

    public static function eaw_add_to_cart()
    {
        if (!self::validate_nonce()) {
            wp_send_json(['status' => 'error', 'message' => 'invalid nonce']);
        }
        if (!did_action('woocommerce_add_to_cart')) {
            \WC_Form_Handler::add_to_cart_action();
        }
        if (! empty(wc_get_notices('error'))) {
            wp_send_json(['error' => true, 'message' => wc_print_notices(true)]);
            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified by validate_nonce() above
        } elseif (isset($_POST['add-to-cart']) && !empty($_POST['add-to-cart'])) {
            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified by validate_nonce() above
            do_action('woocommerce_ajax_added_to_cart', apply_filters('woocommerce_add_to_cart_product_id', absint(sanitize_text_field(wp_unslash($_POST['add-to-cart'])))));
        }
        if (function_exists('facebook_for_woocommerce')) {
            add_filter('woocommerce_add_to_cart_fragments', function ($fragments) {
                return facebook_for_woocommerce()->get_integration()->events_tracker->add_add_to_cart_event_fragment($fragments);
            }, 10, 1);
        }
        \WC_AJAX::get_refreshed_fragments();
    }

    public static function eaw_show_variation()
    {
        if (!self::validate_nonce()) {
            wp_send_json(['status' => 'error', 'message' => 'invalid nonce']);
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified by validate_nonce() above
        $product_id = isset($_POST['product_id']) ? sanitize_text_field(wp_unslash($_POST['product_id'])) : '';
        $result     = [
            'status' => 'error',
            'html'   => '',
        ];
        $product = wc_get_product($product_id);
        if ($product && $product->is_type('variable') && $product->is_in_stock()) {
            ob_start();
            wc_get_template(
                'variation-popup.php',
                ['product' => $product],
                'essential-addons-for-woocommerce' . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR,
                CCPEAW_TEMPLATES . 'atc/'
            );
            $html             = ob_get_clean();
            $result['status'] = 'success';
            $result['html']   = $html;
            wp_send_json($result);
        }
        wp_send_json($result);
    }

    public static function product_get_quantity_html($args = [])
    {
        if (empty($args)) {
            return '';
        }
        extract($args);
        ob_start();
        if ($max_value && $min_value === $max_value) {
            ?>
			<input type="hidden" id="<?php echo esc_attr($input_id); ?>" name="<?php echo esc_attr($input_name); ?>"
				value="<?php echo esc_attr($min_value); ?>">
		<?php
        } else {
            do_action('woocommerce_before_quantity_input_field');
            ?>
			<div class="eaw-va-change-qty eaw-va-qty-subtract">
				<span class="eaw_nav_icons-pre"></span>
			</div>
			<div>
				<input type="number"
					title="<?php echo esc_attr_x('Qty', 'Product quantity input tooltip', 'essential-addons-for-woocommerce'); ?>"
					placeholder="<?php echo esc_attr($placeholder); ?>"
					id="<?php echo esc_attr($input_id); ?>"
					class="<?php echo esc_attr(join(' ', (array) $classes)); ?>"
					name="<?php echo esc_attr($input_name); ?>"
					inputmode="<?php echo esc_attr($inputmode); ?>"
					min="<?php echo esc_attr($min_value); ?>"
					max="<?php echo esc_attr(0 < $max_value ? $max_value : ''); ?>"
					step="<?php echo esc_attr($step); ?>"
					value="<?php echo esc_attr($input_value); ?>">
			</div>
			<div class="eaw-va-change-qty eaw-va-qty-add">
				<span class="eaw_nav_icons-next"></span>
			</div>
		<?php
                do_action('woocommerce_after_quantity_input_field');
        }
        $html = ob_get_clean();

        return $html;
    }

    public static function eaw_apply_coupon()
    {
        $result = [
            'status'  => 'error',
            'message' => '',
        ];

        if (!self::validate_nonce()) {
            wp_send_json(['status' => 'error', 'message' => 'invalid nonce']);
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified by validate_nonce() above
        $coupon_code = isset($_POST['eaw_coupon_code']) ? sanitize_text_field(wp_unslash($_POST['eaw_coupon_code'])) : '';
        if ($coupon_code) {
            WC()->cart->add_discount(wc_format_coupon_code($coupon_code));
            $notices = WC()->session->get('wc_notices', []);
            if (empty($notices['error'])) {
                $result['status'] = 'success';
            }
        } else {
            wc_add_notice(\WC_Coupon::get_generic_coupon_error(\WC_Coupon::E_WC_COUPON_PLEASE_ENTER), 'error');
        }

        $result['message'] = wc_print_notices(true);
        wp_send_json($result);
    }

    public static function eaw_remove_coupon()
    {
        $result = [
            'status'  => 'error',
            'message' => '',
        ];

        if (!self::validate_nonce()) {
            wp_send_json(['status' => 'error', 'message' => 'invalid nonce']);
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified by validate_nonce() above
        $coupon = isset($_POST['eaw_coupon_code']) ? wc_format_coupon_code(wc_clean(sanitize_text_field(wp_unslash($_POST['eaw_coupon_code'])))) : '';

        if (empty($coupon)) {
            $result['message'] = esc_html__('Sorry there was a problem removing this coupon.', 'essential-addons-for-woocommerce');
        } else {
            WC()->cart->remove_coupon($coupon);
            $notices = WC()->session->get('wc_notices', []);
            if (empty($notices['error'])) {
                $result['status']  = 'success';
                $result['message'] = esc_html__('Coupon has been removed.', 'essential-addons-for-woocommerce');
                WC()->cart->calculate_totals();
            }
        }

        wp_send_json($result);
    }

    public static function eaw_change_quantity()
    {
        if (!self::validate_nonce()) {
            wp_send_json(['status' => 'error', 'message' => 'invalid nonce']);
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce verified by validate_nonce() above
        $eaw_cart = isset($_POST['eaw_cart']) ? wc_clean(wp_unslash($_POST['eaw_cart'])) : [];
        if (empty($eaw_cart)) {
            wp_send_json(['error' => true]);
        }
        $cart = WC()->cart->get_cart();

        foreach ($eaw_cart as $cart_item_key => $qty) {
            if (! isset($cart[$cart_item_key]) || ! ($product = $cart[$cart_item_key]['data'] ?? '')) {
                continue;
            }
            $cart_qty = $cart[$cart_item_key]['quantity'] ?? '';
            if ($product->is_sold_individually() && $cart_qty == 1) {
                continue;
            }
            $qty = $qty['qty'] ?? 0;
            $qty = $qty < 0 ? 0 : ($product->is_sold_individually() && floatval($qty) > 1 ? 1 : $qty);
            // Sanitize.
            $qty = apply_filters('woocommerce_stock_amount_cart_item', wc_stock_amount(preg_replace('/[^0-9\.]/', '', $qty)), $cart_item_key);
            if ('' === $qty || $qty == ($cart[$cart_item_key]['quantity'] ?? '')) {
                continue;
            }
            WC()->cart->set_quantity(strval($cart_item_key), $qty, true);
        }

        WC()->cart->calculate_totals();
        \WC_AJAX::get_refreshed_fragments();
        die();
    }

    public static function eaw_remove_item()
    {
        if (!self::validate_nonce()) {
            wp_send_json(['status' => 'error', 'message' => 'invalid nonce']);
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified by validate_nonce() above
        $cart_item_key = isset($_POST['cart_item_key']) ? sanitize_text_field(wp_unslash($_POST['cart_item_key'])) : '';
        if ($cart_item_key && false !== WC()->cart->remove_cart_item($cart_item_key)) {
            do_action('woocommerce_check_cart_items');
            \WC_AJAX::get_refreshed_fragments();
        } else {
            wp_send_json_error();
        }
        die();
    }

    public static function eaw_get_cart_fragments()
    {
        if (!self::validate_nonce()) {
            wp_send_json(['status' => 'error', 'message' => 'invalid nonce']);
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verified by validate_nonce() above
        if (! isset($_REQUEST['eaw_get_cart_fragments'])) {
            wp_die();
        }
        \WC_AJAX::get_refreshed_fragments();
    }


    public static function eawWcATCFragments($fragments)
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- This is a fragment filter, nonce checked by WooCommerce
        if (isset($_POST['eaw_nonce']) && ! empty(WC()->session->get('wc_notices', []))) {
            $fragments['eaw_message'] = wc_print_notices(true);
        }

        if (function_exists('pewc_wc_calculate_total') || apply_filters('eaw_wc_calculate_total', false)) {
            WC()->cart->calculate_totals();
        }

        $wc_cart              = WC()->cart;
        $cart_total           = $wc_cart->get_total();
        $cart_subtotal        = $wc_cart->get_cart_subtotal();
        $cart_content_count   = $wc_cart->get_cart_contents_count();
        $settings             = AppSettings::getInstance();
        $mcDisplayStyle       = $settings->getParams('mcDisplayStyle');
        $mcCartTotal          = $settings->getParams('mcCartTotal');
        $scFootCartTotal      = $settings->getParams('scFootCartTotal');
        $scIconCountType      = $settings->getParams('scIconCountType');
        $scIconStyle          = $settings->getParams('scIconStyle');
        ob_start();
        ?>
		<span class="eaw-menu-cart-text-wrap">
			<?php
            MenuCart::get_menu_cart_text($mcDisplayStyle, $mcCartTotal === 'total' ? $cart_total : $cart_subtotal, $cart_content_count);
        ?>
		</span>

		<?php
        $menu_text = ob_get_clean();
        if ($settings->getParams('scEnable')) {
            ob_start();
            ?>
			<ul class="eaw-sidebar-cart-products">
				<?php
                    SidebarCartContent::get_sidebar_content_pd_html($wc_cart);
            ?>
			</ul>
			<?php
            $sidebar_content_pd_html                           = ob_get_clean();
            $fragments['.eaw-sidebar-cart-products']           = $sidebar_content_pd_html;
            if (in_array($scIconStyle, ['1', '2', '3', '5'])) {
                if ($scIconStyle === '3' && $scIconCountType === 'cart_subtotal') {
                    $scIconCountType = 'pd_count';
                }
                ob_start();
                ?>
				<div class="eaw-sidebar-cart-count">
					<?php
                        switch ($scIconCountType) {
                            case 'item_count':
                                echo wp_kses_post(count($wc_cart->get_cart()));
                                break;
                            case 'cart_subtotal':
                                echo wp_kses_post($cart_subtotal);
                                break;
                            default:
                                echo wp_kses_post($cart_content_count);
                        }
                ?>
				</div>
			<?php
                $sidebar_count_pd_html = ob_get_clean();
            }
            ob_start();
            ?>
			<div class="eaw-sidebar-cart-footer-cart_total1 eaw-sidebar-cart-footer-cart_total1-<?php echo esc_attr($scFootCartTotal); ?>">
				<?php echo $scFootCartTotal === 'total' ? wp_kses_post($cart_total) : wp_kses_post($cart_subtotal); ?>
			</div>
			<?php
            $sidebar_cart_total_html                           = ob_get_clean();
            $fragments['.eaw-sidebar-cart-footer-cart_total1'] = $sidebar_cart_total_html;
            if ($settings->getParams('scFootCoupon')) {
                $applied_coupons      = wc_coupons_enabled() ? $wc_cart->get_applied_coupons() : [];
                $applied_coupons_html = SidebarCartContent::get_scFootCoupon_html($applied_coupons);
                ob_start();
                ?>
				<div class="eaw-sidebar-cart-footer-coupons<?php echo esc_attr($applied_coupons_html ? '' : ' eaw-disabled'); ?>">
					<div class="eaw-sidebar-cart-footer-coupons1">
						<?php echo wp_kses($applied_coupons_html, AppSettings::extendPostAllowedHtml()); ?>
					</div>
				</div>
<?php
                    $sidebar_coupons_html = ob_get_clean();
            }
            if (
                strpos($settings->getParams('scFootMsg'), '{product_plus}') !== false &&
                in_array($scFootPdPlus = $settings->getParams('scFootPdPlus'), ['product_upsell', 'cross_sell'])
            ) {
                $fragments['.eaw-sidebar-cart-footer-pd-wrap-wrap'] = SidebarCartContent::get_product_plus(true, $scFootPdPlus);
            }
        }
        $fragments['.eaw-menu-cart-text-wrap'] = $menu_text;
        if (isset($sidebar_count_pd_html)) {
            $fragments['.eaw-sidebar-cart-count'] = $sidebar_count_pd_html;
        }
        if (isset($sidebar_coupons_html)) {
            $fragments['.eaw-sidebar-cart-footer-coupons'] = $sidebar_coupons_html;
        }

        return $fragments;
    }

    public static function eaw_quantity_input_args($args = [], $product = null)
    {
        if (is_null($product)) {
            $product = $GLOBALS['product'];
        }
        $defaults = [
            'input_id'     => uniqid('quantity_'),
            'input_name'   => 'quantity',
            'input_value'  => '1',
            'classes'      => apply_filters('woocommerce_quantity_input_classes', [
                'input-text',
                'qty',
                'text'
            ], $product),
            'max_value'    => apply_filters('woocommerce_quantity_input_max', -1, $product),
            'min_value'    => apply_filters('woocommerce_quantity_input_min', 0, $product),
            'step'         => apply_filters('woocommerce_quantity_input_step', 1, $product),
            'pattern'      => apply_filters('woocommerce_quantity_input_pattern', has_filter('woocommerce_stock_amount', 'intval') ? '[0-9]*' : ''),
            'inputmode'    => apply_filters('woocommerce_quantity_input_inputmode', has_filter('woocommerce_stock_amount', 'intval') ? 'numeric' : ''),
            'product_name' => $product ? $product->get_title() : '',
            'placeholder'  => apply_filters('woocommerce_quantity_input_placeholder', '', $product),
        ];
        $args     = apply_filters('woocommerce_quantity_input_args', wp_parse_args($args, $defaults), $product);
        // Apply sanity to min/max args - min cannot be lower than 0.
        $args['min_value'] = max($args['min_value'], 0);
        $args['max_value'] = 0 < $args['max_value'] ? $args['max_value'] : '';
        // Max cannot be lower than min if defined.
        if ('' !== $args['max_value'] && $args['max_value'] < $args['min_value']) {
            $args['max_value'] = $args['min_value'];
        }

        return $args;
    }

    public static function eawGetClassIcon()
    {
        if (!self::validate_nonce()) {
            wp_send_json(['status' => 'error', 'message' => 'invalid nonce']);
        }
        $result  = [
            'status'  => '',
            'message' => '',
        ];
        // phpcs:disable WordPress.Security.NonceVerification.Missing -- Nonce verified by validate_nonce() above
        $icon_id = sanitize_text_field(wp_unslash($_POST['icon_id'] ?? ''));
        $type    = sanitize_text_field(wp_unslash($_POST['type'] ?? ''));
        // phpcs:enable WordPress.Security.NonceVerification.Missing
        if (is_numeric($icon_id) && $type && $class = self::getInstance()->settings->getClassIcon($icon_id, $type)) {
            $result['status']  = 'success';
            $result['message'] = $class;
        }
        wp_send_json($result);
    }

    public function eawRecentlyViewed()
    {
        $check = false;
        if ($this->settings->getParams('vpEnable')) {
            $check = true;
        }
        if ($this->settings->getParams('scEnable') && $this->settings->getParams('scFootPdPlus') === 'viewed_product') {
            $check = true;
        }
        if (! $check) {
            return;
        }
    }

    /**
     * @param $element
     * @param $name
     * @param $style
     * @param array $suffix
     * @param array $important
     *
     * @return string
     */
    public static function add_inline_style($element, $name, $style, $suffix = [], $important = [])
    {
        if (! $element || ! is_array($element)) {
            return '';
        }
        $settings = AppSettings::getInstance();
        $element  = implode(',', $element);
        $return   = "{$element}{";
        if (is_array($name) && count($name)) {
            foreach ($name as $key => $value) {
                $get_value  = $settings->getParams($value);
                $get_suffix = $suffix[$key]    ?? '';
                $imp        = $important[$key] ?? '';
                $return     .= $style[$key] . ':' . $get_value . $get_suffix;
                if ($imp) {
                    $return .= ' !important';
                }
                $return .= ';';
            }
        }
        $return .= '}';

        return $return;
    }
}
