<?php

namespace orderflow\Facebook;

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

/** @noinspection PhpIncludeInspection */
require_once ADS_PLUGIN_PATH . '/includes/facebook/modules/facebook/function-helpers.php';

use orderflow\Settings;
use orderflow\Facebook\Pixel;
use orderflow\Facebook\Helpers;
use orderflow\Facebook\Consent;
use orderflow\Facebook\EventIdGenerator;

class Facebook extends Settings implements Pixel {
	
	private static $_instance;
	
	private $configured;
	public static function instance() {
		
		if ( is_null( self::$_instance ) ) {
			self::$_instance = new self();
		}
		
		return self::$_instance;
		
	}

    public function __construct() {
		
        parent::__construct( 'orderflow_facebook' );
        
        $this->locateOptions(
	        ADS_PLUGIN_PATH . '/includes/facebook/modules/facebook/options_fields.json',
	        ADS_PLUGIN_PATH . '/includes/facebook/modules/facebook/options_defaults.json'
        );
	
	    add_action( 'pys_register_pixels', function( $core ) {
	    	/** @var \orderflow\Facebook\PYS $core */
	    	$core->registerPixel( $this );
	    } );
        add_filter('orderflow_facebook_settings_sanitize_verify_meta_tag_field', array($this, 'sanitize_verify_meta_tag_field'));
        add_action( 'wp_head', array( $this, 'output_meta_tag' ) );
    }

    public function enabled() {
	    return $this->getOption( 'of_enabled' );
    }

	public function configured() {
		
		if ( $this->configured === null ) {

			$pixel_id = $this->getPixelIDs();
			$this->configured = $this->enabled()
			                    && count( $pixel_id ) > 0
                                && !empty($pixel_id[0]);
		}
		
		return $this->configured;
		
	}
	
	public function getPixelIDs() {
		
		$ids = (array) $this->getOption( 'of_pixel_id' );

        if(count($ids) == 0|| empty($ids[0])) {
            return apply_filters("pys_facebook_ids",[]);
        } else {
			$id = array_shift($ids);
			return apply_filters("pys_facebook_ids", array($id)); // return first id only
        }
	}

	public function getPixelOptions() {
		return array(
			'pixelIds'                   => $this->getPixelIDs(),
			'advancedMatching'           => $this->getOption( 'of_advanced_matching_enabled' ) ? Helpers\getAdvancedMatchingParams() : array(),
			'advancedMatchingEnabled'    => $this->getOption( 'of_advanced_matching_enabled' ),
			'removeMetadata'             => $this->getOption( 'of_remove_metadata' ),
			'wooVariableAsSimple'        => $this->getOption( 'of_woo_variable_as_simple' ),
			'serverApiEnabled'           => $this->isServerApiEnabled() && count( $this->getApiToken() ) > 0,
			'wooCRSendFromServer'        => $this->getOption( "of_woo_complete_registration_send_from_server" ) && $this->getOption( "of_woo_complete_registration_fire_every_time" ),
			'send_external_id'           => $this->getOption( 'send_external_id' ),
			'enabled_medical'            => $this->getOption( 'of_enabled_medical' ),
			'do_not_track_medical_param' => $this->getOption( 'of_do_not_track_medical_param' ),
			'meta_ldu'                   => $this->getLDUMode(),
		);
	}

    public function updateOptions( $values = null ) {
        if(isset($_POST['pys'][$this->getSlug()]['of_test_api_event_code']))
        {


            $api_event_code_expiration_at = array();
            foreach ($_POST['pys'][$this->getSlug()]['of_test_api_event_code'] as $key => $test_api)
            {
                if(!empty($test_api) && empty($this->getOption('of_test_api_event_code_expiration_at')[$key]))
                {
                    $api_event_code_expiration_at[] = time() + $this->convertTimeToSeconds();
                }
                elseif (!empty($this->getOption('of_test_api_event_code_expiration_at')[$key]))
                {
                    $api_event_code_expiration_at[] = $this->getOption('of_test_api_event_code_expiration_at')[$key];
                }
            }

            $_POST['pys'][$this->getSlug()]['of_test_api_event_code_expiration_at'] = $api_event_code_expiration_at;
        }
        parent::updateOptions($values);
    }
    /**
     * Create pixel event and fill it
     * @param SingleEvent $event
     * @return SingleEvent[]
     */
    public function generateEvents($event) {
        $pixelEvents = [];
        if ( ! $this->configured() ) {
            return [];
        }

        $pixelIds = $this->getPixelIDs();

        if(count($pixelIds) > 0) {
            $pixelEvent = clone $event;
            $addParamsResult = $this->addParamsToEvent($pixelEvent);
            
            if($addParamsResult) {
                $eventId = EventIdGenerator::guidv4();
                $pixelEvent->addPayload([
                    'pixelIds' => $pixelIds,
                    'eventID' => $eventId
                ]);
                $pixelEvents[] = $pixelEvent;
            }
        }

        return $pixelEvents;
    }

