-- System modules table — admin toggles for company module access
-- Run against your ERP database. Safe to re-run.

CREATE TABLE IF NOT EXISTS `system_modules` (
    `id`           TINYINT UNSIGNED    NOT NULL AUTO_INCREMENT,
    `module_key`   VARCHAR(50)         NOT NULL,
    `is_enabled`   TINYINT(1)          NOT NULL DEFAULT 1,
    `updated_by`   INT UNSIGNED        NULL,
    `updated_at`   DATETIME            NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_system_modules_key` (`module_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Seed all toggleable modules as enabled by default
INSERT INTO `system_modules` (`module_key`, `is_enabled`, `updated_at`)
SELECT 'hrm', 1, NOW() FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `system_modules` WHERE `module_key` = 'hrm');

INSERT INTO `system_modules` (`module_key`, `is_enabled`, `updated_at`)
SELECT 'sale', 1, NOW() FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `system_modules` WHERE `module_key` = 'sale');

INSERT INTO `system_modules` (`module_key`, `is_enabled`, `updated_at`)
SELECT 'contracts', 1, NOW() FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `system_modules` WHERE `module_key` = 'contracts');

INSERT INTO `system_modules` (`module_key`, `is_enabled`, `updated_at`)
SELECT 'procurement', 1, NOW() FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `system_modules` WHERE `module_key` = 'procurement');

INSERT INTO `system_modules` (`module_key`, `is_enabled`, `updated_at`)
SELECT 'inventory', 1, NOW() FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `system_modules` WHERE `module_key` = 'inventory');

INSERT INTO `system_modules` (`module_key`, `is_enabled`, `updated_at`)
SELECT 'accounting', 1, NOW() FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `system_modules` WHERE `module_key` = 'accounting');

INSERT INTO `system_modules` (`module_key`, `is_enabled`, `updated_at`)
SELECT 'operations', 1, NOW() FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `system_modules` WHERE `module_key` = 'operations');

INSERT INTO `system_modules` (`module_key`, `is_enabled`, `updated_at`)
SELECT 'transport', 1, NOW() FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `system_modules` WHERE `module_key` = 'transport');

INSERT INTO `system_modules` (`module_key`, `is_enabled`, `updated_at`)
SELECT 'reports', 1, NOW() FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `system_modules` WHERE `module_key` = 'reports');

INSERT INTO `system_modules` (`module_key`, `is_enabled`, `updated_at`)
SELECT 'messages', 1, NOW() FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `system_modules` WHERE `module_key` = 'messages');

-- Company security settings (TPIN policy)
-- Run: app/Database/sql/company_settings_security.sql
