<?php

namespace Quicker\Utils;

defined( 'ABSPATH' ) || exit;

/**
 * Helper function
 */
class Helper {

	use Singleton;

	/**
	 * Html markup validation
	 */
	public static function kses( $raw ) {
		$allowed_tags = array(
			'a'                             => array(
				'class'  => array(),
				'href'   => array(),
				'rel'    => array(),
				'title'  => array(),
				'target' => array(),
			),
			'input'                         => array(
				'value'       => array(),
				'type'        => array(),
				'size'        => array(),
				'name'        => array(),
				'checked'     => array(),
				'placeholder' => array(),
				'id'          => array(),
				'class'       => array(),
				'data-name'   => array(),
			),

			'select'                        => array(
				'value'       => array(),
				'type'        => array(),
				'size'        => array(),
				'name'        => array(),
				'placeholder' => array(),
				'id'          => array(),
				'class'       => array(),
				'multiple'    => array(),
				'data-option' => array(),
				'data-name'   => array(),
				'data-id'     => array(),
			),
			'option'                        => array(
				'selected' => array(),
				'value'    => array(),
				'disabled' => array(),
			),
			'textarea'                      => array(
				'value'       => array(),
				'type'        => array(),
				'size'        => array(),
				'name'        => array(),
				'rows'        => array(),
				'cols'        => array(),
				'placeholder' => array(),
				'id'          => array(),
				'class'       => array(),
			),
			'abbr'                          => array(
				'title' => array(),
			),
			'b'                             => array(),
			'blockquote'                    => array(
				'cite' => array(),
			),
			'cite'                          => array(
				'title' => array(),
			),
			'code'                          => array(),
			'del'                           => array(
				'datetime' => array(),
				'title'    => array(),
			),
			'dd'                            => array(),
			'div'                           => array(
				'data'  => array(),
				'class' => array(),
				'id'    => array(),
				'title' => array(),
				'style' => array(),
			),
			'dl'                            => array(),
			'dt'                            => array(),
			'em'                            => array(),
			'h1'                            => array(
				'class' => array(),
			),
			'h2'                            => array(
				'class' => array(),
			),
			'h3'                            => array(
				'class' => array(),
			),
			'h4'                            => array(
				'class' => array(),
			),
			'h5'                            => array(
				'class' => array(),
			),
			'h6'                            => array(
				'class' => array(),
			),
			'i'                             => array(
				'class' => array(),
			),
			'img'                           => array(
				'alt'    => array(),
				'class'  => array(),
				'height' => array(),
				'src'    => array(),
				'width'  => array(),
			),
			'li'                            => array(
				'class' => array(),
			),
			'ol'                            => array(
				'class' => array(),
			),
			'p'                             => array(
				'class' => array(),
			),
			'q'                             => array(
				'cite'  => array(),
				'title' => array(),
			),
			'span'                          => array(
				'class' => array(),
				'title' => array(),
				'style' => array(),
			),
			'small'                         => array(
				'class' => array(),
				'title' => array(),
				'style' => array(),
			),
			'iframe'                        => array(
				'width'       => array(),
				'height'      => array(),
				'scrolling'   => array(),
				'frameborder' => array(),
				'allow'       => array(),
				'src'         => array(),
			),
			'strike'                        => array(),
			'br'                            => array(),
			'strong'                        => array(),
			'data-wow-duration'             => array(),
			'data-wow-delay'                => array(),
			'data-wallpaper-options'        => array(),
			'data-stellar-background-ratio' => array(),
			'ul'                            => array(
				'class' => array(),
			),
			'label'                         => array(
				'class' => array(),
				'for'   => array(),
			),
		);

		if ( function_exists( 'wp_kses' ) ) { // WP is here
			return wp_kses( $raw, $allowed_tags );
		} else {
			return $raw;
		}
	}