	// need refactoring
    private function addDataToEvent($eventData,&$event) {
        $params = $eventData["data"];
        unset($eventData["data"]);
        //unset($eventData["name"]);
        $event->addParams($params);
        $event->addPayload($eventData);
    }

    /**
     * @param SingleEvent $event
     * @return bool|mixed|null
     */
    function addParamsToEvent(&$event) {
        if ( ! $this->configured() ) {
            return false;
        }
        $isActive = false;

        switch ($event->getId()) {
            case 'init_event':{
                $eventData = $this->getPageViewEventParams();
                
                if($eventData) {
                    $isActive = true;
                    $consentCheck = \orderflow\Facebook\Consent::instance()->checkConsent( 'facebook' );
                    
                    $event->addPayload( [ "ajaxFire" => !$consentCheck ] );
                    
                    $this->addDataToEvent($eventData,$event);
                }
            } break;

            case 'woo_view_content': {
                $eventData =  $this->getWooViewContentEventParams();
                if($eventData) {
                    $isActive = true;
                    $this->addDataToEvent($eventData,$event);
                }
            }break;
            case 'woo_add_to_cart_on_cart_page':
            case 'woo_add_to_cart_on_checkout_page': {
                $eventData =  $this->getWooAddToCartOnCartEventParams();
                if ($eventData) {
                    $isActive = true;
                    $this->addDataToEvent($eventData, $event);
                }
            }break;
            case 'woo_remove_from_cart': {
                $isActive =  $this->getWooRemoveFromCartParams( $event);
            }break;
            case 'woo_view_category':{
                $eventData =  $this->getWooViewCategoryEventParams();
                if($eventData) {
                    $isActive = true;
                    $this->addDataToEvent($eventData,$event);
                }
            }break;
            case 'woo_initiate_checkout': {
                $eventData =  $this->getWooInitiateCheckoutEventParams();
                if ($eventData) {
                    $isActive = true;
                    $this->addDataToEvent($eventData, $event);
                }
            }break;
            case 'woo_purchase':{
                $eventData =  $this->getWooPurchaseEventParams();
                if ($eventData) {
                    $isActive = true;
                    $this->addDataToEvent($eventData, $event);
                }
            }break;
            case 'woo_complete_registration': {
                if( $this->getOption("of_woo_complete_registration_fire_every_time") ||
                    get_user_meta( get_current_user_id(), 'of_pys_complete_registration', true )
                ) {
                    $eventData = $this->getWooCompleteRegistrationEventParams();
                    if($eventData) {
                        $isActive = true;
                        $this->addDataToEvent($eventData,$event);
                    }
                }
            }break;

            case 'woo_add_to_cart_on_button_click':{
                if (  $this->getOption( 'of_woo_add_to_cart_enabled' )
                    && $this->getOption( 'of_woo_add_to_cart_on_button_click' )
                ) {
                    $isActive = true;
                    if(isset($event->args['productId'])) {
                       // error_log("Product ID: " . $event->args['productId']);
                        $eventData =  $this->getWooAddToCartOnButtonClickEventParams( $event->args );
                        //error_log("Event data: " . print_r($eventData, true));

                        if($eventData && isset($eventData["params"])) {
                            $event->addParams($eventData["params"]);
                            unset($eventData["params"]);
                            if(!empty($eventData)) {
                                $event->addPayload($eventData);
                            }
                        }
                    }

                    $event->addPayload(array(
                        'name'=>"AddToCart",
                    ));

                }
            }break;


        }

        return $isActive;
    }
	
	public function getEventData( $eventType, $args = null ) {

        return false;
	}

