<?php

namespace FinchCart\Frontend\AddedtoCartPopup;

use function FinchCart\fc_kses_allowed_svg;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Ajax Added to Cart Popup
 */
class AddedtoCartPopup {

	/**
	 * Pro Plugin __FILE__
	 * Root file of plugin's pro version
	 *
	 * @var string
	 * @since      1.0.0
	 */
	protected static $file_pro = WP_PLUGIN_DIR . '/finch-cart-pro/finch-cart-pro.php';

	/**
	 * Class Constructor.
	 */
	public function __construct() {
		add_action( 'wp_ajax_finchcart_fire_added_to_cart_popup', array( $this, 'added_to_cart_popup' ) );
		add_action( 'wp_ajax_nopriv_finchcart_fire_added_to_cart_popup', array( $this, 'added_to_cart_popup' ) );

		add_action( 'wp_ajax_finchcart_inside_popup_added_to_cart_notice', array( $this, 'inside_popup_added_to_cart_notice' ) );
		add_action( 'wp_ajax_nopriv_finchcart_inside_popup_added_to_cart_notice', array( $this, 'inside_popup_added_to_cart_notice' ) );

		// Update cart item count for popup cart.
		add_filter( 'woocommerce_add_to_cart_fragments', array( $this, 'update_cart_items_count' ) );
	}

	/**
	 * Is pro version activated or not
	 */
	public function is_pro_activated() {
		return class_exists( 'WPBean_Finch_Cart_Pro' );
	}

	/**
	 * Get template path of popup modal
	 *
	 * @param string $file_path File name with folder path.
	 * @return string Full of template from theme or pro plugin or plugin.
	 */
	public function get_templates_path( $file_path ) {
		// from theme.
		$theme_tmpl = get_stylesheet_directory() . '/finch-cart-template/' . $file_path;
		if ( file_exists( $theme_tmpl ) ) {
			return $theme_tmpl;
		}

		// from pro version.
		if ( $this->is_pro_activated() ) {
			$pro_template = plugin_dir_path( self::$file_pro ) . $file_path;
			if ( file_exists( $pro_template ) ) {
				return $pro_template;
			}
		}

		// from free version.
		return plugin_dir_path( FINCHCART_FILE ) . $file_path;
	}

	/**
	 * Notification Bar Data
	 *
	 * @param array $settings Finch Cart settings options.
	 * @return array
	 */
	public function get_notification_bar_data( $settings ) {
		$template_data           = array();
		$notification_btns_label = isset( $settings['finchcart_notification_btns_label'] ) ? $settings['finchcart_notification_btns_label'] : '';
		$notification_content    = isset( $settings['finchcart_notification_content'] ) ? $settings['finchcart_notification_content'] : '';

		$template_data['show_notification_bar']  = isset( $settings['finchcart_show_notification'] ) ? wc_string_to_bool( $settings['finchcart_show_notification'] ) : '';
		$template_data['cart_link_text']         = isset( $notification_btns_label['finchcart_notice_cart_link'] ) ? esc_html( $notification_btns_label['finchcart_notice_cart_link'] ) : '';
		$template_data['continue_shopping_text'] = isset( $notification_btns_label['finchcart_notice_con_shop_text'] ) ? esc_html( $notification_btns_label['finchcart_notice_con_shop_text'] ) : '';
		$template_data['checkout_text']          = isset( $notification_btns_label['finchcart_notice_checkout_text'] ) ? esc_html( $notification_btns_label['finchcart_notice_checkout_text'] ) : '';
		$template_data['notice_show_image']      = isset( $notification_content['finchcart_notice_show_image'] ) ? wc_string_to_bool( $notification_content['finchcart_notice_show_image'] ) : '';
		$template_data['notice_show_view_cart']  = isset( $notification_content['finchcart_notice_show_view_cart'] ) ? wc_string_to_bool( $notification_content['finchcart_notice_show_view_cart'] ) : '';
		$template_data['notice_show_con_shop']   = isset( $notification_content['finchcart_notice_show_con_shop'] ) ? wc_string_to_bool( $notification_content['finchcart_notice_show_con_shop'] ) : '';
		$template_data['notice_show_checkout']   = isset( $notification_content['finchcart_notice_show_checkout'] ) ? wc_string_to_bool( $notification_content['finchcart_notice_show_checkout'] ) : '';
		$template_data['notice_show_cart_count'] = isset( $notification_content['finchcart_notice_show_cart_count'] ) ? wc_string_to_bool( $notification_content['finchcart_notice_show_cart_count'] ) : '';
		$template_data['notice_message_text']    = isset( $settings['finchcart_notice_message_text'] ) ? esc_html( $settings['finchcart_notice_message_text'] ) : '';

		return $template_data;
	}

