<?php
declare(strict_types=1);

// Output analytics code if enabled, using the already-loaded $pdo from calling scope
try {
    // $pdo is available in the include scope from the calling page
    $__pdo = isset($pdo) ? $pdo : (isset($GLOBALS['pdo']) ? $GLOBALS['pdo'] : null);
    if (!$__pdo) {
        $__pdo = require __DIR__ . '/../config/database.php';
    }

    // Check if settings table exists
    $__stmt = $__pdo->query("SELECT name FROM sqlite_master WHERE type='table' AND name='settings'");
    if (!$__stmt->fetch()) {
        return;
    }

    $__stmt = $__pdo->prepare("SELECT value FROM settings WHERE key = 'google_analytics_enabled'");
    $__stmt->execute();
    $__enabled = $__stmt->fetchColumn();
    if (!$__enabled) {
        return;
    }

    $__stmt = $__pdo->prepare("SELECT value FROM settings WHERE key = 'google_analytics_id'");
    $__stmt->execute();
    $__analyticsId = (string)$__stmt->fetchColumn();

    $__stmt = $__pdo->prepare("SELECT value FROM settings WHERE key = 'google_analytics_code'");
    $__stmt->execute();
    $__customCode = (string)$__stmt->fetchColumn();

    if (!empty($__customCode)) {
        echo "<!-- Custom Analytics -->\n" . $__customCode . "\n<!-- End Custom Analytics -->";
    } elseif (!empty($__analyticsId)) {
        $__id = htmlspecialchars($__analyticsId, ENT_QUOTES, 'UTF-8');
        echo "<!-- Google Analytics 4 -->
<script async src=\"https://www.googletagmanager.com/gtag/js?id={$__id}\"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', '{$__id}');
</script>
<!-- End Google Analytics -->";
    }
} catch (Throwable $e) {
    // Fail silently in production
}