	public function outputNoScriptEvents() {
	 
		if ( ! $this->configured() || $this->getOption('of_disable_noscript')) {
			return;
		}

		$ldu = $this->getLDUMode();
		$eventsManager = \orderflow\Facebook\PYS()->getEventsManager();

		foreach ( $eventsManager->getStaticEvents( 'orderflow_facebook' ) as $eventId => $events ) {

			foreach ( $events as $event ) {
                if( $event['name'] == "hCR") continue;
				foreach ( $this->getPixelIDs() as $pixelID ) {
					$args = array(
						'id'       => $pixelID,
						'ev'       => urlencode( $event['name'] ),
						'noscript' => 1,
					);

					$params = $event[ 'params' ];
					if ( $ldu ) {
						$params = array_merge( $params, array(
							'vdpo'  => 'LDU',
							'dpoco' => 0,
							'dpost' => 0
						) );
					}

					foreach ( $params as $param => $value ) {
                        if(is_array($value))
                            $value = json_encode($value);
						@$args[ 'cd[' . $param . ']' ] = urlencode( $value );
					}
                    $src = add_query_arg( $args, 'https://www.facebook.com/tr' );
                    $src = str_replace("[","%5B",$src); //pass markup validation
                    $src = str_replace("]","%5D",$src);
					// ALT tag used to pass ADA compliance
					printf( '<noscript><img height="1" width="1" style="display: none;" src="%s" alt=""></noscript>',
                        $src);

					echo "\r\n";

				}
			}
		}
		
	}
	
	private function getPageViewEventParams() {
	    $data = array();
        $cpt = get_post_type();
        if(!$cpt) {
            return false;
        }
        
        $result = array(
			'name'  => 'PageView',
			'data'  => $data,
		);
		
		return $result;

	}

	private function getWooViewContentEventParams() {
		global $post;

		if ( ! $this->getOption( 'of_woo_view_content_enabled' ) ) {
			return false;
		}

		$params = array();

		$product = wc_get_product( $post->ID );
        if(!$product) return false;
		$content_id = Helpers\getFacebookWooProductContentId( $post->ID );
		$params['content_ids']  =  $content_id ;

		if ( \orderflow\Facebook\wooProductIsType( $product, 'variable' ) && ! $this->getOption( 'of_woo_variable_as_simple' ) ) {
			$params['content_type'] = 'product_group';
		} else {
			$params['content_type'] = 'product';
		}

		// Facebook for WooCommerce plugin integration
		if ( ! Helpers\isDefaultWooContentIdLogic() && \orderflow\Facebook\wooProductIsType( $product, 'variable' ) ) {
			$params['content_type'] = 'product_group';
		}

		// content_name, category_name, tags
		$params['tags'] = implode( ', ', \orderflow\Facebook\getObjectTerms( 'product_tag', $post->ID ) );
		$params = array_merge( $params, Helpers\getWooCustomAudiencesOptimizationParams( $post->ID ) );

		// currency, value
		if ( \orderflow\Facebook\PYS()->getOption( 'woo_view_content_value_enabled' ) ) {

            $value_option = \orderflow\Facebook\PYS()->getOption( 'woo_view_content_value_option' );
            $global_value = \orderflow\Facebook\PYS()->getOption( 'woo_view_content_value_global', 0 );


            $params['value']    = \orderflow\Facebook\getWooEventValue( $value_option, $global_value,100, $post->ID ,1);
            $params['currency'] = get_woocommerce_currency();

		}

		// contents
		if ( Helpers\isDefaultWooContentIdLogic() ) {

			// Facebook for WooCommerce plugin does not support new Dynamic Ads parameters
			$params['contents'] =  array(
				array(
					'id'         => (string) reset( $content_id ),
					'quantity'   => 1,
					//'item_price' => \orderflow\Facebook\getWooProductPriceToDisplay( $post->ID ),
				)
			);

		}


		$params['product_price'] = \orderflow\Facebook\getWooProductPriceToDisplay( $post->ID );

		return array(
			'name'  => 'ViewContent',
			'data'  => $params,
			'delay' => (int) \orderflow\Facebook\PYS()->getOption( 'woo_view_content_delay' ),
		);

	}