	/**
	 * Heading Data
	 *
	 * @param array $settings Finch Cart settings options.
	 * @param int   $product_id Current product id.
	 * @return array
	 */
	public function get_heading_data( $settings, $product_id ) {
		$template_data        = array();
		$product_meta         = get_post_meta( $product_id, 'finch_cart_product_meta_', true );
		$recommended_products = $this->get_recommended_products( $settings, $product_id );

		$template_data['show_heading'] = isset( $settings['finchcart_show_heading'] ) ? wc_string_to_bool( $settings['finchcart_show_heading'] ) : '';
		if ( isset( $product_meta['finchcart_show_heading'] ) && 'default' !== $product_meta['finchcart_show_heading'] ) {
			if ( 'yes' === $product_meta['finchcart_show_heading'] ) {
				$template_data['show_heading'] = true;
			} elseif ( 'no' === $product_meta['finchcart_show_heading'] ) {
				$template_data['show_heading'] = false;
			}
		}

		$popup_heading = isset( $settings['finchcart_default_heading_text'] ) ? wp_kses_post( $settings['finchcart_default_heading_text'] ) : '';

		if ( isset( $product_meta['finchcart_override_heading'] ) && '1' === $product_meta['finchcart_override_heading'] ) {
			$popup_heading = isset( $product_meta['finchcart_default_heading_text'] ) ? wp_kses_post( $product_meta['finchcart_default_heading_text'] ) : '';
		}

		$popup_heading            = str_replace( '%title%', get_the_title( $product_id ), $popup_heading );
		$popup_heading            = preg_replace( '/\[(.+),(.+)\]/', _n( '${1}', '${2}', $recommended_products->found_posts, 'finch-cart-product-recommendations' ), $popup_heading );
		$template_data['heading'] = do_shortcode( $popup_heading );

		// Subheading data.
		$popup_subheading = isset( $settings['finchcart_default_subheading_text'] ) ? wp_kses_post( $settings['finchcart_default_subheading_text'] ) : '';

		if ( isset( $product_meta['finchcart_override_heading'] ) && '1' === $product_meta['finchcart_override_heading'] ) {
			$popup_subheading = isset( $product_meta['finchcart_default_subheading_text'] ) ? wp_kses_post( $product_meta['finchcart_default_subheading_text'] ) : '';
		}
		$template_data['subheading'] = do_shortcode( $popup_subheading );

		return $template_data;
	}

	/**
	 * Get global recommendations products.
	 *
	 * @param array $settings Finch Cart settings options.
	 * @return array
	 */
	public function get_global_recommendations( $settings ) {
		$global             = array();
		$additional_options = isset( $settings['finchcart_global_additional_options'] ) ? (array) wp_unslash( $settings['finchcart_global_additional_options'] ) : '';

		$global['recommendations_type'] = isset( $settings['finchcart_global_product_recommendations_type'] ) ? sanitize_text_field( $settings['finchcart_global_product_recommendations_type'] ) : '';
		$global['categories']           = isset( $settings['finchcart_global_categories'] ) && '' !== $settings['finchcart_global_categories'] ? array_map( 'absint', (array) wp_unslash( $settings['finchcart_global_categories'] ) ) : '';
		$global['tags']                 = isset( $settings['finchcart_global_tags'] ) && '' !== $settings['finchcart_global_tags'] ? array_map( 'absint', (array) wp_unslash( $settings['finchcart_global_tags'] ) ) : '';
		$global['orderby']              = isset( $additional_options['finchcart_global_products_orderby'] ) ? sanitize_text_field( $additional_options['finchcart_global_products_orderby'] ) : '';
		$global['order']                = isset( $additional_options['finchcart_global_products_order'] ) ? sanitize_text_field( $additional_options['finchcart_global_products_order'] ) : '';
		$global['products_type']        = isset( $additional_options['finchcart_global_products_type'] ) ? sanitize_text_field( $additional_options['finchcart_global_products_type'] ) : '';
		$global['stock_status']         = isset( $additional_options['finchcart_global_products_stock_status'] ) ? sanitize_text_field( $additional_options['finchcart_global_products_stock_status'] ) : '';
		$global['on_sale_only']         = isset( $additional_options['finchcart_global_on_sale_products_only'] ) ? wc_string_to_bool( $additional_options['finchcart_global_on_sale_products_only'] ) : '';
		$global['featured_only']        = isset( $additional_options['finchcart_global_featured_products_only'] ) ? wc_string_to_bool( $additional_options['finchcart_global_featured_products_only'] ) : '';
		$global['number_of_products']   = isset( $additional_options['finchcart_global_numbers_of_products'] ) ? absint( $additional_options['finchcart_global_numbers_of_products'] ) : '';

		return $global;
	}

