<?php

function m_meta($page_sef,$canoncial,$data='',$image='') 
{
	$db = new DB();
	$return = array();
	$site_name = $db->table('metas')->where('page_sef','=','site_name')->get_var('m_title');
	$short_brand = $db->table('metas')->where('page_sef','=','short_brand')->get_var('m_title');
	
	$site_name = lang($site_name,LANG_CODE);
	$short_brand = lang($short_brand,LANG_CODE);
	
	if(m_u_g('page_no')!='')
	{
		$short_brand = ''.__('page').' '.m_u_g('page_no').' - '.$short_brand.'';
		$canoncial = $canoncial.'/page/'.m_u_g('page_no');
	}
	$informations = $db->table('metas')->where('page_sef','=',$page_sef)->order('id','desc')->limit(1)->get();
	$info = $informations['data'][0];
	$return['site_name'] = $site_name;
	$return['canoncial'] = $canoncial;
	$return['image'] = $image;
	$return['title'] = str_replace('[short_brand]',$short_brand,str_replace("[data]",$data,lang($info['m_title'],LANG_CODE)));
	$return['description'] = str_replace('[short_brand]',$short_brand,str_replace("[data]",$data,lang($info['m_description'],LANG_CODE)));
	$return['keywords'] = str_replace('[short_brand]',$short_brand,str_replace("[data]",$data,lang($info['m_keywords'],LANG_CODE)));
	return $return;
}

function m_header()
{
	global $meta_informations;
	$db = new DB();
	require_once(SITE_THEME_DIR.'/header.php');
}

function m_footer()
{
	global $meta_informations;
	$db = new DB();
	require_once(SITE_THEME_DIR.'/footer.php');
}

