<?php
/**
 * MIS Permissions helper
 * Ensures MIS permissions exist and are granted to super_admin/hr_admin by default
 */

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

/**
 * Ensure MIS permissions exist and are seeded
 */
function ensureMisPermissions() {
    try {
        $db = getDB();

        $permissions = [
            ['MIS_VIEW', 'MIS View', 'mis', 'Can view MIS reports'],
            ['MIS_CREATE', 'MIS Create', 'mis', 'Can create MIS reports'],
            ['MIS_EDIT', 'MIS Edit', 'mis', 'Can edit MIS reports'],
            ['MIS_EXPORT', 'MIS Export', 'mis', 'Can export MIS reports'],
            ['MIS_ASSIGN', 'MIS Assign', 'mis', 'Can assign MIS permissions to roles'],
        ];

        // Insert permissions if not exist
        $stmtSelectPerm = $db->prepare("SELECT permission_id FROM permissions WHERE permission_code = ?");
        $stmtInsertPerm = $db->prepare("
            INSERT INTO permissions (permission_code, permission_name, permission_module, permission_description)
            VALUES (?, ?, ?, ?)
        ");

        foreach ($permissions as $perm) {
            [$code, $name, $module, $desc] = $perm;
            $stmtSelectPerm->execute([$code]);
            if (!$stmtSelectPerm->fetch()) {
                $stmtInsertPerm->execute([$code, $name, $module, $desc]);
            }
        }

        // Grant to super_admin and hr_admin by default
        $roleStmt = $db->prepare("SELECT role_id, role_code FROM roles WHERE role_code IN ('super_admin', 'hr_admin')");
        $roleStmt->execute();
        $roles = $roleStmt->fetchAll();

        $permIdStmt = $db->prepare("SELECT permission_id FROM permissions WHERE permission_code = ?");
        $insertRolePerm = $db->prepare("
            INSERT IGNORE INTO role_permissions (role_id, permission_id)
            VALUES (?, ?)
        ");

        foreach ($roles as $role) {
            foreach ($permissions as $perm) {
                $permIdStmt->execute([$perm[0]]);
                $permId = $permIdStmt->fetchColumn();
                if ($permId) {
                    $insertRolePerm->execute([$role['role_id'], $permId]);
                }
            }
        }
    } catch (Exception $e) {
        error_log("ensureMisPermissions error: " . $e->getMessage());
    }
}