	/**
	 * Get specific recommendations products.
	 *
	 * @param int $product_id Current product id.
	 * @return array
	 */
	public function get_specific_recommendations( $product_id ) {
		$specific           = array();
		$product_meta       = get_post_meta( $product_id, 'finch_cart_product_meta_', true );
		$additional_options = isset( $product_meta['finchcart_specificl_additional_options'] ) ? (array) wp_unslash( $product_meta['finchcart_specificl_additional_options'] ) : '';

		$specific['override_product_recommendations'] = isset( $product_meta['finchcart_override_product_recommendations'] ) ? wc_string_to_bool( $product_meta['finchcart_override_product_recommendations'] ) : '';
		$specific['recommendations_type']             = isset( $product_meta['finchcart_specific_product_recommendations_type'] ) ? sanitize_text_field( $product_meta['finchcart_specific_product_recommendations_type'] ) : '';
		$specific['manual_recommendations']           = isset( $product_meta['finchcart_specific_product_manual_recommendations']['disabled'] ) ? (array) array_keys( $product_meta['finchcart_specific_product_manual_recommendations']['disabled'] ) : '';
		$specific['categories']                       = isset( $product_meta['finchcart_specific_categories'] ) && '' !== $product_meta['finchcart_specific_categories'] ? array_map( 'absint', (array) wp_unslash( $product_meta['finchcart_specific_categories'] ) ) : '';
		$specific['tags']                             = isset( $product_meta['finchcart_specific_tags'] ) && '' !== $product_meta['finchcart_specific_tags'] ? array_map( 'absint', (array) wp_unslash( $product_meta['finchcart_specific_tags'] ) ) : '';
		$specific['orderby']                          = isset( $additional_options['finchcart_specific_products_orderby'] ) ? sanitize_text_field( $additional_options['finchcart_specific_products_orderby'] ) : '';
		$specific['order']                            = isset( $additional_options['finchcart_specific_products_order'] ) ? sanitize_text_field( $additional_options['finchcart_specific_products_order'] ) : '';
		$specific['products_type']                    = isset( $additional_options['finchcart_specific_products_type'] ) ? sanitize_text_field( $additional_options['finchcart_specific_products_type'] ) : '';
		$specific['stock_status']                     = isset( $additional_options['finchcart_specific_products_stock_status'] ) ? sanitize_text_field( $additional_options['finchcart_specific_products_stock_status'] ) : '';
		$specific['on_sale_only']                     = isset( $additional_options['finchcart_specific_on_sale_products_only'] ) ? wc_string_to_bool( $additional_options['finchcart_specific_on_sale_products_only'] ) : '';
		$specific['featured_only']                    = isset( $additional_options['finchcart_specific_featured_products_only'] ) ? wc_string_to_bool( $additional_options['finchcart_specific_featured_products_only'] ) : '';
		$specific['number_of_products']               = isset( $additional_options['finchcart_specific_numbers_of_products'] ) ? absint( $additional_options['finchcart_specific_numbers_of_products'] ) : '';

		return $specific;
	}