	private function getWooAddToCartOnButtonClickEventParams( $args ) {

		if ( ! $this->getOption( 'of_woo_add_to_cart_enabled' ) || ! \orderflow\Facebook\PYS()->getOption( 'woo_add_to_cart_on_button_click' ) ) {
			return false;
		}
        $product_id = $args['productId'];
        $quantity = $args['quantity'];

		$params = Helpers\getWooSingleAddToCartParams( $product_id, $quantity );
        $data = array(
            'params' => $params,
        );

        $product = wc_get_product($product_id);
        if(!$product) return false;
        if($product->get_type() == 'grouped') {
            $grouped = array();
            foreach ($product->get_children() as $childId) {
                $conId = Helpers\getFacebookWooProductContentId( $childId );
                $grouped[$childId] = array(
                    'content_id' => (string) reset($conId),
                    'price' => \orderflow\Facebook\getWooProductPriceToDisplay( $childId )
                );
            }
            $data['grouped'] = $grouped;
        }
		return $data;

	}

	private function getWooAddToCartOnCartEventParams() {

		if ( ! $this->getOption( 'of_woo_add_to_cart_enabled' ) ) {
			return false;
		}

		$params = Helpers\getWooCartParams();

		return array(
			'name' => 'AddToCart',
			'data' => $params,
		);

	}

    /**
     * @param SingleEvent $event
     * @return bool
     */
	private function getWooRemoveFromCartParams( $event ) {

		if ( ! $this->getOption( 'of_woo_remove_from_cart_enabled' ) ) {
			return false;
		}
        $cart_item = $event->args['item'];
		$product_id = Helpers\getFacebookWooCartItemId( $cart_item );
		$content_id = Helpers\getFacebookWooProductContentId( $product_id );

		$params['content_type'] = 'product';
		$params['content_ids']  =  $content_id ;

		// content_name, category_name, tags
		$params['tags'] = implode( ', ', \orderflow\Facebook\getObjectTerms( 'product_tag', $product_id ) );
		$params = array_merge( $params, Helpers\getWooCustomAudiencesOptimizationParams( $product_id ) );

		$params['num_items'] = $cart_item['quantity'];
		$params['product_price'] = \orderflow\Facebook\getWooProductPriceToDisplay( $product_id );

		$params['contents'] =  array(
			array(
				'id'         => (string) reset( $content_id ),
				'quantity'   => $cart_item['quantity'],
				//'item_price' => getWooProductPriceToDisplay( $product_id ),
			)
		) ;
        $data = [
            'name' => "RemoveFromCart",
        ];
        $event->addParams($params);
        $event->addPayload($data);
		return true;

	}

	private function getWooViewCategoryEventParams() {
		global $posts;

		if ( ! $this->getOption( 'of_woo_view_category_enabled' ) ) {
			return false;
		}
        
        if ( Helpers\isDefaultWooContentIdLogic() ) {
            $params['content_type'] = 'product';
        } else {
            $params['content_type'] = 'product_group';
        }
        
        $params['content_category'] = array();
        $term = get_term_by( 'slug', get_query_var( 'term' ), 'product_cat' );
        
        if ( $term ) {
            
            $params['content_name'] = $term->name;
            
            $parent_ids = get_ancestors( $term->term_id, 'product_cat', 'taxonomy' );
            
            foreach ( $parent_ids as $term_id ) {
                $term = get_term_by( 'id', $term_id, 'product_cat' );
                if($term) {
                    $params['content_category'][] = $term->name;
                }

            }
            
        }
        
        $params['content_category'] = implode( ', ', $params['content_category'] );

		$content_ids = array();
		$limit       = min( count( $posts ), 5 );

		for ( $i = 0; $i < $limit; $i ++ ) {
			$content_ids = array_merge( Helpers\getFacebookWooProductContentId( $posts[ $i ]->ID ), $content_ids );
		}

		$params['content_ids']  =  $content_ids ;

		return array(
			'name' => 'ViewCategory',
			'data' => $params,
		);

	}

	private function getWooInitiateCheckoutEventParams() {

		if ( ! $this->getOption( 'of_woo_initiate_checkout_enabled' ) ) {
			return false;
		}

		$params = Helpers\getWooCartParams( 'InitiateCheckout' );


		return array(
			'name' => 'InitiateCheckout',
			'data' => $params,
		);

	}

