<?php
defined('ABSPATH') || exit;

/**
 * REEID Page SEO — Canonical (NON-WOO ONLY)
 *
 * Canonical = CURRENT REQUEST URL (language-prefixed)
 * WooCommerce is HARD excluded.
 */

// Remove core canonical early
add_action('wp', function () {
    if (is_admin()) return;

    // if (function_exists('is_woocommerce') && is_woocommerce()) {
    //     return;
    // }

    remove_action('wp_head', 'rel_canonical');
}, 0);

// Emit canonical based on request URL
add_action( 'wp_head', function () {

	if ( is_admin() || ! is_singular() ) {
		return;
	}

	if ( function_exists( 'is_woocommerce' ) && is_woocommerce() ) {
		return;
	}

	$scheme = is_ssl() ? 'https' : 'http';

	$host_raw = filter_input( INPUT_SERVER, 'HTTP_HOST', FILTER_UNSAFE_RAW );
	$uri_raw  = filter_input( INPUT_SERVER, 'REQUEST_URI', FILTER_UNSAFE_RAW );

	$host = is_string( $host_raw ) ? sanitize_text_field( wp_unslash( $host_raw ) ) : '';
	$uri  = is_string( $uri_raw ) ? wp_unslash( $uri_raw ) : '';

	if ( $host === '' || $uri === '' ) {
		return;
	}

	$url = esc_url_raw( $scheme . '://' . $host . $uri );

	echo "\n" . '<link rel="canonical" href="' . esc_url( $url ) . '" />' . "\n";

}, 1 );