	/**
	 * Return inline sanitized SVG markup if $url points to an SVG within site, else <img> fallback.
	 * Adds wrapper span for styling: .quicker-icon .is-svg / .is-img
	 */
	public static function inline_svg_or_img( $url, $attrs = array() ) {
		$url = trim( (string) $url );
		if ( $url === '' ) { return ''; }
		$ext = strtolower( pathinfo( wp_parse_url( $url, PHP_URL_PATH ), PATHINFO_EXTENSION ) );
		$attr_str = '';
		foreach ( (array) $attrs as $k => $v ) {
			$attr_str .= ' ' . esc_attr( $k ) . '="' . esc_attr( $v ) . '"';
		}
		if ( $ext !== 'svg' ) {
			return '<span class="quicker-icon is-img"><img src="' . esc_url( $url ) . '"' . $attr_str . ' alt="" /></span>';
		}
		// Try multiple strategies to locate local file path for the SVG.
		$local_path = str_replace( home_url(), ABSPATH, $url );
		if ( ! file_exists( $local_path ) ) {
			$parsed = wp_parse_url( $url );
			if ( isset( $parsed['path'] ) ) {
				$path = wp_normalize_path( $parsed['path'] );
				// If site in subdirectory, strip leading subdir part already in ABSPATH to avoid duplication.
				$home_path = wp_normalize_path( wp_parse_url( home_url(), PHP_URL_PATH ) );
				if ( $home_path && strpos( $path, $home_path ) === 0 ) {
					$relative = substr( $path, strlen( $home_path ) );
				} else {
					$relative = $path;
				}
				$candidate = wp_normalize_path( untrailingslashit( ABSPATH ) . $relative );
				if ( file_exists( $candidate ) ) { $local_path = $candidate; }
			}
		}
		if ( ! file_exists( $local_path ) || ! is_readable( $local_path ) ) {
			// Remote fetch fallback (handles cases where SVG served from plugins dir but path mapping failed)
			if ( function_exists( 'wp_remote_get' ) ) {
				$response = wp_remote_get( $url, array( 'timeout' => 2 ) );
				if ( ! is_wp_error( $response ) && 200 === wp_remote_retrieve_response_code( $response ) ) {
					$body = wp_remote_retrieve_body( $response );
					if ( strpos( $body, '<svg' ) !== false ) {
						$body = preg_replace( '/<script[\s\S]*?<\/script>/', '', $body );
							$allowed = array(
								'svg'   => array( 'xmlns'=>true,'viewBox'=>true,'width'=>true,'height'=>true,'fill'=>true,'stroke'=>true,'stroke-width'=>true,'stroke-linecap'=>true,'stroke-linejoin'=>true,'class'=>true ),
								'path'  => array( 'd'=>true,'fill'=>true,'stroke'=>true,'stroke-width'=>true,'stroke-linecap'=>true,'stroke-linejoin'=>true,'fill-rule'=>true,'clip-rule'=>true ),
								'circle'=> array( 'cx'=>true,'cy'=>true,'r'=>true,'fill'=>true,'stroke'=>true,'stroke-width'=>true ),
								'rect'  => array( 'x'=>true,'y'=>true,'width'=>true,'height'=>true,'rx'=>true,'ry'=>true,'fill'=>true,'stroke'=>true,'stroke-width'=>true ),
								'g'     => array( 'fill'=>true,'stroke'=>true,'stroke-width'=>true,'stroke-linecap'=>true,'stroke-linejoin'=>true ),
							);
						return '<span class="quicker-icon is-svg">' . wp_kses( $body, $allowed ) . '</span>';
					}
				}
			}
			return '<span class="quicker-icon is-img"><img src="' . esc_url( $url ) . '"' . $attr_str . ' alt="" /></span>';
		}
		$raw = file_get_contents( $local_path );
		$raw = preg_replace( '/<script[\s\S]*?<\/script>/', '', $raw );
		$allowed = array(
			'svg'   => array( 'xmlns'=>true,'viewBox'=>true,'width'=>true,'height'=>true,'fill'=>true,'stroke'=>true,'stroke-width'=>true,'stroke-linecap'=>true,'stroke-linejoin'=>true,'class'=>true ),
			'path'  => array( 'd'=>true,'fill'=>true,'stroke'=>true,'stroke-width'=>true,'stroke-linecap'=>true,'stroke-linejoin'=>true,'fill-rule'=>true,'clip-rule'=>true ),
			'circle'=> array( 'cx'=>true,'cy'=>true,'r'=>true,'fill'=>true,'stroke'=>true,'stroke-width'=>true ),
			'rect'  => array( 'x'=>true,'y'=>true,'width'=>true,'height'=>true,'rx'=>true,'ry'=>true,'fill'=>true,'stroke'=>true,'stroke-width'=>true ),
			'g'     => array( 'fill'=>true,'stroke'=>true,'stroke-width'=>true,'stroke-linecap'=>true,'stroke-linejoin'=>true ),
		);
		$sanitized = wp_kses( $raw, $allowed );
		// If SVG has a viewBox, we can remove width/height for scalability; else keep them or add a synthetic viewBox.
		$has_viewbox = stripos( $sanitized, 'viewBox=' ) !== false;
		if ( $has_viewbox ) {
			$sanitized = preg_replace( '/\s(width|height)="[0-9\.]+(%|px)?"/i', '', $sanitized );
		} else {
			// Attempt to extract width/height; if present, synthesize a viewBox; if missing, add default 24.
			$width_match  = array();
			$height_match = array();
			preg_match( '/width="([0-9\.]+)"/i', $sanitized, $width_match );
			preg_match( '/height="([0-9\.]+)"/i', $sanitized, $height_match );
			$w = isset( $width_match[1] ) ? (float) $width_match[1] : 24;
			$h = isset( $height_match[1] ) ? (float) $height_match[1] : 24;
			$sanitized = preg_replace_callback( '/<svg([^>]*)>/i', function( $m ) use ( $w, $h ) {
				$attrs = $m[1];
				if ( stripos( $attrs, 'viewBox=' ) === false ) {
					$attrs .= ' viewBox="0 0 ' . max(1,$w) . ' ' . max(1,$h) . '"';
				}
				return '<svg' . $attrs . '>';
			}, $sanitized );
		}
		return '<span class="quicker-icon is-svg">' . $sanitized . '</span>';
	}

