-- Follow-up fix: use the existing label tables from your database:
-- customer_lable + customer_lable_customers
-- This migration does NOT create labels/entity_labels.

ALTER TABLE audience
  ADD COLUMN IF NOT EXISTS rules_json LONGTEXT NULL AFTER description;

ALTER TABLE campaign
  ADD COLUMN IF NOT EXISTS type_whatsapp TINYINT(1) NOT NULL DEFAULT 0 AFTER status,
  ADD COLUMN IF NOT EXISTS type_email TINYINT(1) NOT NULL DEFAULT 0 AFTER type_whatsapp,
  ADD COLUMN IF NOT EXISTS type_sms TINYINT(1) NOT NULL DEFAULT 0 AFTER type_email,
  ADD COLUMN IF NOT EXISTS target_type VARCHAR(30) NOT NULL DEFAULT 'audience' AFTER type_sms,
  ADD COLUMN IF NOT EXISTS audience_id INT NULL AFTER target_type,
  ADD COLUMN IF NOT EXISTS rules_json LONGTEXT NULL AFTER audience_id,
  ADD COLUMN IF NOT EXISTS message_whatsapp TEXT NULL AFTER rules_json,
  ADD COLUMN IF NOT EXISTS message_email TEXT NULL AFTER message_whatsapp,
  ADD COLUMN IF NOT EXISTS message_sms TEXT NULL AFTER message_email,
  ADD COLUMN IF NOT EXISTS email_subject VARCHAR(255) NULL AFTER message_sms;

CREATE TABLE IF NOT EXISTS campaign_logs (
  id INT AUTO_INCREMENT PRIMARY KEY,
  campaign_id INT NOT NULL,
  customer_id INT NOT NULL,
  type VARCHAR(30) NOT NULL,
  status VARCHAR(30) NOT NULL DEFAULT 'pending',
  response TEXT NULL,
  sent_at DATETIME NULL,
  date_created DATETIME DEFAULT CURRENT_TIMESTAMP,
  KEY idx_campaign (campaign_id),
  KEY idx_customer (customer_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- If old wrong tables labels/entity_labels were created by mistake, do not use them anymore.
-- The PHP code now reads from customer_lable and customer_lable_customers only.

INSERT INTO user_permissions (account_id, user_id, page_key, action_key, allowed, created_at)
SELECT u.account_id, u.id, p.page_key, a.action_key, 1, NOW()
FROM users u
CROSS JOIN (SELECT 'audience' page_key UNION ALL SELECT 'campaigns') p
CROSS JOIN (SELECT 'view' action_key UNION ALL SELECT 'add' UNION ALL SELECT 'edit' UNION ALL SELECT 'delete') a
WHERE NOT EXISTS (
  SELECT 1 FROM user_permissions up
  WHERE up.account_id=u.account_id AND up.user_id=u.id AND up.page_key=p.page_key AND up.action_key=a.action_key
);