	/**
	 * Global recommendation product query.
	 *
	 * @param array $settings Finch Cart settings options.
	 * @param int   $product_id Current product id.
	 * @return object
	 */
	public function get_global_recommendation_query( $settings, $product_id ) {
		$query                = '';
		$product              = wc_get_product( $product_id );
		$global               = $this->get_global_recommendations( $settings );
		$recommendations_type = $global['recommendations_type'];

		$query_args = array(
			'post_type'           => 'product',
			'post_status'         => 'publish',
			'ignore_sticky_posts' => 1,
			'post__not_in'        => array( $product_id ),
			'numberposts'         => $global['number_of_products'],
			'orderby'             => $global['orderby'],
			'order'               => $global['order'],
		);

		if ( 'price' === $global['orderby'] ) {
			$query_args['orderby']  = 'meta_value_num';
			$query_args['meta_key'] = '_price';
		}

		if ( 'popularity' === $global['orderby'] ) {
			$query_args['orderby']  = 'meta_value_num';
			$query_args['meta_key'] = 'total_sales';
		}

		if ( 'rating' === $global['orderby'] ) {
			$query_args['orderby']  = 'meta_value_num';
			$query_args['meta_key'] = '_wc_average_rating';
		}

		if ( $recommendations_type && 'related' === $recommendations_type ) {
			$query_args['post__in'] = wc_get_related_products( $product_id, $global['number_of_products'], $product->get_upsell_ids() );
		}

		if ( $recommendations_type && 'manual' === $recommendations_type && ! empty( $global['categories'] ) ) {
			$query_args['tax_query'][] = array(
				'taxonomy' => 'product_cat',
				'field'    => 'term_id',
				'terms'    => $global['categories'],
				'operator' => 'IN',
			);
		}

		if ( isset( $global['tags'] ) && ! empty( $global['tags'] ) ) {
			$query_args['tax_query'][] = array(
				'taxonomy' => 'product_tag',
				'field'    => 'term_id',
				'terms'    => $global['tags'],
				'operator' => 'IN',
			);
		}

		if ( isset( $global['products_type'] ) && '' !== $global['products_type'] ) {
			$query_args['tax_query'][] = array(
				'taxonomy' => 'product_type',
				'field'    => 'slug',
				'terms'    => $global['products_type'],
			);
		}

		if ( isset( $global['stock_status'] ) && '' !== $global['stock_status'] ) {
			$query_args['meta_query'][] = array(
				'key'   => '_stock_status',
				'value' => $global['stock_status'],
			);
		}

		if ( isset( $global['featured_only'] ) && true === $global['featured_only'] ) {
			$query_args['tax_query'][] = array(
				'taxonomy' => 'product_visibility',
				'field'    => 'name',
				'terms'    => 'featured',
			);
		}

		if ( isset( $global['on_sale_only'] ) && true === $global['on_sale_only'] ) {
			$query_args['meta_query'][] = array(
				'relation' => 'OR',
				array(
					'key'     => '_sale_price',
					'value'   => 0,
					'compare' => '>',
					'type'    => 'numeric',
				),
				array(
					'key'     => '_min_variation_sale_price',
					'value'   => 0,
					'compare' => '>',
					'type'    => 'numeric',
				),
			);
		}

		$query = new \WP_Query( $query_args );

		return $query;
	}

