<?php

namespace Ecomus\Addons\Modules\Dynamic_Pricing_Discounts;

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

/**
 * Main class of plugin for admin
 */
class Frontend {

	/**
	 * Instance
	 *
	 * @var $instance
	 */
	private static $instance;

	/**
	 * Initiator
	 *
	 * @since 1.0.0
	 * @return object
	 */
	public static function instance() {
		if ( ! isset( self::$instance ) ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	const POST_TYPE = 'em_pricing_discount';

	/**
	 * Instantiate the object.
	 *
	 * @since 1.0.0
	 *
	 * @return void
	 */
	public function __construct() {
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );

		add_action( 'woocommerce_single_product_summary', array( $this, 'dynamic_pricing_discounts' ), 27 );

		// Cart
		add_action( 'woocommerce_before_calculate_totals', [ $this, 'before_calculate_totals' ], 9999 );
	}

		/**
	 * Enqueue scripts
	 *
	 * @since 1.0.0
	 *
	 * @return void
	 */
	public function enqueue_scripts() {
		if ( is_singular( 'product' ) ) {
			wp_enqueue_style( 'ecomus-dynamic-pricing-discounts', ECOMUS_ADDONS_URL . 'modules/dynamic-pricing-discounts/assets/dynamic-pricing-discounts.css', array(), '1.0.0' );
			wp_enqueue_script('ecomus-dynamic-pricing-discounts', ECOMUS_ADDONS_URL . 'modules/dynamic-pricing-discounts/assets/dynamic-pricing-discounts.js',  array('jquery'), '1.0.0' );

			$data = array(
				'currency_pos'       => get_option( 'woocommerce_currency_pos' ),
				'currency_symbol'    => function_exists( 'get_woocommerce_currency_symbol' ) ? get_woocommerce_currency_symbol() : '',
				'thousand_sep'       => function_exists( 'wc_get_price_thousand_separator' ) ? wc_get_price_thousand_separator() : '',
				'decimal_sep'        => function_exists( 'wc_get_price_decimal_separator' ) ? wc_get_price_decimal_separator() : '',
				'price_decimals'     => function_exists( 'wc_get_price_decimals' ) ? wc_get_price_decimals() : '',
			);

			wp_localize_script(
				'ecomus-dynamic-pricing-discounts', 'ecomusDpd', $data
			);
		}
	}

	/**
	 * Get product bought together
	 *
	 * @since 1.0.0
	 *
	 * @return void
	 */
	public function dynamic_pricing_discounts() {
		global $product;

		if ( ! $product->is_type( 'simple' ) && ! $product->is_type( 'variable' ) ) {
            return;
        }

		$post_ids = (array) $this->get_post_ids();

		foreach( $post_ids as $post_id ) {
			if( ! self::check_current_product( $post_id, $product->get_ID() ) ) {
				return;
			}

			$items = (array) get_post_meta( $post_id, 'ecomus_dynamic_pricing_discounts_items', true );

			if( empty( $items ) ) {
				return;
			}
		?>
			<div id="ecomus-dynamic-pricing-discounts" class="dynamic-pricing-discounts">
				<?php foreach ( $items as $item ) : ?>
					<?php if( ( $item['from' ] >= 0 || $item['to' ] > 0 ) && $item['discount'] > 0 ) : ?>
					<?php
						$discount_price         = ( $product->get_price() / 100 ) * ( 100 - intval( $item['discount'] ) );
						$item['price']          = $product->get_price();
						$item['discount_price'] = $discount_price;
					?>
						<div class="dynamic-pricing-discounts-item" data-discount="<?php echo esc_attr( json_encode( $item ) ); ?>">
							<div class="dynamic-pricing-discounts-item__summary em-flex">
								<input type="radio" class="dynamic-pricing-discounts-item__quantity" name="dynamic_pricing_discounts_item_quantity" value="<?php echo esc_attr( $item['to'] ); ?>" />
								<?php if( $item['from' ] >= 0 && empty( $item['to' ] ) ) : ?>
									<label class="em-color-dark em-font-semibold"><?php printf( __( 'Buy %s+ items for %s OFF per item.', 'ecomus-addons' ), $item['from'], $item['discount'] . '%' ); ?></label>
								<?php else : ?>
									<label class="em-color-dark em-font-semibold"><?php printf( __( 'Buy from %s to %s items for %s OFF per item.', 'ecomus-addons' ), $item['from'], $item['to'], $item['discount'] . '%' ); ?></label>
								<?php endif; ?>

								<span class="dynamic-pricing-discounts-item__discount em-font-bold"><?php printf( __( 'Save %s', 'ecomus-addons' ), $item['discount'] . '%' ); ?></span>
								<input type="hidden" name="dynamic_pricing_discounts_item_discount" value="<?php echo esc_attr( $item['discount'] ); ?>" />
							</div>
							<div class="dynamic-pricing-discounts-item__price em-flex <?php echo $product->is_type( 'variable' ) ? 'hidden' : ''; ?>">
								<span class="em-color-dark em-font-bold"><?php esc_html_e( 'Price', 'ecomus-addons' ); ?></span>
								<span class="price"><?php echo wc_format_sale_price( $product->get_price(), $discount_price ); ?></span>
							</div>
						</div>
					<?php endif; ?>
				<?php endforeach; ?>
			</div>
		<?php
		}
	}

	/**
	 * Get post pricing discount ids
     *
	 * @since 1.0.0
	 *
	 * @return void
	 */
	public function get_post_ids() {
		$transient_name = 'ecomus_post_pricing_discount';
		$transient      = get_transient( $transient_name );
		$post_ids       = $transient ? $transient : false;

		if ( false === $post_ids) {
			$posts = new \WP_Query( array(
				'post_type'        => self::POST_TYPE,
				'posts_per_page'   => '-1',
				'fields'           => 'ids',
				'no_found_rows'    => true,
				'orderby'          => 'menu_order',
				'order'            => 'DESC',
				'suppress_filters' => false,
			) );

			if ( $posts->have_posts() ) {
				$post_ids  = $posts->posts;
				$transient = $post_ids;
				set_transient( $transient_name, $transient, DAY_IN_SECONDS );
			}

			wp_reset_postdata();
		}

		return $post_ids;
	}

	/**
	 * Check product
	 *
	 * @return boolean
	 */
	public function check_current_product( $post_id, $product_id, $variation_id = 0 ) {
		$status   = get_post_meta( $post_id, '_pricing_discount_status', true );
		$check    = false;

		if( $status == 'yes' ) {
			$display    = get_post_meta( $post_id, '_dynamic_pricing_discounts_display', true );
			$products   = get_post_meta( $post_id, '_product_pricing_discount_ids', true );
			$categories	= get_the_terms( $post_id, 'product_cat' );
			$terms_args = [];

			if( ! empty( $categories ) ) {
				foreach( $categories as $category ) {
					$terms_args[] = $category->slug;
				}
			}

			if( $display == 'products' ) {
				if( empty( $products ) ) {
					$check = true;
				} else {
					if( in_array( $product_id, $products ) ) {
						$check = true;
					}

					if( $variation_id > 0 ) {
						$variation = wc_get_product( $variation_id );

						if( in_array( $variation_id, $products ) || in_array( $variation->get_parent_id(), $products ) ) {
							$check = true;
						}
					}
				}
			} else {
				if( empty( $terms_args ) ) {
					$check = true;
				} else {
					if( $variation_id > 0 ) {
						$variation = wc_get_product( $variation_id );
						$product_id = $variation->get_parent_id();
					}

					$terms = get_the_terms( $product_id, 'product_cat' );
					if( ! is_wp_error( $terms ) && $terms ) {
						foreach( $terms as $term ) {
							if( in_array( $term->slug, $terms_args ) ) {
								$check = true;
								break;
							} else {
								if( ! empty( $term->parent ) ) {
									$slug = get_term( $term->parent )->slug;
									if( in_array( $slug, $terms_args ) ) {
										$check = true;
										break;
									}
								}
							}
						}
					}
				}
			}
		}

		return $check;
	}

	function before_calculate_totals( $cart_object ) {
		if ( ! defined( 'DOING_AJAX' ) && is_admin() ) {
			// This is necessary for WC 3.0+
			return;
		}

		$cart_contents = $cart_object->cart_contents;

		foreach ( $cart_contents as $cart_item_key => $cart_item ) {
			if ( $cart_item['variation_id'] > 0 ) {
				$item_product = wc_get_product( $cart_item['variation_id'] );
			} else {
				$item_product = wc_get_product( $cart_item['product_id'] );
			}

			$product_price = $item_product->get_price();

			$post_ids = (array) $this->get_post_ids();
			foreach( $post_ids as $post_id ) {
				if( self::check_current_product( $post_id, $cart_item['product_id'], $cart_item['variation_id'] ) ) {
					$items = (array) get_post_meta( $post_id, 'ecomus_dynamic_pricing_discounts_items', true );

					if ( ! empty( $items ) ) {
						foreach( $items as $item ) {
							if( ! empty( $item['discount'] ) && $item['discount'] !== '0' ) {
								if( ( intval( $item['from'] ) <= intval( $cart_item['quantity'] ) && intval( $cart_item['quantity'] ) <= intval( $item['to'] ) ) || ( empty( $item['to'] ) && intval( $item['from'] ) <= intval( $cart_item['quantity'] ) ) ) {
									$discount_price = $product_price * ( 100 - (float) $item['discount'] ) / 100;

									$cart_item['data']->set_price( $discount_price );
								}
							}
						}
					}
				}
			}
		}
	}
}