<?php
declare(strict_types=1);
/** @var string $pageTitle */
/** @var string|null $pageClass */
/** @var string|null $metaDescription */
/** @var string|null $ogTitle */
/** @var string|null $ogDescription */
/** @var string|null $ogImage */
/** @var string|null $ogUrl */
/** @var string|null $ogType */
/** @var int|null $ogImageWidth */
/** @var int|null $ogImageHeight */
/** @var string|null $ogImageType */
/** @var string|null $ogImageAlt */
/** @var array|null $jsonLd */
/** @var string|null $ogPriceAmount */
/** @var string|null $ogPriceCurrency */

$user = current_user();
$pageClass = $pageClass ?? '';
$isAdminChrome = str_contains($pageClass, 'page-admin');
$isAdminLogin = str_contains($pageClass, 'page-admin-login');
$flash = ($isAdminChrome && !$isAdminLogin) ? null : get_flash();
$isAdmin = is_admin($user);
$displayName = function_exists('site_name') ? site_name() : APP_NAME;
$displayTagline = function_exists('setting') ? (setting('tagline') ?: APP_TAGLINE) : APP_TAGLINE;

$metaDescription = $metaDescription ?? ($displayName . ' — bölgesel doğal ürün vitrini. Link ile paylaşılır.');
$ogTitle = $ogTitle ?? ($pageTitle ?? $displayName);
$ogDescription = $ogDescription ?? $metaDescription;
$ogImage = $ogImage ?? absolute_url(site_logo_url());
$ogUrl = $ogUrl ?? app_base_url() . ($_SERVER['REQUEST_URI'] ?? '/');
$ogType = $ogType ?? 'website';
$ogImageWidth = $ogImageWidth ?? null;
$ogImageHeight = $ogImageHeight ?? null;
$ogImageType = $ogImageType ?? null;
$ogImageAlt = $ogImageAlt ?? $ogTitle;
$jsonLd = $jsonLd ?? null;
$ogPriceAmount = $ogPriceAmount ?? null;
$ogPriceCurrency = $ogPriceCurrency ?? 'TRY';

// Admin: tam noindex.
// Vitrin "Google'da görünmesin": SADECE meta googlebot/bingbot — X-Robots-Tag kullanma.
// (Bazı WhatsApp/Facebook istemcileri header'daki "noindex" kelimesini yanlış okuyup kartı düşürüyor.)
$hideSearch = !$isAdminChrome && function_exists('site_hide_from_search') && site_hide_from_search();
if ($isAdminChrome) {
    header('X-Robots-Tag: noindex, nofollow, noarchive', false);
}
?>
<!DOCTYPE html>
<?php
$protectAttr = (!$isAdminChrome && function_exists('theme_protect_attr'))
    ? theme_protect_attr(function_exists('theme_get') ? theme_get() : null)
    : '';