	/**
	 * Specific recommendation product query.
	 *
	 * @param array $settings Finch Cart settings options.
	 * @param int   $product_id Current product id.
	 * @return object
	 */
	public function get_specific_recommendation_query( $settings, $product_id ) {
		$query                = '';
		$product_meta         = get_post_meta( $product_id, 'finch_cart_product_meta_', true );
		$specific             = $this->get_specific_recommendations( $product_id );
		$recommendations_type = isset( $product_meta['finchcart_specific_product_recommendations_type'] ) ? sanitize_text_field( $product_meta['finchcart_specific_product_recommendations_type'] ) : '';

		$query_args = array(
			'post_type'           => 'product',
			'post_status'         => 'publish',
			'ignore_sticky_posts' => 1,
			'post__not_in'        => array( $product_id ),
			'numberposts'         => $specific['number_of_products'],
			'orderby'             => $specific['orderby'],
			'order'               => $specific['order'],
		);

		if ( 'price' === $specific['orderby'] ) {
			$query_args['orderby']  = 'meta_value_num';
			$query_args['meta_key'] = '_price';
		}

		if ( 'popularity' === $specific['orderby'] ) {
			$query_args['orderby']  = 'meta_value_num';
			$query_args['meta_key'] = 'total_sales';
		}

		if ( 'rating' === $specific['orderby'] ) {
			$query_args['orderby']  = 'meta_value_num';
			$query_args['meta_key'] = '_wc_average_rating';
		}

		if ( $recommendations_type && 'manual' === $recommendations_type ) {
			$query_args['post__in'] = $specific['manual_recommendations'];
		}

		if ( $recommendations_type && 'dynamic' === $recommendations_type && isset( $specific['categories'] ) && ! empty( $specific['categories'] ) ) {
			$query_args['tax_query'][] = array(
				'taxonomy' => 'product_cat',
				'field'    => 'term_id',
				'terms'    => $specific['categories'],
				'operator' => 'IN',
			);
		}

		if ( $recommendations_type && 'dynamic' === $recommendations_type && isset( $specific['tags'] ) && ! empty( $specific['tags'] ) ) {
			$query_args['tax_query'][] = array(
				'taxonomy' => 'product_tag',
				'field'    => 'term_id',
				'terms'    => $specific['tags'],
				'operator' => 'IN',
			);
		}

		if ( isset( $specific['products_type'] ) && '' !== $specific['products_type'] ) {
			$query_args['tax_query'][] = array(
				'taxonomy' => 'product_type',
				'field'    => 'slug',
				'terms'    => $specific['products_type'],
			);
		}

		if ( isset( $specific['stock_status'] ) && '' !== $specific['stock_status'] ) {
			$query_args['meta_query'][] = array(
				'key'   => '_stock_status',
				'value' => $specific['stock_status'],
			);
		}

		if ( isset( $specific['featured_only'] ) && true === $specific['featured_only'] ) {
			$query_args['tax_query'][] = array(
				'taxonomy' => 'product_visibility',
				'field'    => 'name',
				'terms'    => 'featured',
			);
		}

		if ( isset( $specific['on_sale_only'] ) && true === $specific['on_sale_only'] ) {
			$query_args['meta_query'][] = array(
				'relation' => 'OR',
				array(
					'key'     => '_sale_price',
					'value'   => 0,
					'compare' => '>',
					'type'    => 'numeric',
				),
				array(
					'key'     => '_min_variation_sale_price',
					'value'   => 0,
					'compare' => '>',
					'type'    => 'numeric',
				),
			);
		}

		$query = new \WP_Query( $query_args );

		return $query;
	}

	/**
	 * Slider attributes.
	 *
	 * @param array $settings Finch Cart settings options.
	 * @return array
	 */
	public function get_slider_attr( $settings ) {
		$slider_options = isset( $settings['finchcart_slider_options'] ) ? (array) wp_unslash( $settings['finchcart_slider_options'] ) : '';
		$slider_columns = isset( $settings['finchcart_slider_columns'] ) ? (array) wp_unslash( $settings['finchcart_slider_columns'] ) : '';

		$attr = array(
			'autoplay'            => isset( $slider_options['finchcart_slider_autoplay'] ) ? wc_string_to_bool( $slider_options['finchcart_slider_autoplay'] ) : false,
			'loop'                => isset( $slider_options['finchcart_slider_loop'] ) ? wc_string_to_bool( $slider_options['finchcart_slider_loop'] ) : false,
			'autoplayspeed'       => isset( $slider_options['finchcart_slider_autoplay_speed'] ) ? absint( $slider_options['finchcart_slider_autoplay_speed'] ) : '',
			'columnsgap'          => isset( $slider_options['finchcart_slider_columns_gap'] ) ? absint( $slider_options['finchcart_slider_columns_gap'] ) : '',
			'columnsdesktop'      => isset( $slider_columns['finchcart_slider_columns_desktop'] ) ? absint( $slider_columns['finchcart_slider_columns_desktop'] ) : '',
			'columnssmalldesktop' => isset( $slider_columns['finchcart_slider_columns_small_desktop'] ) ? absint( $slider_columns['finchcart_slider_columns_small_desktop'] ) : '',
			'columnstablet'       => isset( $slider_columns['finchcart_slider_columns_tablet'] ) ? absint( $slider_columns['finchcart_slider_columns_tablet'] ) : '',
			'columnslargemobile'  => isset( $slider_columns['finchcart_slider_columns_large_mobile'] ) ? absint( $slider_columns['finchcart_slider_columns_large_mobile'] ) : '',
			'columnsmobile'       => isset( $slider_columns['finchcart_slider_columns_mobile'] ) ? absint( $slider_columns['finchcart_slider_columns_mobile'] ) : '',
		);

		if ( is_rtl() ) {
			$attr['dir'] = array(
				'value' => 'rtl',
				'data'  => false,
			);
		}

		return $attr;
	}

