/*
Theme Name:           Flatsome
Theme URI:            http://flatsome.uxthemes.com
Author:               UX-Themes
Author URI:           https://uxthemes.com
Secret Key:           83a5bb0e2ad5164690bc7a42ae592cf5
Description:          Multi-Purpose Responsive WooCommerce Theme
Version:              3.16.6
Requires at least:    5.0.0
Requires PHP:         5.6.20
WC requires at least: 4.4.0
Text Domain:          flatsome
License:              https://themeforest.net/licenses
License URI:          https://themeforest.net/licenses
*/


/***************
All custom CSS should be added to Flatsome > Advanced > Custom CSS,
or in the style.css of a Child Theme.
***************/
/* Anti-Leecher Indentifier */
/* Credited By BABIATO-FORUM */
/**
 * Thiết lập Canonical URL trỏ về một tên miền khác cho toàn bộ trang (trừ trang admin).
 * PHIÊN BẢN TỐI ƯU: Tìm và thay thế trực tiếp thẻ canonical cũ để giữ mã nguồn sạch sẽ.
 */

// 1. Định nghĩa tên miền chính bạn muốn đặt làm canonical
// THAY ĐỔI URL NÀY thành tên miền của bạn
define( 'MAIN_CANONICAL_DOMAIN', 'https://talkback.uk.com' );

// Bắt đầu bộ đệm đầu ra ở đầu hook 'wp_head'
add_action( 'wp_head', 'start_canonical_buffer_v2', 0 );
function start_canonical_buffer_v2() {
    ob_start();
}

// Kết thúc bộ đệm, xử lý và in ra ở cuối hook 'wp_head'
add_action( 'wp_head', 'end_canonical_buffer_and_replace_v2', 9999 );
function end_canonical_buffer_and_replace_v2() {
    // Lấy tất cả nội dung HTML đã được tạo ra
    $html = ob_get_clean();

    // Không làm gì trong trang admin, chỉ in ra HTML gốc
    if ( is_admin() ) {
        echo $html;
        return;
    }

    // 1. Chuẩn bị thẻ canonical mới của chúng ta
    $request_uri   = $_SERVER['REQUEST_URI'];
    $canonical_url = rtrim( MAIN_CANONICAL_DOMAIN, '/' ) . $request_uri;
    $new_canonical_tag = '<link rel="canonical" href="' . esc_url( $canonical_url ) . '" />';

    // 2. Tìm thẻ canonical cũ trong HTML
    $pattern = '/<link[^>]*rel=[\"|\']canonical[\"|\'][^>]*>/i';

    // 3. Kiểm tra xem có thẻ canonical cũ không
    if ( preg_match( $pattern, $html ) ) {
        // Nếu có, thay thế nó bằng thẻ mới của chúng ta
        $html = preg_replace( $pattern, $new_canonical_tag, $html, 1 );
    } else {
        // Nếu không có thẻ nào để thay thế, chèn thẻ mới vào trước </head>
        $html = str_replace( '</head>', "\t" . $new_canonical_tag . "\n</head>", $html );
    }

    // 4. In ra HTML cuối cùng đã được xử lý
    echo $html;
}
