<?php

namespace Core\App\Models;

use PDO;

class TikTokPixelSettingModel
{
    protected PDO $db;

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

    public function get(): array
    {
        $stmt = $this->db->prepare("
            SELECT is_active, config
            FROM tracking_integrations
            WHERE provider = 'tiktok_pixel'
            LIMIT 1
        ");
        $stmt->execute();

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

        $config = json_decode($row['config'], true) ?: [];

        return array_merge($config, [
            'is_active' => (int)$row['is_active']
        ]);
    }

    public function save(array $config, int $isActive): void
    {
        $stmt = $this->db->prepare("
            UPDATE tracking_integrations
            SET config = :config, is_active = :active
            WHERE provider = 'tiktok_pixel'
        ");

        $stmt->execute([
            ':config' => json_encode($config, JSON_UNESCAPED_UNICODE),
            ':active' => $isActive,
        ]);
    }
}
