<?php

if( ! class_exists( 'MDWC_Insights' ) ):
class MDWC_Insights {

    private static $_instance;

    private $visitor_id = false;

    /**
     * Single ton
     * 
     * @return MDWC_Insights
     * 
     * @since 1.1.0
     */
    public static function get_instance() {

        if( self::$_instance == null ) {
            self::$_instance = new self();
        }

        return self::$_instance;

    }

    /**
     * Constructor
     * 
     * @since 1.1.0
     */
    public function __construct() {

        add_action( 'init', array( $this, 'track_visitors' ) );
        add_action( 'wp', array( $this, 'track_impressions' ) );
        add_action( 'template_redirect', array( $this, 'track_clicks' ) );
        add_action( 'woocommerce_checkout_order_processed', array( $this, 'track_sales' ) );

    }

    /**
     * Track visitors | Action Callback
     * 
     * @since 1.1.0
     */
    public function track_visitors() {

        // Run only on frontend and not in admin or REST API requests.
        if ( is_admin() || defined( 'REST_REQUEST' ) && REST_REQUEST ) {

            return;

        }

        $visitor_ip = mdwc_get_ip_address();
        $this->visitor_id = mdwc_get_visitor_id( $visitor_ip );

        return array(
            'visitor_id' => $this->visitor_id,
            'visitor_ip' => $visitor_ip
        );

    }

    /**
     * Track impressions | Action Callback
     * 
     * @since 1.1.0
     */
    public function track_impressions() {

        if ( is_shop() || is_product_category() || is_product_tag() ) {
            
            global $wp_query;

            // Loop through products displayed on the page
            if ( isset( $wp_query->posts ) && is_array( $wp_query->posts ) ) {

                foreach ( $wp_query->posts as $post ) {

                    if ( $post->post_type === 'product' ) {
                        
                        $product_id = $post->ID;
                        mdwc_insert_event( $product_id, 'impression', mdwc_is_deal_valid( $product_id ), '', $this->visitor_id );

                    }
                }
            }
        }

    }

    /**
     * Track Clicks | Action Callback
     * 
     * @since 1.1.0
     */
    public function track_clicks() {

        if( is_product() ) {

            $product_id = get_the_ID();

            mdwc_insert_event( $product_id, 'click', mdwc_is_deal_valid( $product_id ), '', $this->visitor_id );

        }

    }

    /**
     * Track Sales | Action Callback
     * 
     * @since 1.1.0
     */
    public function track_sales( $order_id ) {

        $order = wc_get_order( $order_id );

        foreach( $order->get_items() as $item_id => $item ) {

            $product_id = $item->get_product_id();
            $price = $item->get_total();

            mdwc_insert_event( $product_id, 'sale', mdwc_is_deal_valid( $product_id ), $price, $this->visitor_id );

        }

    }

}

MDWC_Insights::get_instance();

endif;