	/**
	 * Show Notices
	 */
	public static function push( $notice ) {

		$defaults = array(
			'id'               => '',
			'type'             => 'info',
			'show_if'          => true,
			'message'          => '',
			'class'            => 'active-notice',
			'dismissible'      => false,
			'btn'              => array(),
			'dismissible-meta' => 'user',
			'dismissible-time' => WEEK_IN_SECONDS,
			'data'             => '',
		);

		$notice = wp_parse_args( $notice, $defaults );

		$classes = array( 'notice', 'notice' );

		$classes[] = $notice['class'];

		if ( isset( $notice['type'] ) ) {
			$classes[] = 'notice-' . $notice['type'];
		}

		// Is notice dismissible?
		if ( true === $notice['dismissible'] ) {
			$classes[] = 'is-dismissible';

			// Dismissable time.
			$notice['data'] = ' dismissible-time=' . esc_attr( $notice['dismissible-time'] ) . ' ';
		}

		// Notice ID.
		$notice_id    = 'sites-notice-id-' . $notice['id'];
		$notice['id'] = $notice_id;

		if ( ! isset( $notice['id'] ) ) {
			$notice_id    = 'sites-notice-id-' . $notice['id'];
			$notice['id'] = $notice_id;
		} else {
			$notice_id = $notice['id'];
		}

		$notice['classes'] = implode( ' ', $classes );

		// User meta.
		$notice['data'] .= ' dismissible-meta=' . esc_attr( $notice['dismissible-meta'] ) . ' ';

		if ( 'user' === $notice['dismissible-meta'] ) {
			$expired = get_user_meta( get_current_user_id(), $notice_id, true );
		} elseif ( 'transient' === $notice['dismissible-meta'] ) {
			$expired = get_transient( $notice_id );
		}

		// Notice visible after transient expire.
		if ( isset( $notice['show_if'] ) ) {
			if ( true === $notice['show_if'] ) {
				// Is transient expired?
				if ( false === $expired || empty( $expired ) ) {
					self::markup( $notice );
				}
			}
		} else {
			self::markup( $notice );
		}
	}

