<?php
/**
 * Seed MIS permissions and assign to default roles (super_admin, hr_admin)
 */

if (!defined('HRM_ACCESS')) {
    die('Direct access not allowed');
}

function ensureMisPermissions() {
    try {
        $db = getDB();

        // Permission codes
        $perms = [
            ['MIS_VIEW', 'MIS - View', 'mis'],
            ['MIS_CREATE', 'MIS - Create', 'mis'],
            ['MIS_EDIT', 'MIS - Edit', 'mis'],
            ['MIS_EXPORT', 'MIS - Export', 'mis'],
        ];

        // Insert permissions if missing
        $stmt = $db->prepare("
            INSERT IGNORE INTO permissions (permission_code, permission_name, permission_module)
            VALUES (?, ?, ?)
        ");
        foreach ($perms as $p) {
            $stmt->execute($p);
        }

        // Fetch role_ids for super_admin and hr_admin
        $roleStmt = $db->prepare("SELECT role_id, role_code FROM roles WHERE role_code IN ('super_admin', 'hr_admin')");
        $roleStmt->execute();
        $roles = $roleStmt->fetchAll(PDO::FETCH_ASSOC);
        if (!$roles) {
            return;
        }

        // Map permission_id by code
        $permIdsStmt = $db->prepare("SELECT permission_id, permission_code FROM permissions WHERE permission_code IN ('MIS_VIEW','MIS_CREATE','MIS_EDIT','MIS_EXPORT')");
        $permIdsStmt->execute();
        $permIds = [];
        foreach ($permIdsStmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
            $permIds[$row['permission_code']] = $row['permission_id'];
        }

        // Assign permissions to roles (INSERT IGNORE)
        $assignStmt = $db->prepare("
            INSERT IGNORE INTO role_permissions (role_id, permission_id)
            VALUES (?, ?)
        ");
        foreach ($roles as $role) {
            foreach ($permIds as $pid) {
                $assignStmt->execute([$role['role_id'], $pid]);
            }
        }
    } catch (Exception $e) {
        error_log("ensureMisPermissions error: " . $e->getMessage());
    }
}