function m_pagination($sayfa, $oldugu, $veri, $name="") 
{
       if ($sayfa > 1)
       {
           if ($oldugu < 3) { $Basla = 1; }else{ $Basla = $oldugu-2; }
           if ($oldugu <= $sayfa-2) { $Bitis = $oldugu + 2; }else{ $Bitis = $sayfa; }
           if ($oldugu != 1) { $Onceki = $oldugu-1; }else{ $Onceki = 1; }
           if ($oldugu != $sayfa) { $Sonraki = $oldugu+1; }else{ $Sonraki = $sayfa; }
		if($Onceki=="1")
		{
		$Oncekilink = '<li><a class="page-numbers next" href="'.$veri.'">'.__('first').'</a></li>';
		}
		else {
		$Oncekilink = '<li><a class="page-numbers next" href="'.$veri.'">'.__('first').'</a></li>';
		}
		$Gonderilecek = '<div class="pq-pagination">
				<nav aria-label="Page navigation">
				   <ul class="page-numbers">
		'.$Oncekilink.'';
			
           for ($j=$Basla; $j<=$Bitis; $j++)
           {
               if ($j!=$oldugu)
               {
				if($j=="1")
				{
				 $Gonderilecek .=  '<li><a class="page-numbers" href="'.$veri.'">'.$j.'</a></li>';
				}
				else {
				 $Gonderilecek .=  '<li><a class="page-numbers" href="'.$veri.'/page/'.$j.'">'.$j.'</a></li>';
				}
               }else{
                   $Gonderilecek .=  '<li><a class="page-numbers current" href="#">'.$j.'</a></li>';
               }
           }

				   $Gonderilecek .= '<li><a class="page-numbers next" href="'.$veri.'/page/'.$sayfa.'">'.__('end').'</a></li>
		
	</ul>
	</nav>
	</div>';
       }else{
           $Gonderilecek = '';
       }

       return $Gonderilecek;
}
function m_admin_pagination($sayfa, $oldugu, $veri, $name="") 
{
		$sayfa = $sayfa-1;
       if ($sayfa > 1)
       {
           if ($oldugu < 3) { $Basla = 1; }else{ $Basla = $oldugu-2; }
           if ($oldugu <= $sayfa-2) { $Bitis = $oldugu + 2; }else{ $Bitis = $sayfa; }
           if ($oldugu != 1) { $Onceki = $oldugu-1; }else{ $Onceki = 1; }
           if ($oldugu != $sayfa) { $Sonraki = $oldugu+1; }else{ $Sonraki = $sayfa; }
		if($Onceki=="1")
		{
		$Oncekilink = '<a href="'.$veri.'" class="btn">İlk</a>';
		}
		else {
		$Oncekilink = '<a href="'.$veri.'" class="btn">İlk</a>';
		}
		$Gonderilecek = '
	
				<div class="pager">
		
				 '.$Oncekilink.'';
			
           for ($j=$Basla; $j<=$Bitis; $j++)
           {
               if ($j!=$oldugu)
               {
				if($j=="1")
				{
				 $Gonderilecek .=  '<a href="'.$veri.'" class="btn">'.$j.'</a>';
				}
				else {
				 $Gonderilecek .=  '<a href="'.$veri.'&basla='.$j.'" class="btn"><b>'.$j.'</b></a>';
				}
               }else{
                   $Gonderilecek .=  '	<a class="btn"><b>'.$j.'</b></a>';
               }
           }

				   $Gonderilecek .= '	
		<a href="'.$veri.'&basla='.$sayfa.'" class="btn">Son</a>
		
</div>		';
       }else{
           $Gonderilecek = '';
       }

       return $Gonderilecek;
}
function m_alert($title,$data)
{
	switch($title)
	{
		case __('error'):
		$type = 'danger';
		$icon = 'fa-exclamation-triangle';
		break;
		case __('info'):
		$type = 'info';
		$icon = 'fa-info-circle';
		break;
		case __('success'):
		$type = 'success';
		$icon = 'fa-check-square';
		break;
		default;
		$type = "info";
	}
	
	return '<div class="alert alert-'.$type.'"  style="text-align:left;word-break: break-word;">
	<i class="fa '.$icon.'"></i> 
	  '.$title.': '.$data.'
	</div>';
}
function m_admin_alert($title,$data)
{
	switch($title)
	{
		case 'Hata':
		$type = 'danger';
		$icon = 'fa-exclamation-triangle';
		break;
		case 'Bilgi':
		$type = 'info';
		$icon = 'fa-info-circle';
		break;
		case 'Başarılı':
		$type = 'success';
		$icon = 'fa-check-square';
		break;
		default;
		$type = "info";
	}
	
	return '<div class="alert alert-'.$type.'"  style="text-align:left;word-break: break-word;">
	<i class="fa '.$icon.'"></i> 
	  '.$title.': '.$data.'
	</div>';
}
function m_status($data)
{
	if($data==0)
	{
	return '<span class="badge bg-danger text-light text-uppercase">'.lang('table_status_deactive', [], 'Bekliyor').'</span>';
	}
	if($data==1)
	{
		return '<span class="badge bg-success text-light text-uppercase">'.lang('table_status_active', [], 'Yayında').'</span>';
	}
    if($data==2)
	{
		return '<span class="badge bg-warning text-light text-uppercase">'.lang('table_status_draft', [], 'Taslak').'</span>';
	}
	
}
function m_read($data)
{
	if($data==0)
	{
		return '<span class="badge bg-warning">Okunmadı</span>';
	}
	if($data==1)
	{
		return '<span class="badge bg-success">Okundu</span>';
	}
	
}
function m_yes_no($data)
{
	if($data==0)
	{
		return '<span class="badge bg-warning">Hayır</span>';
	}
	if($data==1)
	{
		return '<span class="badge bg-success">Evet</span>';
	}
	
}
?>
<?php
// SEO yardımcıları – tek noktadan meta/og/twitter/canonical/hreflang/JSON-LD üretimi