	/**
	 * Popup content settings.
	 *
	 * @param array $settings Finch Cart settings options.
	 * @return array
	 */
	public function get_popup_content_settings( $settings ) {
		$content = array(
			'show_product_image'    => isset( $settings['finchcart_show_product_image'] ) ? wc_string_to_bool( $settings['finchcart_show_product_image'] ) : '',
			'show_product_price'    => isset( $settings['finchcart_show_product_price'] ) ? wc_string_to_bool( $settings['finchcart_show_product_price'] ) : '',
			'show_product_rating'   => isset( $settings['finchcart_show_product_rating'] ) ? wc_string_to_bool( $settings['finchcart_show_product_rating'] ) : '',
			'show_product_title'    => isset( $settings['finchcart_show_product_title'] ) ? wc_string_to_bool( $settings['finchcart_show_product_title'] ) : '',
			'show_product_cart_btn' => isset( $settings['finchcart_show_product_cart_btn'] ) ? wc_string_to_bool( $settings['finchcart_show_product_cart_btn'] ) : '',
		);

		return $content;
	}

	/**
	 * Get recommendation products.
	 *
	 * @param array $settings Finch Cart settings options.
	 * @param int   $product_id Current product id.
	 * @return array
	 */
	public function get_recommended_products( $settings, $product_id ) {
		$recommended_products             = array();
		$product_meta                     = get_post_meta( $product_id, 'finch_cart_product_meta_', true );
		$override_product_recommendations = isset( $product_meta['finchcart_override_product_recommendations'] ) ? wc_string_to_bool( $product_meta['finchcart_override_product_recommendations'] ) : '';

		if ( true === $override_product_recommendations ) {
			$recommended_products = $this->get_specific_recommendation_query( $settings, $product_id );
		} else {
			$recommended_products = $this->get_global_recommendation_query( $settings, $product_id );
		}

		return $recommended_products;
	}

