-- Granular permissions: sub-components within each module (e.g. individual reports, sales sub-pages).
-- Run after schema and seed_roles_permissions. Existing roles keep module-level access (e.g. "reports" grants all reports).
-- Assign granular permissions to roles to allow only specific sub-components when needed.
--
-- Your database: bgmxghks_averycrm

USE bgmxghks_averycrm;

-- Reports: each report is a sub-permission (reports.profit_loss = P&L page, etc.)
INSERT IGNORE INTO permissions (name, description) VALUES
('reports.profit_loss', 'Profit and Loss report'),
('reports.product_purchase', 'Product Purchase report'),
('reports.sales_rep', 'Sales Representative report'),
('reports.register', 'Register report'),
('reports.expense', 'Expense report'),
('reports.sell_payment', 'Sell Payment report'),
('reports.purchase_payment', 'Purchase Payment report'),
('reports.product_sell', 'Product Sell report'),
('reports.purchase_sale', 'Purchase & Sale report'),
('reports.trending_products', 'Trending Products report'),
('reports.stock_adjustment', 'Stock Adjustment report'),
('reports.stock', 'Stock report'),
('reports.supplier_customer', 'Supplier & Customer report'),
('reports.tax', 'Tax report'),
('reports.payroll_levies', 'Levies to Pay (NSSF, Housing, SHIF) report'),
('reports.activity_log', 'Activity Log report');

-- Sales: POS, list, add sale
INSERT IGNORE INTO permissions (name, description) VALUES
('sales.pos', 'Point of Sale'),
('sales.list', 'List sales / invoices'),
('sales.add', 'Add sale / create invoice');

-- User management: list, add, roles, audit log
INSERT IGNORE INTO permissions (name, description) VALUES
('users.list', 'View users list'),
('users.add', 'Add / edit users'),
('users.roles', 'Roles & permissions'),
('users.audit_log', 'Audit log');

-- Accounting: expenses, ledger, loans, liabilities, assets, financial statement
INSERT IGNORE INTO permissions (name, description) VALUES
('accounting.expenses', 'Expenses list and add'),
('accounting.expense_categories', 'Expense categories'),
('accounting.ledger', 'Payment accounts / ledger'),
('accounting.loans', 'Loans'),
('accounting.liabilities', 'Other liabilities'),
('accounting.assets', 'Assets'),
('accounting.asset_categories', 'Asset categories'),
('accounting.financial_statement', 'Financial statement');

-- Payroll
INSERT IGNORE INTO permissions (name, description) VALUES
('payroll.employees', 'Employees'),
('payroll.runs', 'Payroll runs and payslips');

-- Purchases
INSERT IGNORE INTO permissions (name, description) VALUES
('purchases.list', 'Purchases list and edit'),
('purchases.projection', 'Purchase projection');

-- Grant Admin all new permissions (any permission not yet in role_permissions for Admin)
INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id FROM roles r CROSS JOIN permissions p
WHERE r.name = 'Admin'
AND NOT EXISTS (SELECT 1 FROM role_permissions rp WHERE rp.role_id = r.id AND rp.permission_id = p.id);
