-- =====================================================================
-- Migração v6 — MULTIPIXEL (vários Meta e vários Google) + admin completo
-- =====================================================================

CREATE TABLE IF NOT EXISTS pixels (
  id         INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  type       ENUM('meta','google') NOT NULL,
  name       VARCHAR(120) NULL,           -- apelido para você identificar
  pixel_id   VARCHAR(64)  NOT NULL,       -- Meta Pixel ID  OU  Google AW-XXXXXXXXX
  token      VARCHAR(512) NULL,           -- Meta: CAPI Access Token
  label      VARCHAR(120) NULL,           -- Google: conversion label
  test_code  VARCHAR(64)  NULL,           -- Meta: test event code (opcional)
  active     TINYINT(1)   NOT NULL DEFAULT 1,
  created_at DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_type_active (type, active)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Migra o Meta já configurado nas settings (se houver) para a tabela
INSERT INTO pixels (type, name, pixel_id, token, test_code)
SELECT 'meta', 'Meta principal',
       s1.v,
       NULLIF((SELECT v FROM settings WHERE k='meta_capi_token'), ''),
       NULLIF((SELECT v FROM settings WHERE k='meta_test_event_code'), '')
FROM settings s1
WHERE s1.k = 'meta_pixel_id' AND s1.v <> ''
  AND NOT EXISTS (SELECT 1 FROM pixels WHERE type='meta' AND pixel_id = s1.v);

-- Migra o Google já configurado nas settings (se houver) para a tabela
INSERT INTO pixels (type, name, pixel_id, label)
SELECT 'google', 'Google Ads',
       s1.v,
       NULLIF((SELECT v FROM settings WHERE k='google_conversion_label'), '')
FROM settings s1
WHERE s1.k = 'google_ads_id' AND s1.v <> ''
  AND NOT EXISTS (SELECT 1 FROM pixels WHERE type='google' AND pixel_id = s1.v);
