<?php

if ( !defined( 'ABSPATH' ) ) {
    exit;
}


if ( !class_exists( 'Pricely_Product_Util' ) ) {

    class Pricely_Product_Util {

        private static $instance;
        private $product_terms;

        public static function get_instance(): self {

            if ( !self::$instance ) {

                self::$instance = new self();
            }

            return self::$instance;
        }

        public function get_terms( $product, $variation, $taxonomy, $use_variations ) {

            $product_id = $product->get_id();

            if ( 'product_cat' == $taxonomy ) {

                $this->product_terms[ $product_id ][ $taxonomy ] = $product->get_category_ids( 'edit' );

                return $this->product_terms[ $product_id ][ $taxonomy ];
            }


            if ( 'product_tag' == $taxonomy ) {

                $this->product_terms[ $product_id ][ $taxonomy ] = $product->get_tag_ids( 'edit' );

                return $this->product_terms[ $product_id ][ $taxonomy ];
            }

            if ( 'product_brand' == $taxonomy && method_exists( $product, 'get_brand_ids' ) ) { // This method is only available from wc v10.3

                $this->product_terms[ $product_id ][ $taxonomy ] = $product->get_brand_ids( 'edit' ); // This method is only available from wc v10.3

                return $this->product_terms[ $product_id ][ $taxonomy ];
            }

            if ( 'product_brand' == $taxonomy ) {

                $this->product_terms[ $product_id ][ $taxonomy ] = wc_get_product_term_ids( $product_id, $taxonomy );

                return $this->product_terms[ $product_id ][ $taxonomy ];
            }

            $variation_id = 0;

            if ( !is_null( $variation ) ) {

                $variation_id = $variation->get_id();
            }


            $variation_term_ids = array();

            if ( $use_variations && $variation_id > 0 ) {

                $variation_term_ids = wc_get_product_term_ids( $variation_id, $taxonomy );
            }

            if ( count( $variation_term_ids ) ) {

                $this->product_terms[ $product_id ][ $variation_id ] = $variation_term_ids;
            }

            $term_ids = array();

            if ( !count( $term_ids ) ) {

                $term_ids = wc_get_product_term_ids( $product_id, $taxonomy );
            }

            $this->product_terms[ $product_id ][ $product_id ] = $term_ids;

            if ( count( $variation_term_ids ) ) {

                return $variation_term_ids;
            }

            return $term_ids;
        }

    }

}