<?php

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

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

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

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

        echo "<script>
        !function(w,d,t){
          w.TiktokAnalyticsObject=t;
          var ttq=w[t]=w[t]||[];
          ttq.methods=['page','track','identify','instances','debug','on','off','once','ready','alias','group','enableCookie','disableCookie'];
          ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};
          for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);
          ttq.load=function(e){
            var i='https://analytics.tiktok.com/i18n/pixel/events.js';
            ttq._i=ttq._i||{};
            ttq._i[e]=[];
            var o=d.createElement('script');
            o.async=!0;o.src=i+'?sdkid='+e+'&lib='+t;
            var a=d.getElementsByTagName('script')[0];
            a.parentNode.insertBefore(o,a)
          };
          ttq.load('{$id}');
          ttq.page();
        }(window,document,'ttq');
        </script>";
    }

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