<?php

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

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

        $stmt = $this->db->prepare("
            SELECT config
            FROM tracking_integrations
            WHERE provider = 'facebook_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(f,b,e,v,n,t,s)
        {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
        n.callMethod.apply(n,arguments):n.queue.push(arguments)};
        if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
        n.queue=[];t=b.createElement(e);t.async=!0;
        t.src=v;s=b.getElementsByTagName(e)[0];
        s.parentNode.insertBefore(t,s)}(window, document,'script',
        'https://connect.facebook.net/en_US/fbevents.js');
        fbq('init','{$id}');
        fbq('track','PageView');
        </script>";
    }

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