?>
<html lang="tr"<?= $protectAttr !== '' ? ' data-protect="' . e($protectAttr) . '"' : '' ?>>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= e($pageTitle ?? $displayName) ?> · <?= e($displayName) ?></title>
    <meta name="description" content="<?= e($metaDescription) ?>">
    <?php if ($isAdminChrome): ?>
        <meta name="robots" content="noindex, nofollow, noarchive, nosnippet">
    <?php elseif ($hideSearch): ?>
        <meta name="googlebot" content="noindex, nofollow, noarchive, nosnippet">
        <meta name="bingbot" content="noindex, nofollow, noarchive, nosnippet">
    <?php else: ?>
        <meta name="robots" content="index, follow">
    <?php endif; ?>
    <link rel="canonical" href="<?= e($ogUrl) ?>">

    <!-- Open Graph — WhatsApp / Facebook / LinkedIn -->
    <meta property="og:site_name" content="<?= e($displayName) ?>">
    <meta property="og:type" content="<?= e($ogType) ?>">
    <meta property="og:title" content="<?= e($ogTitle) ?>">
    <meta property="og:description" content="<?= e($ogDescription) ?>">
    <meta property="og:url" content="<?= e($ogUrl) ?>">
    <meta property="og:locale" content="tr_TR">
    <meta property="og:image" content="<?= e($ogImage) ?>">
    <meta property="og:image:secure_url" content="<?= e($ogImage) ?>">
    <meta property="og:image:alt" content="<?= e($ogImageAlt) ?>">
    <?php if ($ogImageWidth): ?>
        <meta property="og:image:width" content="<?= (int) $ogImageWidth ?>">
    <?php endif; ?>
    <?php if ($ogImageHeight): ?>
        <meta property="og:image:height" content="<?= (int) $ogImageHeight ?>">
    <?php endif; ?>
    <?php if ($ogImageType): ?>
        <meta property="og:image:type" content="<?= e($ogImageType) ?>">
    <?php endif; ?>
    <?php if ($ogPriceAmount !== null && $ogPriceAmount !== ''): ?>
        <meta property="product:price:amount" content="<?= e((string) $ogPriceAmount) ?>">
        <meta property="product:price:currency" content="<?= e((string) $ogPriceCurrency) ?>">
    <?php endif; ?>

    <!-- Twitter / X -->
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:title" content="<?= e($ogTitle) ?>">
    <meta name="twitter:description" content="<?= e($ogDescription) ?>">
    <meta name="twitter:image" content="<?= e($ogImage) ?>">
    <meta name="twitter:image:alt" content="<?= e($ogImageAlt) ?>">

    <?php if (is_array($jsonLd) && $jsonLd): ?>
        <script type="application/ld+json"><?= json_encode($jsonLd, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?></script>
    <?php endif; ?>

    <?php
    $faviconUrl = function_exists('site_favicon_url') ? site_favicon_url() : url('assets/img/logo.svg');
    $faviconType = function_exists('site_favicon_type') ? site_favicon_type() : 'image/svg+xml';
    if (function_exists('site_control_client_gate_script') && !str_contains($pageClass, 'page-admin')) {
        echo site_control_client_gate_script();
    }
    ?>
    <link rel="icon" href="<?= e($faviconUrl) ?>" type="<?= e($faviconType) ?>">
    <link rel="shortcut icon" href="<?= e($faviconUrl) ?>" type="<?= e($faviconType) ?>">
    <link rel="apple-touch-icon" href="<?= e($faviconUrl) ?>">

    <?php
    $theme = function_exists('theme_get') ? theme_get() : [];
    $themeFontsHref = function_exists('theme_google_fonts_href')
        ? theme_google_fonts_href($theme)
        : 'https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700&family=Fraunces:opsz,wght@9..144,500;9..144,700&display=swap';
    $themeCss = function_exists('theme_css_vars') ? theme_css_vars($theme) : '';
    ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="<?= e($themeFontsHref) ?>" rel="stylesheet">
    <link rel="stylesheet" href="<?= e(url('assets/css/style.css')) ?>">
    <?php if (str_contains($pageClass, 'page-admin')): ?>
        <link rel="stylesheet" href="<?= e(url('assets/css/admin.css')) ?>">
    <?php endif; ?>
    <?php if ($themeCss !== '' && !str_contains($pageClass, 'page-admin')): ?>
        <style id="site-theme"><?= $themeCss ?></style>
    <?php endif; ?>
    <?php if ($protectAttr !== ''): ?>
    <script>
    (function () {
      var root = document.documentElement;
      var tokens = (root.getAttribute('data-protect') || '').split(/\s+/);
      var map = {};
      for (var i = 0; i < tokens.length; i++) {
        if (tokens[i]) map[tokens[i]] = true;
      }
      if (!Object.keys(map).length) return;
      var has = function (t) { return !!map[t]; };
      var allow = function (el) {
        if (!el || !el.closest) return false;
        return !!el.closest('input, textarea, select, [data-allow-copy], [contenteditable="true"]');
      };
      var stop = function (e) {
        e.preventDefault();
        e.stopPropagation();
        return false;
      };
      if (has('context')) {
        document.addEventListener('contextmenu', function (e) {
          if (!allow(e.target)) stop(e);
        }, true);
      }
      if (has('drag')) {
        document.addEventListener('dragstart', function (e) {
          var t = e.target;
          if (t && (t.tagName === 'IMG' || (t.closest && t.closest('img')))) stop(e);
        }, true);
      }
      if (has('copy')) {
        var blockClip = function (e) {
          if (!allow(e.target)) stop(e);
        };
        document.addEventListener('copy', blockClip, true);
        document.addEventListener('cut', blockClip, true);
      }
      if (has('keys') || has('copy')) {
        document.addEventListener('keydown', function (e) {
          if (allow(e.target)) return;
          var code = e.code || '';
          var key = (e.key || '').toLowerCase();
          var ctrl = e.ctrlKey || e.metaKey;
          // F12 — bazı tarayıcılar yine de açabilir
          if (has('keys') && (code === 'F12' || key === 'f12')) { stop(e); return; }
          if (has('keys') && ctrl && (code === 'KeyU' || key === 'u')) { stop(e); return; }
          if (has('keys') && ctrl && (code === 'KeyS' || key === 's')) { stop(e); return; }
          if (has('keys') && ctrl && (code === 'KeyP' || key === 'p')) { stop(e); return; }
          if (has('keys') && ctrl && e.shiftKey && (code === 'KeyI' || code === 'KeyJ' || code === 'KeyC' || key === 'i' || key === 'j' || key === 'c' || key === 'ı')) {
            stop(e);
            return;
          }
          if (has('copy') && ctrl && (code === 'KeyC' || code === 'KeyX' || code === 'KeyA' || key === 'c' || key === 'x' || key === 'a')) {
            stop(e);
          }
        }, true);
      }
    })();
    </script>
    <?php endif; ?>
</head>
<body class="<?= e($pageClass) ?>"<?= $protectAttr !== '' ? ' data-protect="' . e($protectAttr) . '"' : '' ?>>
<?php if (!$isAdminChrome): ?>
<header class="site-header">
    <div class="container header-inner">
        <a class="brand" href="<?= e(url('index.php')) ?>">
            <span class="brand-mark" aria-hidden="true"></span>
            <span class="brand-text">
                <strong><?= e($displayName) ?></strong>
                <small><?= e($displayTagline) ?></small>
            </span>
        </a>
        <nav class="nav">
            <a href="<?= e(url('index.php')) ?>"><?= e(function_exists('theme_t') ? theme_t('nav_home') : 'Vitrin') ?></a>
            <a href="<?= e(url('magaza.php')) ?>"><?= e(function_exists('theme_t') ? theme_t('nav_shop') : 'Mağaza') ?></a>
        </nav>
    </div>
</header>
<?php endif; ?>
<main class="site-main<?= $isAdminChrome ? ' site-main-admin' : '' ?>">
    <div class="<?= $isAdminChrome ? 'admin-container' : 'container' ?>">
        <?php if ($flash): ?>
            <div class="flash flash-<?= e($flash['type']) ?>"><?= e($flash['message']) ?></div>
        <?php endif; ?>