	public function getWooPurchaseEventParams() {

		if ( ! $this->getOption( 'of_woo_purchase_enabled' ) ) {
			return false;
		}
        $order_key = sanitize_key($_REQUEST['key']);
        $cache_key = 'order_id_' . $order_key;
        $order_id = get_transient( $cache_key );
        global $wp;
        if (\orderflow\Facebook\PYS()->woo_is_order_received_page() && empty($order_id) && $wp->query_vars['order-received']) {

            $order_id = absint( $wp->query_vars['order-received'] );
            if ($order_id) {
                set_transient( $cache_key, $order_id, HOUR_IN_SECONDS );
            }
        }
        if ( empty($order_id) ) {
            $order_id = (int) wc_get_order_id_by_order_key( $order_key );
            set_transient( $cache_key, $order_id, HOUR_IN_SECONDS );
        }
        $order    = wc_get_order( $order_id );
        if(!$order) return false;
        
        $content_ids        = array();
        $content_names      = array();
        $content_categories = array();
        $tags               = array();
        $num_items          = 0;
        $contents           = array();
        
        foreach ( $order->get_items( 'line_item' ) as $line_item ) {
            
            $product_id = Helpers\getFacebookWooCartItemId( $line_item );
            $content_id = Helpers\getFacebookWooProductContentId( $product_id );
            
            $content_ids = array_merge( $content_ids, $content_id );
            
            $num_items += $line_item['qty'];
            
            // content_name, category_name, tags
            $custom_audiences = Helpers\getWooCustomAudiencesOptimizationParams( $product_id );
            
            $content_names[]      = $custom_audiences['content_name'];
            $content_categories[] = $custom_audiences['category_name'];
            
            $cart_item_tags = \orderflow\Facebook\getObjectTerms( 'product_tag', $product_id );
            $tags           = array_merge( $tags, $cart_item_tags );
            
            // raw product id
            $_product_id = empty( $line_item['variation_id'] ) ? $line_item['product_id']
                : $line_item['variation_id'];
            
            // contents
            $contents[] = array(
                'id'         => (string) reset( $content_id ),
                'quantity'   => $line_item['qty'],
                'item_price' => \orderflow\Facebook\getWooProductPriceToDisplay( $_product_id ),
            );
            
        }
        
        $params['content_type']  = 'product';
        $params['content_ids']   =  $content_ids ;
        $params['content_name']  = implode( ', ', $content_names );
        $params['category_name'] = implode( ', ', $content_categories );
        
        // contents
        if ( Helpers\isDefaultWooContentIdLogic() ) {
            
            // Facebook for WooCommerce plugin does not support new Dynamic Ads parameters
            $params['contents'] =  $contents ;
            
        }
        
        $tags           = array_unique( $tags );
        $tags           = array_slice( $tags, 0, 100 );
        $params['tags'] = implode( ', ', $tags );
        
        $params['num_items'] = $num_items;
        

        $value_option = \orderflow\Facebook\PYS()->getOption( 'woo_purchase_value_option' );
        $global_value = \orderflow\Facebook\PYS()->getOption( 'woo_purchase_value_global', 0 );

        $params['value'] = \orderflow\Facebook\getWooEventValueOrder( $value_option, $order, $global_value );
        $params['currency'] = get_woocommerce_currency();
        $params['order_id'] = $order_id;

        $params['fees'] = \orderflow\Facebook\get_fees($order);



		return array(
			'name' => 'Purchase',
			'data' => $params,
            'woo_order' => $order_id
		);

	}


    /**
     * @return array
     */
    public function getApiToken() {
        $tokens = array();
        $pixelids = (array) $this->getOption( 'of_pixel_id' );
        $serverids = (array) $this->getOption( 'of_server_access_api_token' );

        if(count($pixelids) == 0) return array();

        if ( \orderflow\Facebook\isSuperPackActive() && function_exists('SuperPack') && SuperPack()->getOption( 'enabled' ) && SuperPack()->getOption( 'additional_ids_enabled' ) ) {
            foreach ($pixelids as $key => $val) {
                if(isset($serverids[$key]))
                    $tokens[$val] = $serverids[$key];
            }
        } else {
            $tokens[$pixelids[0]] =  reset( $serverids ); // return first id only
        }

        return $tokens;
    }