	/**
	 * Markup Notice.
	 */
	public static function markup( $notice = array() ) {
		?>
		<div id="<?php echo esc_attr( $notice['id'] ); ?>" class="<?php echo esc_attr( $notice['classes'] ); ?>" <?php echo esc_html( $notice['data'] ); ?>>
			<p>
				<?php echo esc_html( $notice['message'] ); ?>
			</p>

			<?php if ( ! empty( $notice['btn'] ) ) : ?>
				<p>
					<a href="<?php echo esc_url( $notice['btn']['url'] ); ?>" class="button-primary"><?php echo esc_html( $notice['btn']['label'] ); ?></a>
				</p>
			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Admin pages array
	 *
	 * @return array
	 */
	public static function admin_pages_id() {
		$admin_pages = array(
			'toplevel_page_quicker',
			'quicker_page_quicker-settings',
			'quicker_page_quicker-license',
			'quicker_page_quicker-checkout-fields',
		);

		return $admin_pages;
	}

	/**
	 * Default Field
	 */
	public static function checkout_fields_defaults() {
		return array(
			array(
				'field_type'        => 'billing',
				'field_label'       => esc_html__( 'First Name', 'quicker' ),
				'field_name'        => 'billing_first_name',
				'field_placeholder' => '',
				'field_required'    => 'Yes',
				'field_enabled'     => 'Yes',
				'field_position'    => '',
			),
			array(
				'field_type'        => 'billing',
				'field_label'       => esc_html__( 'Last Name', 'quicker' ),
				'field_name'        => 'billing_last_name',
				'field_placeholder' => '',
				'field_required'    => 'Yes',
				'field_enabled'     => 'Yes',
				'field_position'    => '',
			),
			array(
				'field_type'        => 'billing',
				'field_label'       => esc_html__( 'Company Name', 'quicker' ),
				'field_name'        => 'billing_company',
				'field_placeholder' => '',
				'field_required'    => 'Yes',
				'field_enabled'     => 'Yes',
				'field_position'    => '',
			),
			array(
				'field_type'        => 'billing',
				'field_label'       => esc_html__( 'Country/Region', 'quicker' ),
				'field_name'        => 'billing_country',
				'field_placeholder' => '',
				'field_required'    => 'Yes',
				'field_enabled'     => 'Yes',
				'field_position'    => '',
			),
			array(
				'field_type'        => 'billing',
				'field_label'       => esc_html__( 'Address 1', 'quicker' ),
				'field_name'        => 'billing_address_1',
				'field_placeholder' => '',
				'field_required'    => 'Yes',
				'field_enabled'     => 'Yes',
				'field_position'    => '',
			),
			array(
				'field_type'        => 'billing',
				'field_label'       => esc_html__( 'Address 2', 'quicker' ),
				'field_name'        => 'billing_address_2',
				'field_placeholder' => '',
				'field_required'    => 'Yes',
				'field_enabled'     => 'Yes',
				'field_position'    => '',
			),
			array(
				'field_type'        => 'billing',
				'field_label'       => esc_html__( 'City', 'quicker' ),
				'field_name'        => 'billing_city',
				'field_placeholder' => '',
				'field_required'    => 'Yes',
				'field_enabled'     => 'Yes',
				'field_position'    => '',
			),
			array(
				'field_type'        => 'billing',
				'field_label'       => esc_html__( 'Country/State', 'quicker' ),
				'field_name'        => 'billing_state',
				'field_placeholder' => '',
				'field_required'    => 'Yes',
				'field_enabled'     => 'Yes',
				'field_position'    => '',
			),
			array(
				'field_type'        => 'billing',
				'field_label'       => esc_html__( 'Postcode', 'quicker' ),
				'field_name'        => 'billing_postcode',
				'field_placeholder' => '',
				'field_required'    => 'Yes',
				'field_enabled'     => 'Yes',
				'field_position'    => '',
			),
			array(
				'field_type'        => 'billing',
				'field_label'       => esc_html__( 'Phone', 'quicker' ),
				'field_name'        => 'billing_phone',
				'field_placeholder' => '',
				'field_required'    => 'Yes',
				'field_enabled'     => 'Yes',
				'field_position'    => '',
			),
		);
	}

	/**
	 * Default Field Key
	 */
	public static function checkout_fields_defaults_key() {
		return array( 'field_type', 'input_type', 'field_label', 'field_name', 'field_placeholder', 'field_required', 'field_enabled', 'field_position', 'display_in_emails', 'display_in_order_details', 'field_user_roles', 'field_options', 'field_conditions', 'field_condition_action', 'field_condition_enabled' );
	}

	/**
	 * Settings option
	 */
	public static function get_settings_key() {

		$settings_key = array(
			'upsell_heading'           => esc_html__( 'You may choose', 'quicker' ),
			'enable_buy_now'           => 'no',
			'custom_cart_url'          => '#',
			'enable_single_buy_now'    => '',
			'mix_max_order_msg'   	   => '',
			'direct_checkout_button_behavior' => 'replace',
			'enable_one_click_checkout' => 'no',
			'one_click_button_text' => 'Buy Now',
			'one_click_scope' => 'all',
			'one_click_products' => array(),
			'direct_checkout_button_text' => '',
			'direct_checkout_scope'    => 'entire',
			'direct_checkout_entire_store' => 'no',
			'direct_checkout_categories' => array(),
			'direct_checkout_products'   => array(),
			'bump_product_type'        => 'both',
			'custom_price'             => '',
			'custom_price_label'       => '',
			'quicker_view'             => 'no',
			'mix_max_order'            => '',
			'quicker_btn_label'        => esc_html__( 'Quick View', 'quicker' ),
			'min_order_amount'         => '',
			'max_order_amount'         => '',
			'mix_max_order_roles'      => array(),
			'mix_max_order_qty'            => '',
			'min_order_quantity'           => '',
			'max_order_quantity'           => '',
			'default_order_quantity'       => '',
			'mix_max_order_qty_msg'        => '',
			'mix_max_qty_roles'            => array(),
			'mix_max_qty_scope'            => 'all',
			'mix_max_qty_products'         => array(),
			'mix_max_qty_categories'       => array(),
			'default_quantity'         => '',
			'enable_mini_cart'         => 'yes',
			'enable_cart_upsell'       => 'no',
			'up_sell_products'         => array(),
			'side_cart_style'          => '1',
			'cart_order_bump_style'    => '1',
			'sc_bg_color'             => '#ffffff',
			'sc_title_color'          => '#24272d',
			'sc_product_name_color'   => '#24272d',
			'sc_subtotal_label_font_size' => '14',
			'sc_subtotal_label_color'    => '#24272d',
			'sc_subtotal_price_font_size' => '14',
			'sc_subtotal_price_color'    => '#24272d',
			'sc_fees_label_font_size'    => '14',
			'sc_fees_label_color'        => '#24272d',
			'sc_fees_price_font_size'    => '14',
			'sc_fees_price_color'        => '#24272d',
			'sc_total_label_font_size'   => '14',
			'sc_total_label_color'       => '#24272d',
			'sc_total_price_font_size'   => '14',
			'sc_total_price_color'       => '#24272d',
			'sc_total_extra_text_font_size' => '13',
			'sc_total_extra_text_color'  => '#888888',
			'sc_icon_position'        => 'bottom',
			'sc_icon_bottom'          => '20',
			'sc_icon_type'            => 'cart-1',
			'sc_icon_color'           => '#000000',
			'sc_icon_bg_color'        => '#ffffff',
			'sc_icon_border_radius'   => '50',
			'sc_count_bg_color'       => '#ff0000',
			'sc_count_text_color'     => '#ffffff',
			'sc_checkout_bg_color'    => '#0170b9',
			'sc_checkout_text_color'  => '#ffffff',
			'sc_checkout_hover_color' => '',
			'sc_padding_top'          => '12',
			'sc_padding_bottom'       => '12',
			'sc_padding_left'         => '0',
			'sc_padding_right'        => '0',
			'sc_item_border_top'      => '0',
			'sc_item_border_bottom'   => '1',
			'sc_item_border_left'     => '0',
			'sc_item_border_right'    => '0',
			'sc_item_border_type'     => 'solid',
			'sc_item_border_color'    => '#e0e0e0',
			'sc_coupon_bg_color'      => '#046bd2',
			'sc_coupon_text_color'    => '#ffffff',
			'sc_coupon_field_bg_color' => '#ffffff',
			'sc_coupon_title_font_size' => '14',
			'sc_coupon_title_color'    => '#24272d',
			'sc_coupon_border_top'     => '1',
			'sc_coupon_border_bottom'  => '1',
			'sc_coupon_border_left'    => '0',
			'sc_coupon_border_right'   => '0',
			'sc_coupon_border_type'    => 'solid',
			'sc_coupon_border_color'   => '#e0e0e0',
			'sc_remove_icon_color'    => '#1C274C',
			'sc_remove_icon_size'     => '22',
			'sc_price_calc_color'     => '#888888',
			'sc_price_calc_font_size' => '14',
			'sc_qty_color'            => '#24272d',
			'sc_qty_border_color'     => '#eaeaec',
			'sc_qty_btn_bg'           => '#f9f9f9',
			'sc_qty_border_top'       => '1',
			'sc_qty_border_bottom'    => '1',
			'sc_qty_border_left'      => '1',
			'sc_qty_border_right'     => '1',
			'sc_price_total_font_size' => '14',
			// Order Bump styles.
			'ob_bg_color'              => '#edf8ff',
			'ob_header_color'          => '#24272d',
			'ob_font_size'             => '15',
			'ob_padding_top'           => '12',
			'ob_padding_bottom'        => '12',
			'ob_padding_left'          => '10',
			'ob_padding_right'         => '10',
			'ob_name_color'            => '#333333',
			'ob_name_font_size'        => '12',
			'ob_name_margin_top'       => '6',
			'ob_name_margin_bottom'    => '0',
			'ob_price_color'           => '#555555',
			'ob_price_font_size'       => '12',
			'ob_price_margin_top'      => '2',
			'ob_price_margin_bottom'   => '4',
			'ob_icon_size'             => '18',
			'ob_icon_color'            => '#046bd2',
			'ob_arrow_color'           => '#046bd2',
			'ob_arrow_size'            => '20',
			'price_field_type'         => '',
			'multi_step_checkout'      => '',
			'enable_multi_step_checkout' => 'no',
			'msc_cart_step'            => 'yes',
			'msc_login_step'           => 'yes',
			'msc_coupon_step'          => 'yes',
			'msc_billing_shipping_step' => 'yes',
			'msc_cart_step_label'      => 'Cart',
			'msc_login_step_label'     => 'Login',
			'msc_coupon_step_label'    => 'Coupon',
			'msc_billing_shipping_step_label' => 'Billing & Shipping',
			'msc_payment_step_label'   => 'Payment',
			'msc_checkout_style'       => 'horizontal',
			'msc_step_text_color'      => '#333333',
			'msc_step_bg_color'        => '#f5f5f5',
			'msc_step_bg_color_active' => '#0073aa',
			'msc_step_text_color_active' => '#ffffff',
			'msc_step_separator_color' => '#dddddd',
			'msc_step_hover_color'     => '#0073aa',
			'msc_btn_bg_color'         => '#197beb',
			'msc_btn_text_color'       => '#ffffff',
			'msc_btn_hover_bg_color'   => '#1565c0',
			'msc_btn_hover_text_color' => '#ffffff',
			'cod_charge'               => 'no',
			'ajax_add_to_cart'         => 'no',
			'enable_extra_fees'        => 'no',
			'extra_fees_scope'         => 'all', // all|products|categories
			'extra_fees_cart_total'    => '',
			'extra_fees_cart_quantity' => '',
			'extra_fees_products'      => array(),
			'extra_fees_categories'    => array(),
			'extra_fees_user_roles'    => array(), // empty array means all
			'extra_fees_label'         => esc_html__( 'Extra Fee', 'quicker' ),
			'extra_fees_amount'        => '',
			'extra_fees_description'   => '',
			'show_coupon_form'         => 'yes',
			'cod_charge_amount'        => '',
			'cod_charge_label'         => esc_html__( 'Delivery Charge', 'quicker' ),
			'cod_min_cart'             => '',
			'cod_min_cart_charge'      => '',
			'cod_min_cart_msg'         => '',
			'add_cart_text'            => '',
			'quickview_content_bg'     => '',
			'quickview_overlay'        => '',
			'qview_icon'               => '',
			'quickview_icon'           => '',
			'quickview_icon_hover'     => '',
			'quickview_btn_color'      => '',
			'quickview_btn_hover'      => '',
			'quickview_text_color'     => '',
			'quickview_text_hover'     => '',
			'quickview_close'          => '',
			'quickview_close_hover'    => '',
			'hide_quicker_view_mobile' => '',
			'stick_add_to_cart_btn' 	   => 'no',
			'enable_product_addons'    => 'yes',
			'quicker_view_desc'        => 'no',
			'quicker_view_options'     => array(),
			'quicker_view_btn_postion' => 'after_cart_btn',
		);

		return $settings_key;
	}

	/**
	 * Get WooCommerce product categories as id => name pairs.
	 */
	public static function get_product_categories() {
		$terms = get_terms(
			array(
				'taxonomy'   => 'product_cat',
				'hide_empty' => false,
			)
		);
		$cats = array();
		if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
			foreach ( $terms as $term ) {
				$cats[ $term->term_id ] = $term->name;
			}
		}
		return $cats;
	}