	/**
	 * Get all require data for popup modal
	 *
	 * @param int $product_id Current product id.
	 * @return array
	 */
	public function get_template_data( $product_id ) {
		$product              = wc_get_product( $product_id );
		$template_data        = array();
		$recommended_products = array();
		$settings             = get_option( 'finchcart_settings_' );
		$product_meta         = get_post_meta( $product_id, 'finch_cart_product_meta_', true );

		$template_data['product_id']   = $product_id;
		$template_data['checked_icon'] = wp_kses( '<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="24" height="24" fill="white"/><path fill-rule="evenodd" clip-rule="evenodd" d="M2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12ZM15.7071 9.29289C16.0976 9.68342 16.0976 10.3166 15.7071 10.7071L12.0243 14.3899C11.4586 14.9556 10.5414 14.9556 9.97568 14.3899L8.29289 12.7071C7.90237 12.3166 7.90237 11.6834 8.29289 11.2929C8.68342 10.9024 9.31658 10.9024 9.70711 11.2929L11 12.5858L14.2929 9.29289C14.6834 8.90237 15.3166 8.90237 15.7071 9.29289Z" fill="#323232"/></svg>', fc_kses_allowed_svg() );
		$template_data['cart_icon']    = wp_kses( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><path d="M27 25.15 25.28 10.5a2.93 2.93 0 0 0-3-2.5h-1.35c0-.19 0-.38-.06-.57-.22-1.54-.41-2.87-1.59-4a4.51 4.51 0 0 0-6.56 0c-1.18 1.14-1.37 2.47-1.59 4 0 .19 0 .38-.06.57H9.69a2.93 2.93 0 0 0-3 2.5L5 25.15a4.13 4.13 0 0 0 1 3.26A4.87 4.87 0 0 0 9.72 30h12.56a4.87 4.87 0 0 0 3.64-1.59A4.13 4.13 0 0 0 27 25.15zM13.11 7.71c.22-1.52.34-2.21 1-2.85A2.78 2.78 0 0 1 16 4a2.78 2.78 0 0 1 1.89.86c.66.64.78 1.33 1 2.85V8h-5.8c.01-.1.01-.19.02-.29zm11.31 19.37a2.83 2.83 0 0 1-2.14.92H9.72a2.83 2.83 0 0 1-2.14-.92 2.14 2.14 0 0 1-.58-1.7l1.7-14.65a.94.94 0 0 1 1-.73H11c0 .38.05.76.1 1.14a1 1 0 1 0 2-.28c0-.29 0-.57-.06-.86H19c0 .29 0 .57-.06.86a1 1 0 0 0 .8 1.14h.14a1 1 0 0 0 1-.86c.05-.38.08-.76.1-1.14h1.34a.94.94 0 0 1 1 .73L25 25.38a2.14 2.14 0 0 1-.58 1.7z" style="fill:#231f20" data-name="shopping bag"/></svg>', fc_kses_allowed_svg() );

		// Notification bar data.
		$template_data = array_merge( $template_data, $this->get_notification_bar_data( $settings ) );

		// Heading data.
		$template_data = array_merge( $template_data, $this->get_heading_data( $settings, $product_id ) );

		// Product Recommendations.
		$individual_product_recommendations = isset( $settings['finchcart_individual_product_recommendations'] ) ? wc_string_to_bool( $settings['finchcart_individual_product_recommendations'] ) : '';
		$template_data['show_products']     = isset( $settings['finchcart_global_product_recommendations'] ) ? wc_string_to_bool( $settings['finchcart_global_product_recommendations'] ) : '';

		if ( isset( $product_meta['finchcart_specific_product_recommendations'] ) && 'default' !== $product_meta['finchcart_specific_product_recommendations'] && true === $individual_product_recommendations ) {
			if ( 'yes' === $product_meta['finchcart_specific_product_recommendations'] ) {
				$template_data['show_products'] = true;
			} elseif ( 'no' === $product_meta['finchcart_specific_product_recommendations'] ) {
				$template_data['show_products'] = false;
			}
		}

		// Product Query.
		$template_data['recommended_products'] = $this->get_recommended_products( $settings, $product_id );

		// Product Content.
		$template_data = array_merge( $template_data, $this->get_popup_content_settings( $settings ) );

		// Popup Content - Products.
		$template_data['products_layout'] = isset( $settings['finchcart_products_layout'] ) ? sanitize_text_field( $settings['finchcart_products_layout'] ) : 'grid';
		$template_data['slider_atts']     = $this->get_slider_attr( $settings );

		return apply_filters( 'finchcart_template_data', $template_data, $settings, $product_id );
	}

	/**
	 * Ajax added to cart popup content
	 *
	 * @return void
	 */
	public function added_to_cart_popup() {
		// phpcs:disable WordPress.Security.NonceVerification.Missing
		$product_id = isset( $_POST['product_id'] ) ? intval( $_POST['product_id'] ) : '';
		$popup_data = $this->get_template_data( $product_id );

		ob_start();
		include $this->get_templates_path( 'templates/template-modal-content.php' );
		$modal_content = ob_get_clean();

		if ( $modal_content ) {
			wp_send_json_success( $modal_content );
		}
		// phpcs:enable
	}

	/**
	 * Ajax inside popup added to cart notice
	 *
	 * @return void
	 */
	public function inside_popup_added_to_cart_notice() {
		// phpcs:disable WordPress.Security.NonceVerification.Missing
		$product_id      = isset( $_POST['product_id'] ) ? intval( $_POST['product_id'] ) : '';
		$popup_data      = $this->get_template_data( $product_id );
		$current_product = wc_get_product( $product_id );

		ob_start();

		printf(
			'<div class="finchcart-notice-text">%s %s</div>',
			wp_kses( $popup_data['checked_icon'], fc_kses_allowed_svg() ),
			isset( $popup_data['notice_message_text'] ) ? wp_kses_post( str_replace( '%title%', '<strong>' . esc_html( $current_product->get_name() ) . '</strong>', $popup_data['notice_message_text'] ) ) : '',
		);

		$output = ob_get_clean();

		if ( $output ) {
			wp_send_json_success( $output );
		}
		// phpcs:enable
	}

	/**
	 * Ajax cart count update in the popup
	 *
	 * @param array $fragments The WooCommerce add_to_cart fragments.
	 * @return array
	 */
	public function update_cart_items_count( $fragments ) {
		ob_start();
		?>
		<span class="finchcart-cart-total"><?php echo esc_html( WC()->cart->get_cart_contents_count() ); ?></span>
		<?php
		$fragments['a.finchcart-cart-count .finchcart-cart-total'] = ob_get_clean();
		return $fragments;
	}
}