<?php


class Ga4TrackingService
{
    protected PDO $db;
    protected array $config = [];

    public function __construct()
    {
        $this->db = db();

        $stmt = $this->db->prepare("
            SELECT config
            FROM tracking_integrations
            WHERE provider = 'ga4'
              AND is_active = 1
            LIMIT 1
        ");
        $stmt->execute();

        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$row) {
            return;
        }

        $this->config = json_decode($row['config'], true) ?: [];
    }

    public function inject(): void
    {
        if (empty($this->config['measurement_id'])) {
            return;
        }

        $id = htmlspecialchars($this->config['measurement_id'], ENT_QUOTES, 'UTF-8');

        echo "<script async src=\"https://www.googletagmanager.com/gtag/js?id={$id}\"></script>";
        echo "<script>
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '{$id}');
        </script>";
    }

    public function event(string $name, array $params = []): void
    {
        $json = json_encode($params, JSON_UNESCAPED_UNICODE);
        echo "<script>gtag('event', '{$name}', {$json});</script>";
    }
}