    /**
     * @return array
     */
    public function getApiTestCode() {
        $testCode = array();
        $pixelids = (array) $this->getOption( 'of_pixel_id' );
        $serverTestCode = (array) $this->getOption( 'of_test_api_event_code' );
        if ( \orderflow\Facebook\isSuperPackActive() && function_exists('SuperPack') && SuperPack()->getOption( 'enabled' ) && SuperPack()->getOption( 'additional_ids_enabled' ) ) {
            foreach ($pixelids as $key => $val) {
                if(isset($serverTestCode[$key]))
                    $testCode[$val] = $serverTestCode[$key];
            }
        } else {
            $testCode[$pixelids[0]] =  reset( $serverTestCode ); // return first id only
        }
        return $testCode;
    }

    /**
     * @return bool
     */
    public function isServerApiEnabled() {
        return $this->getOption("of_use_server_api");
    }



    private function getWooCompleteRegistrationEventParams($args=null) {

        if ( ! $this->getOption( 'of_complete_registration_event_enabled' ) ) {
            return false;
        }
        $params = array();
        if($this->getOption("of_woo_complete_registration_fire_every_time") &&
            $this->getOption("woo_complete_registration_use_custom_value") &&
            isset( $_REQUEST['key'] ) && $_REQUEST['key'] != "" ) {
            $params = Helpers\getCompleteRegistrationOrderParams();
        }
        $name = isset($args) && $args == "hCR" ? "hCR" : 'CompleteRegistration';

        return $params = array(
            'name'  => $name,
            'data'  => $params,
        );

    }
    function output_meta_tag() {
        $metaTags = (array) Facebook()->getOption( 'verify_meta_tag' );
        foreach ($metaTags as $tag) {
            echo $tag;
        }
    }
    function sanitize_verify_meta_tag_field($values) {
        $values = is_array( $values ) ? $values : array();
        $sanitized = array();
        $allowed_html = array(
            'meta' => array(
                'name' => array(),
                'content' => array(),
            ),
        );
        foreach ( $values as $key => $value ) {

            $value = wp_kses($value, $allowed_html);
            $new_value = $this->sanitize_textarea_field( $value );

            if ( ! empty( $new_value ) && ! in_array( $new_value, $sanitized ) ) {
                $sanitized[ $key ] = $new_value;
            }

        }

        return $sanitized;
    }

	public function getLDUMode() {
		return apply_filters( 'pys_meta_ldu_mode', false );
	}

	/**
	 * Get main tag ID for pixel hiding functionality
	 * Compatible with PixelYourSite PRO
	 * 
	 * @return string
	 */
	function getMainTagId() {
		$id = $this->getPixelIDs();
		$main_tag = '';
		if ( is_array( $id ) && isset( $id[0] ) ) {
			$main_tag = $id[0];
		} else {
			$main_tag = $id;
		}
		return ( ! empty( $main_tag ) ) ? $main_tag : '';
	}

	/**
	 * Check if pixel should be hidden based on URL or cookie settings
	 * Compatible with PixelYourSite PRO
	 * This method is called by pixelyoursite-pro when both plugins are active
	 */
	function checkHidePixel() {
		$main_tag_id = $this->getMainTagId();
		if ( empty( $main_tag_id ) ) {
			return;
		}

		$existing_hide_pixels = apply_filters( 'hide_pixels', [] );

		$protocol = ( ! empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] === 'on' ) ? 'https://' : 'http://';
		$host = $_SERVER['HTTP_HOST'] ?? parse_url( get_site_url(), PHP_URL_HOST );
		$request_uri = $_SERVER['REQUEST_URI'] ?? '';
		$full_url = $protocol . $host . $request_uri;

		if ( isset( $_COOKIE['hide_tag_' . $main_tag_id] ) ) {
			$existing_hide_pixels[] = $main_tag_id;
		}

		if ( $this->getOption( 'of_hide_this_url' ) ) {
			$hide_keywords = $this->getOption( 'of_hide_this_url_contain' ) ?: [];

			foreach ( $hide_keywords as $keyword ) {
				if ( empty( $keyword ) ) continue;
				if ( stripos( $full_url, $keyword ) !== false ) {
					$existing_hide_pixels[] = $main_tag_id;
					break;
				}
			}
		}

		if ( $existing_hide_pixels ) {
			add_filter( 'hide_pixels', function () use ( $existing_hide_pixels ) {
				return array_unique( $existing_hide_pixels );
			} );
		}
	}
}

/**
 * @return Facebook
 */
function Facebook() {
	return \orderflow\Facebook\Facebook::instance();
}

Facebook();