/**
 * 此代码是把网站客户行为提交至谷歌统计平台,方便网站营销统计。
 * 包含产品浏览事件、加入购物事件、结算事件和已支付购物事件。
 */

// Place the Google Analytics tag on your website
add_action('wp_head', function(){
	$tag_id = 'G-M8KN93S6CP'; // 改为你自己的tag_id
?>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo $tag_id ?>"></script>
<script>
	
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  //gtag('config', '<?php echo $tag_id ?>');
  gtag('config', '<?php echo $tag_id ?>',{ 'debug_mode': true , 'groups': 'wc'});
</script>
<?php
});


// submit view_item event
add_action('wp_head', function(){
if (is_product()) {
	$category_name = yy_get_category();
?>
<script>
	gtag('event', 'view_item', {
		'items': [{
			'id': '<?php echo get_the_ID(); ?>',
			'name': '<?php echo get_the_title(); ?>',
			'category': '<?php echo $category_name ?>',
			'list_name': 'Product Detail View'
		}],
		'send_to': 'wc'
	});
</script>
<?php
}

});

// submit add_to_cart event
add_action('wp_head', function(){
    if (is_product()) {
			$product = wc_get_product();

        ?>
        <script>
            gtag('event', 'add_to_cart', {
                'items': [{
                    'id': '<?php echo $product->get_id(); ?>',
                    'name': '<?php echo $product->get_title(); ?>',
                    'category': '<?php echo yy_get_category() ?>',
                    'quantity': 1,
                    'price': <?php echo $product->get_price(); ?>
                }],
					'send_to': 'wc'
            });
        </script>
        <?php
    }

});

// submit begin_checkout event
add_action('wp_head', function(){
    if (is_checkout() && !is_wc_endpoint_url()) {
			$items = WC()->cart->get_cart();
			$product_data = [];
			foreach ( $items as $item => $values) {
				$_product =  wc_get_product( $values['data']->get_id()); 
				$product_title = $_product->get_title();
				$product_price = get_post_meta($values['product_id'] , '_price', true);
				$product_quantity = $values['quantity'];
				$product_data[] = array(
					'id' => $values['product_id'],
					'name' => $product_title,
					'price' => $product_price,
					'quantity' => $product_quantity
				);
			}
			
		  $total_price = WC()->cart->get_cart_total();
		  $total_price = trim(strip_tags(html_entity_decode($total_price)));
		  $total_price =  str_replace(['$','¥'], "", $total_price);
        ?>
        <script>
				gtag('event', 'begin_checkout', {
					'event_category': 'Ecommerce',
					'event_label': 'Begin Checkout',
					'value': <?php echo $total_price; ?>,
					'items': <?php echo json_encode( $product_data ); ?>,
					'send_to': 'wc'
				});
			</script>
        <?php
    }

});

// submit purchase event
function add_ga4_purchase_event($order_id) {
    $order = wc_get_order($order_id);

    $order_total = $order->get_total();

    ?>
    <script>
    gtag('event', 'purchase', {
      "transaction_id": "<?php echo $order_id; ?>",
      "value": <?php echo $order_total; ?>,
      "currency": "<?php echo get_woocommerce_currency(); ?>",
		'send_to': 'wc'
    });
    </script>
    <?php
}

add_action('woocommerce_thankyou', 'add_ga4_purchase_event');

function yy_get_category(){
	$product = wc_get_product();
	$terms = get_the_terms( $product->get_id(), 'product_cat' );

	if ( ! empty( $terms ) ) {
		return $terms[0]->name;
	}
	return 'Uncategorized';
}