	/**
	 * Look up product/variation IDs used in any saved checkout-field condition
	 * and return an id => name map. Used by the admin to prepopulate select2
	 * labels so editing a saved condition shows product names, not raw IDs.
	 *
	 * @return array
	 */
	public static function get_condition_product_labels() {
		$labels = array();
		if ( ! function_exists( 'wc_get_product' ) ) {
			return $labels;
		}

		$posts = get_posts(
			array(
				'post_type'      => 'quicker_ch_fields',
				'posts_per_page' => -1,
				'fields'         => 'ids',
			)
		);
		if ( empty( $posts ) ) {
			return $labels;
		}

		$ids = array();
		foreach ( $posts as $post_id ) {
			$conditions = get_post_meta( $post_id, 'field_conditions', true );
			if ( empty( $conditions ) || ! is_array( $conditions ) ) {
				continue;
			}
			foreach ( $conditions as $row ) {
				if ( empty( $row['condition_field'] ) ) {
					continue;
				}
				if ( ! in_array( $row['condition_field'], array( 'product', 'product_variation' ), true ) ) {
					continue;
				}
				$vals = $row['condition_value'] ?? array();
				if ( ! is_array( $vals ) ) {
					$vals = array_map( 'trim', explode( ',', (string) $vals ) );
				}
				foreach ( $vals as $v ) {
					$v = trim( (string) $v );
					if ( '' !== $v && ctype_digit( $v ) ) {
						$ids[] = (int) $v;
					}
				}
			}
		}

		$ids = array_values( array_unique( array_filter( $ids ) ) );
		foreach ( $ids as $id ) {
			$product = wc_get_product( $id );
			if ( $product ) {
				$labels[ (string) $id ] = wp_strip_all_tags( $product->get_formatted_name() );
			}
		}
		return $labels;
	}

