class WDP_WCFGC_Compatibility {
  const KEY = 'free_gift_coupons';
  const WDP_VERSION = '2.3.3';
  const TARGET_VERSION = '2.4.3';

  protected $fgc_keys = array(
    'free_gift',
    'fgc_quantity',
  );

  public function is_required() {
    return class_exists( 'WC_Free_Gift_Coupons' );
  }

  public function admin_install() {
  }

  public function remove_admin_hooks() {
  }

  /**
   * @param WDP_Price_Display $price_display
   */
  public function install( $price_display ) {
    $install = function() {
      add_filter( 'wdp_cart_item_data_before_apply', array( $this, 'wdp_cart_item_data_before_apply' ), 10, 2 );
      add_filter( 'wdp_original_cart_item_data', array( $this, 'wdp_original_cart_item_data' ), 10, 1 );
      add_filter( "wdp_get_product_regular_price", array( $this, 'wdp_get_product_any_price' ), 10, 3 );
      add_filter( "wdp_get_product_sale_price", array( $this, 'wdp_get_product_any_price' ), 10, 3 );
      add_filter( "wdp_get_product_initial_price", array( $this, 'wdp_get_product_any_price' ), 10, 3 );
      add_filter( 'wdp_save_cart_item_keys', array( $this, 'wdp_save_cart_item_keys' ), 10, 1 );
    };

    if ( did_action('init') ) {
      $install();
    } else {
      add_action( 'init', $install );
    }
  }

  public function remove_hooks() {
    if ( did_action( 'init' ) ) {
      remove_filter( 'wdp_cart_item_data_before_apply', array( $this, 'wdp_cart_item_data_before_apply' ), 10 );
      remove_filter( 'wdp_original_cart_item_data', array( $this, 'wdp_original_cart_item_data' ), 10 );
      remove_filter( "wdp_get_product_regular_price", array( $this, 'wdp_get_product_any_price' ), 10 );
      remove_filter( "wdp_get_product_sale_price", array( $this, 'wdp_get_product_any_price' ), 10 );
      remove_filter( "wdp_get_product_initial_price", array( $this, 'wdp_get_product_any_price' ), 10 );
      remove_filter( 'wdp_save_cart_item_keys', array( $this, 'wdp_save_cart_item_keys' ), 10 );
    }
  }

  public function wdp_cart_item_data_before_apply( $cart_item_data, $original_cart_item_data ) {
    foreach ( $this->fgc_keys as $key ) {
      if ( isset( $original_cart_item_data[ $key ] ) ) {
        $cart_item_data[ $key ] = $original_cart_item_data[ $key ];
      }
    }

    return $cart_item_data;
  }

  public function wdp_original_cart_item_data( $original_cart_item_data ) {
    foreach ( $this->fgc_keys as $key ) {
      if ( isset( $original_cart_item_data[ $key ] ) ) {
        unset( $original_cart_item_data[ $key ] );
      }
    }

    return $original_cart_item_data;
  }

  public function wdp_get_product_any_price( $price, $product, $item_meta ) {
    if ( isset( $item_meta['free_gift'] ) ) {
      $price = 0;
      }
      return $price;
  }

  public function wdp_save_cart_item_keys( $keys ) {
    return array_merge( $keys, $this->fgc_keys );
  }
}

$comp = new WDP_WCFGC_Compatibility();
if($comp->is_required()) {
    $comp->install(null);
}