if (!function_exists('render_seo_tags')) {
	function render_seo_tags(array $givenPost = null, ?string $lang = null) {
		// Dil belirleme
		if ($lang === null) {
			$lang = function_exists('m_get_session') && m_get_session('lang') ? m_get_session('lang') : (function_exists('lang_is_default') ? lang_is_default('lang_code') : 'tr');
		}

		// URL ve POST tespiti
		$url = isset($_GET['url']) ? trim((string)$_GET['url']) : '';
		$post = is_array($givenPost) ? $givenPost : null;
		if ($post === null) {
			if ($url !== '' && function_exists('post_with_slug')) {
				$post = post_with_slug($url, $lang);
				if (!is_array($post) || empty($post['sef'])) { $post = null; }
			}
		}

		// Temel alanlar
		$siteTitle = function_exists('settings') ? (settings('site_title', $lang) ?: 'Website') : 'Website';
		$baseTitle = $siteTitle;
		$metaDescription = function_exists('settings') ? (settings('site_description', $lang) ?: '') : '';
		$metaKeywords = function_exists('settings') ? (settings('site_keywords', $lang) ?: '') : '';
		$ogImage = function_exists('general_settings') ? (general_settings('default_og_image', $lang) ?: '') : '';
		if ($post) {
			if (!empty($post['seo_title'])) { $baseTitle = (string)$post['seo_title']; }
			elseif (!empty($post['title'])) { $baseTitle = (string)$post['title']; }
			if (!empty($post['seo_description'])) { $metaDescription = (string)$post['seo_description']; }
			elseif (!empty($post['description'])) { $metaDescription = (string)$post['description']; }
			if (!empty($post['seo_keywords'])) { $metaKeywords = (string)$post['seo_keywords']; }
			// Görsel alanı tahmini: image / cover / thumbnail
			$imgCandidate = '';
			foreach (['og_image','image','cover','thumbnail','featured_image'] as $k) {
				if (isset($post[$k]) && (string)$post[$k] !== '') { $imgCandidate = (string)$post[$k]; break; }
			}
			if ($imgCandidate !== '') { $ogImage = $imgCandidate; }
		}

		// Title – site adıyla birleştir (tekrarları önle)
		$metaTitle = $siteTitle;
		if (trim($baseTitle) !== '' && mb_strtolower(trim($baseTitle)) !== mb_strtolower(trim($siteTitle))) {
			$metaTitle = trim($baseTitle) . ' - ' . trim($siteTitle);
		}

		// Canonical URL – kök URL'yi slash'lı normalize et
		$canonicalBase = rtrim(DOMAIN, '/');
		if ($post && !empty($post['sef'])) {
			$canonical = $canonicalBase . '/' . ltrim($post['sef'], '/');
		} else {
			$canonical = $canonicalBase . '/';
		}

		// OG görseli tam URL yap (gerekirse)
		if ($ogImage !== '') {
			if (preg_match('/^https?:\/\//i', $ogImage) !== 1) {
				if (function_exists('image')) { $ogImage = image($ogImage); }
				else { $ogImage = rtrim(DOMAIN,'/') . '/' . ltrim($ogImage,'/'); }
			}
		}

		// OG türü tahmini
		$ogType = 'website';
		if ($post && isset($post['module_type'])) {
			$mt = strtolower((string)$post['module_type']);
			if (in_array($mt, ['post','posts','blog','article'], true)) { $ogType = 'article'; }
		}

		// Twitter hesapları (ayarlar)
		$twitterSite = function_exists('general_settings') ? (general_settings('twitter_site', $lang) ?: '') : '';
		$twitterCreator = function_exists('general_settings') ? (general_settings('twitter_creator', $lang) ?: '') : '';

		// Çıktı
		echo "\n<title>" . htmlspecialchars($metaTitle, ENT_QUOTES, 'UTF-8') . "</title>\n";
		if ($metaDescription !== '') {
			echo '<meta name="description" content="' . htmlspecialchars($metaDescription, ENT_QUOTES, 'UTF-8') . '">' . PHP_EOL;
		}
		if ($metaKeywords !== '') {
			echo '<meta name="keywords" content="' . htmlspecialchars($metaKeywords, ENT_QUOTES, 'UTF-8') . '">' . PHP_EOL;
		}
		echo '<link rel="canonical" href="' . htmlspecialchars($canonical, ENT_QUOTES, 'UTF-8') . '">' . PHP_EOL;

		// Open Graph
		echo '<meta property="og:title" content="' . htmlspecialchars($metaTitle, ENT_QUOTES, 'UTF-8') . '">' . PHP_EOL;
		if ($metaDescription !== '') { echo '<meta property="og:description" content="' . htmlspecialchars($metaDescription, ENT_QUOTES, 'UTF-8') . '">' . PHP_EOL; }
		if ($ogImage !== '') {
			echo '<meta property="og:image" content="' . htmlspecialchars($ogImage, ENT_QUOTES, 'UTF-8') . '">' . PHP_EOL;
			// Önerilen boyut bilgisi (varsayılan 1200x630)
			echo '<meta property="og:image:width" content="1200">' . PHP_EOL;
			echo '<meta property="og:image:height" content="630">' . PHP_EOL;
		}
		// Güncelleme zamanı (varsa)
		if ($post && !empty($post['updated_at'])) {
			echo '<meta property="og:updated_time" content="' . htmlspecialchars((string)$post['updated_at'], ENT_QUOTES, 'UTF-8') . '">' . PHP_EOL;
		}
		echo '<meta property="og:url" content="' . htmlspecialchars($canonical, ENT_QUOTES, 'UTF-8') . '">' . PHP_EOL;
		echo '<meta property="og:type" content="' . $ogType . '">' . PHP_EOL;
		echo '<meta property="og:site_name" content="' . htmlspecialchars($siteTitle, ENT_QUOTES, 'UTF-8') . '">' . PHP_EOL;
		echo '<meta property="og:locale" content="' . htmlspecialchars(str_replace('-', '_', strtolower($lang) === 'tr' ? 'tr_TR' : (strtolower($lang) . '_' . strtoupper($lang))), ENT_QUOTES, 'UTF-8') . '">' . PHP_EOL;

		// Twitter Cards
		echo '<meta name="twitter:card" content="summary_large_image">' . PHP_EOL;
		echo '<meta name="twitter:title" content="' . htmlspecialchars($metaTitle, ENT_QUOTES, 'UTF-8') . '">' . PHP_EOL;
		if ($metaDescription !== '') { echo '<meta name="twitter:description" content="' . htmlspecialchars($metaDescription, ENT_QUOTES, 'UTF-8') . '">' . PHP_EOL; }
		if ($ogImage !== '') {
			echo '<meta name="twitter:image" content="' . htmlspecialchars($ogImage, ENT_QUOTES, 'UTF-8') . '">' . PHP_EOL;
			$imgAlt = $baseTitle ?: $siteTitle;
			echo '<meta name="twitter:image:alt" content="' . htmlspecialchars($imgAlt, ENT_QUOTES, 'UTF-8') . '">' . PHP_EOL;
		}
		if ($twitterSite !== '') { echo '<meta name="twitter:site" content="' . htmlspecialchars($twitterSite, ENT_QUOTES, 'UTF-8') . '">' . PHP_EOL; }
		if ($twitterCreator !== '') { echo '<meta name="twitter:creator" content="' . htmlspecialchars($twitterCreator, ENT_QUOTES, 'UTF-8') . '">' . PHP_EOL; }

		// Arama Motoru Doğrulama Meta Etiketleri (ayarlar üzerinden)
		$gMethod = function_exists('general_settings') ? (general_settings('google_verify_method', $lang) ?: 'html') : 'html';
		$yMethod = function_exists('general_settings') ? (general_settings('yandex_verify_method', $lang) ?: 'html') : 'html';
		$googleToken = function_exists('general_settings') ? (general_settings('google_meta_token', $lang) ?: general_settings('google_key', $lang)) : '';
		$yandexToken = function_exists('general_settings') ? (general_settings('yandex_meta_token', $lang) ?: general_settings('yandex_key', $lang)) : '';
		$bingToken = function_exists('general_settings') ? (general_settings('bing_meta_token', $lang) ?: '') : '';
		if ($gMethod === 'meta' && $googleToken) {
			echo '<meta name="google-site-verification" content="' . htmlspecialchars($googleToken, ENT_QUOTES, 'UTF-8') . '">' . PHP_EOL;
		}
		if ($yMethod === 'meta' && $yandexToken) {
			echo '<meta name="yandex-verification" content="' . htmlspecialchars($yandexToken, ENT_QUOTES, 'UTF-8') . '">' . PHP_EOL;
		}
		if ($bingToken) {
			echo '<meta name="msvalidate.01" content="' . htmlspecialchars($bingToken, ENT_QUOTES, 'UTF-8') . '">' . PHP_EOL;
		}

		// hreflang (yalnızca içerik varyantları biliniyorsa)
		if ($post && isset($post['lang_ref_id']) && (int)$post['lang_ref_id'] > 0 && function_exists('posts_langs')) {
			$variants = posts_langs($post['lang_ref_id'], $lang);
			if (is_array($variants)) {
				$seen = [];
				foreach ($variants as $v) {
					if (!isset($v['lang']) || !isset($v['sef']) || $v['status'] != 1) { continue; }
					$code = strtolower((string)$v['lang']);
					if (isset($seen[$code])) { continue; }
					$href = rtrim(DOMAIN,'/') . '/' . ltrim((string)$v['sef'], '/');
					echo '<link rel="alternate" hreflang="' . htmlspecialchars($code, ENT_QUOTES, 'UTF-8') . '" href="' . htmlspecialchars($href, ENT_QUOTES, 'UTF-8') . '">' . PHP_EOL;
					$seen[$code] = true;
				}
				// x-default ana sürüm
				echo '<link rel="alternate" hreflang="x-default" href="' . htmlspecialchars($canonical, ENT_QUOTES, 'UTF-8') . '">' . PHP_EOL;
			}
		}

		// JSON-LD (WebSite)
		$ldWebsite = [
			'@context' => 'https://schema.org',
			'@type' => 'WebSite',
			'name' => $siteTitle,
			'url' => rtrim(DOMAIN,'/') . '/',
		];
		echo "<script type=\"application/ld+json\">" . json_encode($ldWebsite, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) . "</script>\n";

		// JSON-LD (Organization)
		$orgLogo = '';
		if (function_exists('general_settings')) {
			$logoSetting = (string) (general_settings('logo', $lang) ?: general_settings('favicon', $lang));
			if ($logoSetting !== '') { $orgLogo = function_exists('image') ? image($logoSetting) : (rtrim(DOMAIN,'/') . '/' . ltrim($logoSetting,'/')); }
		}
		$ldOrg = [
			'@context' => 'https://schema.org',
			'@type' => 'Organization',
			'name' => $siteTitle,
			'url' => rtrim(DOMAIN,'/') . '/',
		];
		if ($orgLogo !== '') { $ldOrg['logo'] = $orgLogo; }
		echo "<script type=\"application/ld+json\">" . json_encode($ldOrg, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) . "</script>\n";

		// JSON-LD (Article) – içerik sayfalarında
		if ($ogType === 'article' && $post) {
			$ldArticle = [
				'@context' => 'https://schema.org',
				'@type' => 'Article',
				'headline' => $baseTitle ?: $metaTitle,
				'description' => $metaDescription,
				'inLanguage' => strtoupper($lang),
				'mainEntityOfPage' => $canonical,
				'author' => [
					'@type' => 'Organization',
					'name' => $siteTitle
				]
			];
			if ($ogImage !== '') { $ldArticle['image'] = [$ogImage]; }
			if (!empty($post['updated_at'])) { $ldArticle['dateModified'] = (string)$post['updated_at']; }
			echo "<script type=\"application/ld+json\">" . json_encode($ldArticle, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) . "</script>\n";
		}

		// JSON-LD (BreadcrumbList) – iç sayfalarda (en az 2 adımlı: Ana Sayfa + Sayfa)
		$hasInnerPage = ($post && !empty($post['sef']));
		if ($hasInnerPage) {
			$homeName = function_exists('lang') ? lang('breadcrumb.home', [], 'Ana Sayfa') : 'Ana Sayfa';
			$ldBreadcrumb = [
				'@context' => 'https://schema.org',
				'@type' => 'BreadcrumbList',
				'itemListElement' => [
					[
						'@type' => 'ListItem',
						'position' => 1,
						'name' => $homeName,
						'item' => rtrim(DOMAIN,'/') . '/'
					],
					[
						'@type' => 'ListItem',
						'position' => 2,
						'name' => $baseTitle ?: $metaTitle,
						'item' => $canonical
					]
				]
			];
			echo "<script type=\"application/ld+json\">" . json_encode($ldBreadcrumb, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) . "</script>\n";
		}
	}
}

