-- 113_calendar_reminder_feature_matrix.sql
-- Tambahkan canonical feature calendar.reminder dan permission eksplisit reminder.

INSERT INTO platform_features (code, name, domain, description, is_active, sort_order)
SELECT
  'calendar.reminder',
  'Kalender Reminder',
  'operations',
  'Kalender reminder operasional dengan opsi pencatatan pengeluaran saat selesai.',
  1,
  173
WHERE NOT EXISTS (
  SELECT 1
  FROM platform_features
  WHERE code = 'calendar.reminder'
);

UPDATE platform_features
SET
  name = 'Kalender Reminder',
  domain = 'operations',
  description = 'Kalender reminder operasional dengan opsi pencatatan pengeluaran saat selesai.',
  is_active = 1,
  sort_order = 173
WHERE code = 'calendar.reminder';

INSERT INTO platform_plan_features (platform_plan_id, platform_feature_id, is_enabled)
SELECT pp.id, pf.id, 1
FROM platform_plans pp
INNER JOIN platform_features pf ON pf.code = 'calendar.reminder'
WHERE pp.code IN ('operations', 'management', 'intelligence')
  AND NOT EXISTS (
    SELECT 1
    FROM platform_plan_features ppf
    WHERE ppf.platform_plan_id = pp.id
      AND ppf.platform_feature_id = pf.id
  );

INSERT INTO platform_plan_features (platform_plan_id, platform_feature_id, is_enabled)
SELECT pp.id, pf.id, 0
FROM platform_plans pp
INNER JOIN platform_features pf ON pf.code = 'calendar.reminder'
WHERE pp.code = 'starter'
  AND NOT EXISTS (
    SELECT 1
    FROM platform_plan_features ppf
    WHERE ppf.platform_plan_id = pp.id
      AND ppf.platform_feature_id = pf.id
  );

UPDATE platform_plan_features ppf
INNER JOIN platform_plans pp ON pp.id = ppf.platform_plan_id
INNER JOIN platform_features pf ON pf.id = ppf.platform_feature_id
SET ppf.is_enabled = CASE
  WHEN pp.code IN ('operations', 'management', 'intelligence') THEN 1
  ELSE 0
END
WHERE pf.code = 'calendar.reminder';

INSERT IGNORE INTO permissions (code, name, module, created_at) VALUES
('reminder.view', 'Lihat Kalender Reminder', 'reminder', NOW()),
('reminder.manage', 'Kelola Kalender Reminder', 'reminder', NOW()),
('reminder.complete', 'Selesaikan Reminder', 'reminder', NOW());

INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT DISTINCT rp.role_id, target.id
FROM role_permissions rp
INNER JOIN permissions source ON source.id = rp.permission_id
INNER JOIN permissions target ON target.code = 'reminder.view'
WHERE source.code IN ('reports.view', 'reports.summary.view');
