<?php
declare(strict_types=1);
require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/settings.php';

// Get Google Analytics settings
$pdo = require __DIR__ . '/../config/database.php';
$analyticsEnabled = get_setting($pdo, 'google_analytics_enabled', false);
$analyticsId = get_setting($pdo, 'google_analytics_id', '');
$analyticsCode = get_setting($pdo, 'google_analytics_code', '');

// Only output analytics code if enabled
if ($analyticsEnabled && (!empty($analyticsId) || !empty($analyticsCode))) {
    echo "<!-- Google Analytics -->\n";
    
    if (!empty($analyticsCode)) {
        // Custom analytics code
        echo $analyticsCode . "\n";
    } elseif (!empty($analyticsId)) {
        // Google Analytics 4
        ?>
        <!-- Google Analytics 4 -->
        <script async src="https://www.googletagmanager.com/gtag/js?id=<?=e($analyticsId)?>"></script>
        <script>
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());
          gtag('config', '<?=e($analyticsId)?>');
        </script>
        <?php
    }
    echo "<!-- End Google Analytics -->\n";
}
?>