// Analitik – Matomo izleme kodunu tek noktadan üret
if (!function_exists('render_analytics_tracking')) {
    function render_analytics_tracking(?string $lang = null): void {
        if ($lang === null) {
            $lang = function_exists('m_get_session') && m_get_session('lang') ? m_get_session('lang') : (function_exists('lang_is_default') ? lang_is_default('lang_code') : 'tr');
        }
        if (!function_exists('general_settings')) { return; }
        $enabled = (string) (general_settings('analytics_enabled', $lang) ?: '0');
        $provider = (string) (general_settings('analytics_provider', $lang) ?: 'matomo');
        $endpoint = rtrim((string) general_settings('analytics_endpoint', $lang), '/');
        $siteId = (string) (general_settings('analytics_site_id', $lang) ?: '');
        if ($enabled !== '1' || $provider !== 'matomo' || $endpoint === '' || $siteId === '') { return; }

        // Opsiyonel gizlilik bayrakları (varsayılan kapalı)
        $respectDnt = (string) (general_settings('analytics_dnt', $lang) ?: '0');
        $disableCookies = (string) (general_settings('analytics_disable_cookies', $lang) ?: '0');
        // Consent varsayılan: gerekmiyor (Matomo default). Eğer gerektirilecekse panelde ayrıca yönetilebilir.
        $requireConsent = (string) (general_settings('analytics_consent_required', $lang) ?: '0');
        $consentStyle = (string) (general_settings('analytics_consent_style', $lang) ?: 'minimal');

        // Çıktı – defer yüklenecek hafif snippet
        echo "\n<script>\n  var _paq = window._paq = window._paq || [];\n  try { _paq.push(['setDomains', [window.location.hostname]]); } catch(e) {}\n  _paq.push(['enableLinkTracking']);\n";
        if ($respectDnt === '1') {
            echo "  _paq.push(['setDoNotTrack', true]);\n";
        } else {
            echo "  _paq.push(['setDoNotTrack', false]);\n";
        }
        if ($disableCookies === '1') {
            echo "  _paq.push(['disableCookies']);\n";
        }
        if ($requireConsent === '1') {
            echo "  _paq.push(['requireConsent']);\n";
        }
        echo "  document.addEventListener('DOMContentLoaded', function(){ try{ _paq.push(['trackPageView']); }catch(e){} });\n  (function(){\n    var u = '" . htmlspecialchars($endpoint, ENT_QUOTES, 'UTF-8') . "/';\n    _paq.push(['setTrackerUrl', u + 'matomo.php']);\n    _paq.push(['setSiteId', '" . htmlspecialchars($siteId, ENT_QUOTES, 'UTF-8') . "']);\n    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];\n    g.async = true; g.defer = true; g.src = u + 'matomo.js'; s.parentNode.insertBefore(g,s);\n  })();\n";

        // Eğer açık rıza gerektiriliyorsa, seçilen stile göre consent bileşeni ekle
        if ($requireConsent === '1') {
            $tTitle  = function_exists('lang') ? lang('consent.banner.title', [], 'Çerez ve analiz izni') : 'Çerez ve analiz izni';
            $tText   = function_exists('lang') ? lang('consent.banner.text', [], 'Deneyiminizi geliştirmek için anonim analitik verileri topluyoruz. Kabul ediyor musunuz?') : 'Deneyiminizi geliştirmek için anonim analitik verileri topluyoruz. Kabul ediyor musunuz?';
            $tAccept = function_exists('lang') ? lang('consent.accept', [], 'Kabul Et') : 'Kabul Et';
            $tDecl   = function_exists('lang') ? lang('consent.decline', [], 'Reddet') : 'Reddet';
            $jsTitle  = json_encode($tTitle, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
            $jsText   = json_encode($tText, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
            $jsAccept = json_encode($tAccept, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
            $jsDecl   = json_encode($tDecl, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
            if ($consentStyle === 'advanced') {
                $tPrefs  = function_exists('lang') ? lang('consent.preferences', [], 'Tercihler') : 'Tercihler';
                $tAcceptAll = function_exists('lang') ? lang('consent.accept_all', [], 'Tümünü Kabul Et') : 'Tümünü Kabul Et';
                $tRejectAll = function_exists('lang') ? lang('consent.reject_all', [], 'Tümünü Reddet') : 'Tümünü Reddet';
                $tSave   = function_exists('lang') ? lang('consent.save', [], 'Kaydet') : 'Kaydet';
                $tNecessary = function_exists('lang') ? lang('consent.category.necessary', [], 'Gerekli') : 'Gerekli';
                $tAnalytics = function_exists('lang') ? lang('consent.category.analytics', [], 'Analitik') : 'Analitik';
                $tManage = function_exists('lang') ? lang('consent.manage', [], 'Çerez Tercihleri') : 'Çerez Tercihleri';
                $jsPrefs  = json_encode($tPrefs, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
                $jsAcceptAll = json_encode($tAcceptAll, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
                $jsRejectAll = json_encode($tRejectAll, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
                $jsSave   = json_encode($tSave, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
                $jsNecessary = json_encode($tNecessary, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
                $jsAnalytics = json_encode($tAnalytics, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
                $jsManage = json_encode($tManage, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
                $advJs = <<<'JS'
(function(){
  var KEY='analytics_consent', DETAIL='analytics_consent_detail';
  function hasConsented(){ return (localStorage.getItem(KEY)||'')==='granted'; }
  function hasDenied(){ return (localStorage.getItem(KEY)||'')==='denied'; }
  function remember(){ try{ if(window._paq){ _paq.push(['rememberConsentGiven']); } }catch(e){} }
  function forget(){ try{ if(window._paq){ _paq.push(['forgetConsentGiven']); } }catch(e){} }
  function setDetail(d){ try{ localStorage.setItem(DETAIL, JSON.stringify(d||{})); }catch(e){} }
  function getDetail(){ try{ return JSON.parse(localStorage.getItem(DETAIL)||'{}'); }catch(e){ return {}; } }
  function openModal(){
    if (document.getElementById('consent-modal')) return;
    var wrap = document.createElement('div'); wrap.id='consent-modal';
    wrap.innerHTML =
      '<div class="cons-overlay"></div>'+
      '<div class="cons-dialog" role="dialog" aria-modal="true" aria-label=' + __MANAGE__ + '>'+
        '<div class="cons-header">' + __MANAGE__ + '</div>'+
        '<div class="cons-body">'+
          '<p class="cons-text"><strong>' + __TITLE__ + '</strong><br>' + __TEXT__ + '</p>'+
          '<div class="cons-group">'+
            '<label class="cons-row">'+
              '<span class="cons-name">' + __NECESSARY__ + '</span>'+
              '<span class="cons-note">(always on)</span>'+
              '<input type="checkbox" checked disabled>'+
            '</label>'+
            '<label class="cons-row">'+
              '<span class="cons-name">' + __ANALYTICS__ + '</span>'+
              '<input id="cons-analytics" type="checkbox">'+
            '</label>'+
          '</div>'+
        '</div>'+
        '<div class="cons-actions">'+
          '<button type="button" class="btn light" id="cons-reject-all">' + __REJECT_ALL__ + '</button>'+
          '<button type="button" class="btn" id="cons-save">' + __SAVE__ + '</button>'+
          '<button type="button" class="btn primary" id="cons-accept-all">' + __ACCEPT_ALL__ + '</button>'+
        '</div>'+
        '<button type="button" class="cons-close" aria-label="close">×</button>'+
      '</div>';
    document.body.appendChild(wrap);
    var detail=getDetail(); var chk=wrap.querySelector('#cons-analytics'); if (detail && typeof detail.analytics==='boolean') { chk.checked = !!detail.analytics; }
    wrap.querySelector('.cons-overlay').addEventListener('click', closeModal);
    wrap.querySelector('.cons-close').addEventListener('click', closeModal);
    wrap.querySelector('#cons-accept-all').addEventListener('click', function(){ localStorage.setItem(KEY,'granted'); setDetail({analytics:true, ts:Date.now()}); remember(); closeModal(); });
    wrap.querySelector('#cons-reject-all').addEventListener('click', function(){ localStorage.setItem(KEY,'denied'); setDetail({analytics:false, ts:Date.now()}); forget(); closeModal(); });
    wrap.querySelector('#cons-save').addEventListener('click', function(){ var a=wrap.querySelector('#cons-analytics').checked; if(a){ localStorage.setItem(KEY,'granted'); remember(); } else { localStorage.setItem(KEY,'denied'); forget(); } setDetail({analytics:a, ts:Date.now()}); closeModal(); });
    function closeModal(){ try{wrap.remove();}catch(e){} }
  }
  function mountBar(){
    if (hasConsented() || hasDenied()) { addManageButton(); if (hasConsented()) remember(); return; }
    var bar=document.createElement('div'); bar.className='cons-bar'; bar.setAttribute('role','dialog'); bar.setAttribute('aria-live','polite');
    bar.innerHTML='<div class="cons-bar-text"><strong>' + __TITLE__ + '</strong><br>' + __TEXT__ + '</div>'+
      '<div class="cons-bar-actions">'+
      '<button type="button" class="btn light" id="cons-bar-decline">' + __DECLINE__ + '</button>'+
      '<button type="button" class="btn" id="cons-bar-prefs">' + __PREFS__ + '</button>'+
      '<button type="button" class="btn primary" id="cons-bar-accept">' + __ACCEPT__ + '</button>'+
      '</div>';
    document.body.appendChild(bar);
    document.getElementById('cons-bar-accept').addEventListener('click', function(){ localStorage.setItem(KEY,'granted'); setDetail({analytics:true, ts:Date.now()}); remember(); try{bar.remove();}catch(e){} addManageButton(); });
    document.getElementById('cons-bar-decline').addEventListener('click', function(){ localStorage.setItem(KEY,'denied'); setDetail({analytics:false, ts:Date.now()}); forget(); try{bar.remove();}catch(e){} addManageButton(); });
    document.getElementById('cons-bar-prefs').addEventListener('click', function(){ try{bar.remove();}catch(e){} openModal(); });
  }
  function addManageButton(){ if (document.getElementById('cons-manage')) return; var fab=document.createElement('button'); fab.id='cons-manage'; fab.type='button'; fab.setAttribute('aria-label','preferences'); fab.textContent='⚙'; document.body.appendChild(fab); fab.addEventListener('click', openModal); }
  function injectStyles(){ if (document.getElementById('cons-styles')) return; var s=document.createElement('style'); s.id='cons-styles'; s.textContent=
    '.cons-bar{position:fixed;left:16px;right:16px;bottom:16px;z-index:99998;background:#0b0b0b;color:#fff;padding:14px 16px;border-radius:12px;box-shadow:0 12px 40px rgba(0,0,0,.35);display:flex;gap:16px;align-items:center;justify-content:space-between}'+
    '.cons-bar-text{font-size:14px;line-height:1.45} .cons-bar-actions{display:flex;gap:8px}'+
    '.btn{background:#334155;color:#fff;border:0;border-radius:8px;padding:8px 12px;font-weight:600;cursor:pointer} .btn.light{background:#475569} .btn.primary{background:#22c55e}'+
    '.cons-overlay{position:fixed;inset:0;background:rgba(0,0,0,.55);backdrop-filter:saturate(1.2) blur(2px);z-index:99998}'+
    '.cons-dialog{position:fixed;inset:auto 0 0 0;margin:auto;background:#fff;color:#111;border-radius:14px;max-width:640px;width:calc(100% - 32px);padding:16px;z-index:99999;box-shadow:0 20px 60px rgba(0,0,0,.35)}'+
    '@media(min-width:768px){.cons-dialog{top:12vh;bottom:auto}}'+
    '.cons-header{font-weight:700;font-size:16px;margin-bottom:8px} .cons-text{font-size:14px;margin:0 0 12px}'+
    '.cons-group{border-top:1px solid #e5e7eb;padding-top:12px;margin-top:8px} .cons-row{display:flex;align-items:center;justify-content:space-between;padding:8px 0}'+
    '.cons-name{font-weight:600} .cons-actions{display:flex;gap:8px;justify-content:flex-end;margin-top:12px} .cons-note{font-size:12px;color:#666;margin-left:8px}'+
    '.cons-close{position:absolute;top:8px;right:10px;width:32px;height:32px;border-radius:50%;border:0;background:#f1f5f9;color:#111;cursor:pointer;font-size:18px;line-height:32px}'+
    '#cons-manage{position:fixed;left:16px;bottom:16px;width:40px;height:40px;border-radius:50%;border:0;background:#111;color:#fff;z-index:99997;box-shadow:0 8px 24px rgba(0,0,0,.35);cursor:pointer}'; document.head.appendChild(s);}
  function init(){ injectStyles(); if (document.readyState==='loading'){ document.addEventListener('DOMContentLoaded', mountBar); } else { mountBar(); } }
  init();
})();
JS;
                // Yer tutucuları doldur
                $advJs = strtr($advJs, [
                    '__MANAGE__' => $jsManage,
                    '__TITLE__' => $jsTitle,
                    '__TEXT__' => $jsText,
                    '__NECESSARY__' => $jsNecessary,
                    '__ANALYTICS__' => $jsAnalytics,
                    '__REJECT_ALL__' => $jsRejectAll,
                    '__SAVE__' => $jsSave,
                    '__ACCEPT_ALL__' => $jsAcceptAll,
                    '__DECLINE__' => $jsDecl,
                    '__PREFS__' => $jsPrefs,
                    '__ACCEPT__' => $jsAccept,
                ]);
                echo $advJs . "\n";
            } else {
                $minJs = "(function(){\n  var KEY='analytics_consent';\n  function hasConsented(){ return (localStorage.getItem(KEY)||'')==='granted'; }\n  function hasDenied(){ return (localStorage.getItem(KEY)||'')==='denied'; }\n  function remember(){ try{ if(window._paq){ _paq.push(['rememberConsentGiven']); } }catch(e){} }\n  function forget(){ try{ if(window._paq){ _paq.push(['forgetConsentGiven']); } }catch(e){} }\n  function mount(){\n    if (hasConsented() || hasDenied()) { if (hasConsented()) remember(); return; }\n    var bar = document.createElement('div');\n    bar.setAttribute('role','dialog'); bar.setAttribute('aria-live','polite');\n    bar.style.cssText='position:fixed;left:0;right:0;bottom:0;z-index:99999;background:#0b0b0b;color:#fff;padding:12px 16px;display:flex;gap:12px;align-items:center;justify-content:space-between;box-shadow:0 -4px 16px rgba(0,0,0,.25)';\n    var text=document.createElement('div'); text.style.cssText='font-size:14px;line-height:1.35;';\n    text.innerHTML='<strong>'+" . $jsTitle . "+'</strong><br>'+" . $jsText . ";\n    var actions=document.createElement('div'); actions.style.cssText='display:flex;gap:8px;';\n    var ok=document.createElement('button'); ok.type='button'; ok.textContent=" . $jsAccept . "; ok.style.cssText='background:#22c55e;color:#fff;border:0;border-radius:6px;padding:8px 12px;font-weight:600;cursor:pointer';\n    var no=document.createElement('button'); no.type='button'; no.textContent=" . $jsDecl . "; no.style.cssText='background:#374151;color:#fff;border:0;border-radius:6px;padding:8px 12px;font-weight:600;cursor:pointer';\n    ok.addEventListener('click', function(){ localStorage.setItem(KEY,'granted'); remember(); bar.remove(); });\n    no.addEventListener('click', function(){ localStorage.setItem(KEY,'denied'); forget(); bar.remove(); });\n    actions.appendChild(no); actions.appendChild(ok);\n    bar.appendChild(text); bar.appendChild(actions);\n    document.body.appendChild(bar);\n  }\n  if (document.readyState==='loading') { document.addEventListener('DOMContentLoaded', mount); } else { mount(); }\n})();";
                echo $minJs . "\n";
            }
        }

        echo "</script>\n";
    }
}

?>