<?php

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

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

        $stmt = $this->db->prepare("
            SELECT config
            FROM tracking_integrations
            WHERE provider = 'gtm'
              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['container_id'])) {
            return;
        }

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

        echo "<script>
        (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
        new Date().getTime(),event:'gtm.js'});
        var f=d.getElementsByTagName(s)[0],
        j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';
        j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;
        f.parentNode.insertBefore(j,f);
        })(window,document,'script','dataLayer','{$id}');
        </script>";
    }
}