	/**
	 * Get available WooCommerce payment methods as id => title pairs.
	 * Returns enabled gateways for use in conditional logic value dropdowns.
	 */
	public static function get_payment_methods() {
		$methods = array();
		if ( ! function_exists( 'WC' ) || ! WC()->payment_gateways() ) {
			return $methods;
		}
		$gateways = WC()->payment_gateways()->payment_gateways();
		foreach ( $gateways as $id => $gateway ) {
			if ( isset( $gateway->enabled ) && 'yes' !== $gateway->enabled ) {
				continue;
			}
			$methods[ $id ] = $gateway->get_title();
		}
		return $methods;
	}

	/**
	 * Get available WooCommerce shipping methods as id => title pairs.
	 */
	public static function get_shipping_methods() {
		$methods = array();
		if ( ! function_exists( 'WC' ) || ! WC()->shipping() ) {
			return $methods;
		}
		$shipping_methods = WC()->shipping()->get_shipping_methods();
		foreach ( $shipping_methods as $id => $method ) {
			$methods[ $id ] = $method->get_method_title();
		}
		return $methods;
	}

	/**
	 * Get WooCommerce shipping classes as slug => name pairs.
	 */
	public static function get_shipping_classes() {
		$classes = array();
		$terms   = get_terms(
			array(
				'taxonomy'   => 'product_shipping_class',
				'hide_empty' => false,
			)
		);
		if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
			foreach ( $terms as $term ) {
				$classes[ $term->slug ] = $term->name;
			}
		}
		return $classes;
	}

	/**
	 * Get all published simple products as id => title for select fields.
	 */
	public static function get_all_products_for_select() {
		$products = get_posts(
			array(
				'post_type'      => 'product',
				'post_status'    => 'publish',
				'posts_per_page' => 200, // reasonable cap
				'fields'         => 'ids',
			)
		);
		$options = array();
		if ( ! empty( $products ) ) {
			foreach ( $products as $pid ) {
				$title = get_the_title( $pid );
				$options[ $pid ] = $title ? $title : ( 'Product #' . $pid );
			}
		}
		return $options;
	}

	/**
	 * Admin pages array
	 */
	public static function get_settings() {
		$settings     = array();
		$get_settings = get_option( 'quicker_settings', true );
		$settings_key = self::get_settings_key();

		foreach ( $settings_key as $key => $value ) {
			$settings[ $key ] = isset( $get_settings[ $key ] ) && $get_settings[ $key ] !== '' ? $get_settings[ $key ] : $value;
		}

		return $settings;
	}

	/**
	 * Get all checkout fields
	 *
	 * @return array
	 */
	public static function get_checkout_fields( $limit = -1 ) {
		$all_fields = get_posts(
			array(
				'post_type'      => 'quicker_ch_fields',
				'posts_per_page' => $limit,
				'orderby'        => 'menu_order',
				'order'          => 'ASC',
			)
		);
		if ( empty( $all_fields ) ) {
			foreach ( self::checkout_fields_defaults() as $key => $value ) {
				\Quicker\Core\Admin\Settings\Settings::instance()->insert_fields( $value );
			}

			$all_fields = get_posts(
				array(
					'post_type'      => 'quicker_ch_fields',
					'posts_per_page' => $limit,
					'orderby'        => 'menu_order',
					'order'          => 'ASC',
				)
			);
		}

		return self::get_fields_arr( $all_fields );
	}

	/**
	 * Get all checkout fields
	 *
	 * @return array
	 */
	public static function get_fields_arr( $all_fields ) {
		$fields_arr = array();
		if ( ! empty( $all_fields ) ) {
			foreach ( $all_fields as $key => &$value ) {
				$single = self::single_fields( $value );
				array_push( $fields_arr, $single );
			}
		}

		return $fields_arr;
	}

	public static function single_fields( $item ) {
		$new_result                      = array();
		$new_result['ID']                = $item->ID;
		$new_result['input_type']        = get_post_meta( $item->ID, 'input_type', true ) == '' ? 'text' : get_post_meta( $item->ID, 'input_type', true );
		$new_result['field_type']        = get_post_meta( $item->ID, 'field_type', true ) == '' ? 'billing' : get_post_meta( $item->ID, 'field_type', true );
		$new_result['field_label']       = get_post_meta( $item->ID, 'field_label', true );
		$new_result['field_name']        = get_post_meta( $item->ID, 'field_name', true );
		$new_result['field_placeholder'] = get_post_meta( $item->ID, 'field_placeholder', true );
		$new_result['field_required']    = get_post_meta( $item->ID, 'field_required', true );
		$new_result['field_enabled']           = get_post_meta( $item->ID, 'field_enabled', true );
		$new_result['field_position']          = get_post_meta( $item->ID, 'field_position', true );
		$new_result['display_in_emails']       = get_post_meta( $item->ID, 'display_in_emails', true );
		$new_result['display_in_order_details'] = get_post_meta( $item->ID, 'display_in_order_details', true );
		$new_result['field_user_roles']        = get_post_meta( $item->ID, 'field_user_roles', true );
		$new_result['field_options']           = get_post_meta( $item->ID, 'field_options', true );
		$new_result['field_conditions']        = get_post_meta( $item->ID, 'field_conditions', true );
		$new_result['field_condition_action']   = get_post_meta( $item->ID, 'field_condition_action', true );
		$new_result['field_condition_enabled']  = get_post_meta( $item->ID, 'field_condition_enabled', true );

		return $new_result;
	}

	/**
	 * Get woo products
	 */
	public static function get_products( $type = 'all' ) {
		$products = wc_get_products(
			array(
				'limit'  => -1,
				'status' => 'publish',
			)
		);

		$products_arr = array();
		foreach ( $products as $key => $value ) {
			if ( $type == 'all' ) {
				$products_arr[ $value->get_id() ] = $value->get_name();
			} elseif ( 'simple' == $value->get_type() ) {
				$products_arr[ $value->get_id() ] = $value->get_name();
			}
		}

		return $products_arr;
	}

	/**
	 * New checkout field
	 *
	 * @return array
	 */
	public static function checkout_field_type( $select = 'single' ) {
		if ( $select == 'single' ) {
			return array(
				'before_checkout_billing_form'  => esc_html__( 'Before Billing Form', 'quicker' ),
				'after_checkout_billing_form'   => esc_html__( 'After Billing Form', 'quicker' ),
				'before_checkout_shipping_form' => esc_html__( 'Before Shipping Form', 'quicker' ),
				'after_checkout_shipping_form'  => esc_html__( 'After Shipping Form', 'quicker' ),
				'before_order_notes'            => esc_html__( 'Before Order Notes', 'quicker' ),
				'after_order_notes'             => esc_html__( 'After Order Notes', 'quicker' ),
			);
		} else {
			return array(
				'before_checkout_billing_form'  => array( 'type' => 'billing' ),
				'after_checkout_billing_form'   => array( 'type' => 'billing' ),
				'before_checkout_shipping_form' => array( 'type' => 'shipping' ),
				'after_checkout_shipping_form'  => array( 'type' => 'shipping' ),
				'before_order_notes'            => array( 'type' => 'order' ),
				'after_order_notes'             => array( 'type' => 'order' ),
			);
		}
	}


	/**
	 * Format Value
	 */
	public static function format_input_value( $input ) {
		if ( $input == 'Yes' || $input == 'yes' ) {
			return true;
		} elseif ( $input == 'No' || $input == 'no' ) {
			return false;
		}
	}

	/**
	 * check nonce
	 */
	public function verify_nonce( $nonce_index, $nonce_value ) {
		if ( is_null( $nonce_index ) || ! wp_verify_nonce( $nonce_value, $nonce_index ) ) {
			wp_send_json_error(
				array(
					'message' => __( 'Security check failed', 'quicker' ),
					'code'    => 401,
				)
			);
		}
	}

	public static function cart_btn( $args ) {
		extract( $args );
		$icon      = empty( $args['cart_icon'] ) ? '<svg class="cart-icon" viewBox="0 0 256 256" xml:space="preserve">
		<g style="stroke: none; stroke-width: 0; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: none; fill-rule: nonzero; opacity: 1;" transform="translate(1.4065934065934016 1.4065934065934016) scale(2.81 2.81)" >
			<path class="quicker-cart-icon" d="M 72.975 58.994 H 31.855 c -1.539 0 -2.897 -1.005 -3.347 -2.477 L 15.199 13.006 H 3.5 c -1.933 0 -3.5 -1.567 -3.5 -3.5 s 1.567 -3.5 3.5 -3.5 h 14.289 c 1.539 0 2.897 1.005 3.347 2.476 l 13.309 43.512 h 36.204 l 10.585 -25.191 h -6.021 c -1.933 0 -3.5 -1.567 -3.5 -3.5 s 1.567 -3.5 3.5 -3.5 H 86.5 c 1.172 0 2.267 0.587 2.915 1.563 s 0.766 2.212 0.312 3.293 L 76.201 56.85 C 75.655 58.149 74.384 58.994 72.975 58.994 z" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;" transform=" matrix(1 0 0 1 0 0) " stroke-linecap="round" />
			<circle class="quicker-cart-icon" cx="28.88" cy="74.33" r="6.16" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;" transform="  matrix(1 0 0 1 0 0) "/>
			<circle class="quicker-cart-icon" cx="74.59" cy="74.33" r="6.16" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;" transform="  matrix(1 0 0 1 0 0) "/>
			<path class="quicker-cart-icon" d="M 62.278 19.546 H 52.237 V 9.506 c 0 -1.933 -1.567 -3.5 -3.5 -3.5 s -3.5 1.567 -3.5 3.5 v 10.04 h -10.04 c -1.933 0 -3.5 1.567 -3.5 3.5 s 1.567 3.5 3.5 3.5 h 10.04 v 10.04 c 0 1.933 1.567 3.5 3.5 3.5 s 3.5 -1.567 3.5 -3.5 v -10.04 h 10.041 c 1.933 0 3.5 -1.567 3.5 -3.5 S 64.211 19.546 62.278 19.546 z" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;" transform=" matrix(1 0 0 1 0 0) " stroke-linecap="round" />
		</g></svg>' : $cart_icon;
		$btn_text  = empty( $btn_txt ) ? '' : $btn_txt;
		$cart_html = '';

		switch ( $product->get_type() ) {
			case ( $product->get_type() == 'simple' ) && $product->is_in_stock() == true:
				$cart_html .= '<a href="' . $product->add_to_cart_url() . '" value="' . intval( $product->get_id() ) . '"
			class="ajax_add_to_cart add_to_cart_button"
			data-product_id="' . intval( $product->get_id() ) . '"
			data-product_sku="' . esc_attr( $product->get_sku() ) . '"
			> 
			' . $icon . $btn_text . '</a>';
				break;
			case ( $product->get_type() !== 'simple' ) && $product->is_in_stock() == true:
				$cart_html .= '<a href="' . $product->get_permalink() . '" class="">' . $icon . $btn_text . '</a>';

				break;

			default:
				$cart_html .= esc_html__( 'Out of Stock', 'quicker' );
		}

		return $cart_html;
	}

	public static function is_pro_active() {
		if ( ! class_exists( 'QuickerPro' ) ) {
			return false;
		}
		return true;
	}

	/**
	 * Templates
	 *
	 * @param integer $template
	 * @return array
	 */
	public static function get_templates( $template = 1 ) {
		$styles = array();
		for ( $i = 1; $i <= $template; $i++ ) {
			$styles[ $i ] = esc_html__( 'Template', 'quicker' ) . '-' . $i;
		}

		return $styles;
	}

	/**
	 * Add custom class
	 *
	 * @param [type] $data
	 * @return string
	 */
	public static function d_none_class( $data ) {
		if ( is_array( $data ) ) {
			// If all values are 'yes', return '', else 'd-none'
			foreach ( $data as $val ) {
				if ( $val !== 'yes' ) {
					return 'd-none';
				}
			}
			return '';
		} else {
			return ( $data == 'yes' ) ? '' : 'd-none';
		}
	}

	public static function woo_currency() {
		return class_exists( 'WooCommerce' ) ? get_woocommerce_currency_symbol() : '$';
	}

	/**
	 * Get cart icon SVG markup by type.
	 *
	 * @param string $type Icon type key.
	 * @return string Inline SVG markup.
	 */
	public static function get_cart_icon_svg( $type = 'cart-1' ) {
		$icons = array(
			'cart-1' => '<svg class="mini-cart-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M7 18c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm10 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zM7.16 14.26l.04-.12.94-1.7h7.45c.75 0 1.41-.41 1.75-1.03l3.58-6.49A1 1 0 0 0 20.04 4H5.21l-.94-2H1v2h2l3.6 7.59-1.35 2.44C4.52 15.37 5.48 17 7 17h12v-2H7.42c-.13 0-.25-.1-.25-.25z"/></svg>',
			'cart-2' => '<svg class="mini-cart-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M21.822 7.431A1 1 0 0 0 21 7H7.333L6.179 4.23A1.994 1.994 0 0 0 4.333 3H2v2h2.333l4.744 11.385A1 1 0 0 0 10 17h8c.417 0 .79-.259.937-.648l3-8a1 1 0 0 0-.115-.921z"/><circle cx="10.5" cy="19.5" r="1.5"/><circle cx="17.5" cy="19.5" r="1.5"/></svg>',
			'cart-3' => '<svg class="mini-cart-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"/><line x1="3" y1="6" x2="21" y2="6"/><path d="M16 10a4 4 0 0 1-8 0"/></svg>',
			'cart-4' => '<svg class="mini-cart-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M18 6h-2c0-2.21-1.79-4-4-4S8 3.79 8 6H6c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-6-2c1.1 0 2 .9 2 2h-4c0-1.1.9-2 2-2zm6 16H6V8h2v2c0 .55.45 1 1 1s1-.45 1-1V8h4v2c0 .55.45 1 1 1s1-.45 1-1V8h2v12z"/></svg>',
			'cart-5' => '<svg class="mini-cart-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M22 9h-4.79l-4.38-6.56a.997.997 0 0 0-1.66 0L6.79 9H2c-.55 0-1 .45-1 1 0 .09.01.18.04.27l2.54 9.27c.23.84 1 1.46 1.92 1.46h13c.92 0 1.69-.62 1.93-1.46l2.54-9.27L23 10c0-.55-.45-1-1-1zM12 4.8L14.8 9H9.2L12 4.8zM18.5 19h-13l-2.13-8H20.6l-2.1 8zM12 13c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/></svg>',
			'cart-6' => '<svg class="mini-cart-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M17.63 5.84C17.27 5.33 16.67 5 16 5L5 5.01C4.18 5.01 3.5 5.44 3.14 6.09L.12 11.95c-.05.11-.08.22-.08.34v1.96c0 .83.67 1.5 1.5 1.5H4c0 1.66 1.34 3 3 3s3-1.34 3-3h2c0 1.66 1.34 3 3 3s3-1.34 3-3h1.5c.83 0 1.5-.67 1.5-1.5V12c0-.46-.12-.9-.34-1.29L17.63 5.84zM7 17c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm8.5-10.5l2.5 4.5H13V6.5h2.5zM15 17c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z"/></svg>',
		);

		$svg = isset( $icons[ $type ] ) ? $icons[ $type ] : $icons['cart-1'];
		return $svg;
	}
}
