-- Migration: Add HR Admin Permissions for Role Assignment and Attendance
-- This allows HR Admin to assign roles to employees and manage attendance

-- Add USER_ROLE_ASSIGN permission if not exists
INSERT INTO `permissions` (`permission_code`, `permission_name`, `permission_module`, `permission_description`)
SELECT 'USER_ROLE_ASSIGN', 'Assign Roles to Users', 'user', 'Allow assigning roles to users/employees'
WHERE NOT EXISTS (
    SELECT 1 FROM `permissions` WHERE `permission_code` = 'USER_ROLE_ASSIGN'
);

-- Add ATTENDANCE_REPORT permission if not exists
INSERT INTO `permissions` (`permission_code`, `permission_name`, `permission_module`, `permission_description`)
SELECT 'ATTENDANCE_REPORT', 'Generate Attendance Reports', 'attendance', 'Allow generating attendance reports'
WHERE NOT EXISTS (
    SELECT 1 FROM `permissions` WHERE `permission_code` = 'ATTENDANCE_REPORT'
);

-- Get permission IDs
SET @user_role_assign_id = (SELECT permission_id FROM permissions WHERE permission_code = 'USER_ROLE_ASSIGN');
SET @attendance_report_id = (SELECT permission_id FROM permissions WHERE permission_code = 'ATTENDANCE_REPORT');

-- Assign USER_ROLE_ASSIGN to HR Admin (role_id = 2) if not already assigned
INSERT INTO `role_permissions` (`role_id`, `permission_id`)
SELECT 2, @user_role_assign_id
WHERE NOT EXISTS (
    SELECT 1 FROM `role_permissions` 
    WHERE `role_id` = 2 AND `permission_id` = @user_role_assign_id
);

-- Assign ATTENDANCE_REPORT to HR Admin (role_id = 2) if not already assigned
INSERT INTO `role_permissions` (`role_id`, `permission_id`)
SELECT 2, @attendance_report_id
WHERE NOT EXISTS (
    SELECT 1 FROM `role_permissions` 
    WHERE `role_id` = 2 AND `permission_id` = @attendance_report_id
);

