-- 087_addon_offset_nota_permission_packages.sql
-- Paket permission aktif untuk Add On Offset dan Add On Nota NCR

INSERT INTO permissions (code, name, module, created_at)
SELECT 'addon.offset.master.manage', 'Manage Pengaturan Offset', 'addon_offset', NOW()
WHERE NOT EXISTS (
  SELECT 1 FROM permissions WHERE code = 'addon.offset.master.manage'
);

INSERT INTO permissions (code, name, module, created_at)
SELECT 'addon.offset.manage', 'Manage Hitungan Offset', 'addon_offset', NOW()
WHERE NOT EXISTS (
  SELECT 1 FROM permissions WHERE code = 'addon.offset.manage'
);

INSERT INTO permissions (code, name, module, created_at)
SELECT 'addon.nota.master.manage', 'Manage Master Nota NCR', 'addon_nota', NOW()
WHERE NOT EXISTS (
  SELECT 1 FROM permissions WHERE code = 'addon.nota.master.manage'
);

UPDATE permissions
SET name = 'Manage Pengaturan Offset',
    module = 'addon_offset'
WHERE code = 'addon.offset.master.manage';

UPDATE permissions
SET name = 'Manage Hitungan Offset',
    module = 'addon_offset'
WHERE code = 'addon.offset.manage';

UPDATE permissions
SET name = 'Manage Master Nota NCR',
    module = 'addon_nota'
WHERE code = 'addon.nota.master.manage';

INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT DISTINCT rp.role_id, p_manage.id
FROM role_permissions rp
JOIN permissions p_old ON p_old.id = rp.permission_id
JOIN permissions p_manage ON p_manage.code = 'addon.offset.master.manage'
WHERE p_old.code IN ('addon.offset.master.view', 'addon.offset.master.edit', 'addon.offset.delete');

INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT DISTINCT rp.role_id, p_manage.id
FROM role_permissions rp
JOIN permissions p_old ON p_old.id = rp.permission_id
JOIN permissions p_manage ON p_manage.code = 'addon.offset.manage'
WHERE p_old.code IN ('addon.offset.view', 'addon.offset.add');

INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT DISTINCT rp.role_id, p_manage.id
FROM role_permissions rp
JOIN permissions p_old ON p_old.id = rp.permission_id
JOIN permissions p_manage ON p_manage.code = 'addon.nota.master.manage'
WHERE p_old.code IN ('addon.nota.master.view', 'addon.nota.master.edit', 'addon.nota.delete');
