<?php
/**
 * Enterprise HRM ERP System - Role Management
 * Create custom roles and assign permissions
 */

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/check_admin_access.php';

// Check if user is Super Admin - with better error handling
startSession();

// Force refresh role_code from database
$roleCode = $_SESSION['role_code'] ?? '';
if (empty($roleCode) && isset($_SESSION['user_id'])) {
    try {
        $db = getDB();
        $stmt = $db->prepare("
            SELECT r.role_code 
            FROM users u
            INNER JOIN roles r ON u.role_id = r.role_id
            WHERE u.user_id = ?
        ");
        $stmt->execute([$_SESSION['user_id']]);
        $userRole = $stmt->fetch();
        if ($userRole && !empty($userRole['role_code'])) {
            $roleCode = $userRole['role_code'];
            $_SESSION['role_code'] = $roleCode;
        }
    } catch (Exception $e) {
        error_log("Error loading role_code: " . $e->getMessage());
    }
}

// Check if Super Admin (case-insensitive)
if (strtolower($roleCode) !== 'super_admin') {
    $_SESSION['error'] = 'Only Super Admin can manage roles. Your role: ' . ($roleCode ?: 'Unknown');
    header('Location: ' . BASE_URL . '/dashboard.php');
    exit;
}

$pageTitle = 'Role Management';
$currentModule = 'settings';

$errors = [];
$success = false;

// Get all roles
try {
    $db = getDB();
    $stmt = $db->prepare("
        SELECT r.*, COUNT(DISTINCT u.user_id) as user_count
        FROM roles r
        LEFT JOIN users u ON r.role_id = u.role_id
        GROUP BY r.role_id
        ORDER BY r.is_system_role DESC, r.role_name
    ");
    $stmt->execute();
    $roles = $stmt->fetchAll();
    
    // Get all permissions
    $stmt = $db->prepare("
        SELECT permission_id, permission_code, permission_name, permission_module
        FROM permissions
        ORDER BY permission_module, permission_name
    ");
    $stmt->execute();
    $allPermissions = $stmt->fetchAll();
    
    // Group permissions by module
    $permissionsByModule = [];
    foreach ($allPermissions as $perm) {
        $module = $perm['permission_module'];
        if (!isset($permissionsByModule[$module])) {
            $permissionsByModule[$module] = [];
        }
        $permissionsByModule[$module][] = $perm;
    }
    
} catch (Exception $e) {
    error_log("Roles error: " . $e->getMessage());
    $roles = [];
    $permissionsByModule = [];
}

include __DIR__ . '/../includes/header.php';
?>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Role Management</h2>
        <div style="display: flex; gap: 10px;">
            <a href="<?php echo BASE_URL; ?>/modules/settings/index.php" class="btn btn-secondary">Back to Settings</a>
            <a href="<?php echo BASE_URL; ?>/admin/role_management_dashboard.php" class="btn btn-primary">Dashboard</a>
            <a href="<?php echo BASE_URL; ?>/admin/permissions.php" class="btn btn-secondary">Permission Setup</a>
            <a href="<?php echo BASE_URL; ?>/admin/seed_all_modules_permissions.php" class="btn btn-primary">Seed All Permissions</a>
            <a href="<?php echo BASE_URL; ?>/admin/roles_create.php" class="btn btn-primary">Add Role</a>
            <a href="<?php echo BASE_URL; ?>/admin/roles_edit.php" class="btn btn-secondary">Role Editor</a>
            <a href="<?php echo BASE_URL; ?>/admin/user_access_role.php" class="btn btn-secondary">User Access Role</a>
        </div>
    </div>
    
    <?php 
    // Get flash messages
    $success = getFlashMessage('success');
    $error = getFlashMessage('error');
    ?>
    
    <?php if ($success): ?>
    <div class="alert alert-success" style="margin-top: 20px;">
        <?php echo htmlspecialchars($success); ?>
    </div>
    <?php endif; ?>
    
    <?php if ($error): ?>
    <div class="alert alert-error" style="margin-top: 20px;">
        <?php echo htmlspecialchars($error); ?>
    </div>
    <?php endif; ?>
    
    <div style="margin-top: 20px;">
        <h3 style="margin-bottom: 15px;">System Roles (Cannot be deleted)</h3>
        <table class="data-table">
            <thead>
                <tr>
                    <th>Role Code</th>
                    <th>Role Name</th>
                    <th>Description</th>
                    <th>Users</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($roles as $role): ?>
                <?php if ($role['is_system_role']): ?>
                <tr>
                    <td><strong><?php echo htmlspecialchars($role['role_code']); ?></strong></td>
                    <td><?php echo htmlspecialchars($role['role_name']); ?></td>
                    <td><?php echo htmlspecialchars($role['role_description'] ?? 'N/A'); ?></td>
                    <td><?php echo number_format($role['user_count']); ?></td>
                    <td class="table-actions-cell">
                        <a href="<?php echo BASE_URL; ?>/admin/roles_view.php?id=<?php echo $role['role_id']; ?>" 
                           class="btn btn-sm btn-primary">View Permissions</a>
                    </td>
                </tr>
                <?php endif; ?>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    
    <div style="margin-top: 30px;">
        <h3 style="margin-bottom: 15px;">Custom Roles</h3>
        <?php 
        $customRoles = array_filter($roles, function($r) { return !$r['is_system_role']; });
        if (count($customRoles) > 0): 
        ?>
        <table class="data-table">
            <thead>
                <tr>
                    <th>Role Code</th>
                    <th>Role Name</th>
                    <th>Description</th>
                    <th>Users</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($customRoles as $role): ?>
                <tr>
                    <td><strong><?php echo htmlspecialchars($role['role_code']); ?></strong></td>
                    <td><?php echo htmlspecialchars($role['role_name']); ?></td>
                    <td><?php echo htmlspecialchars($role['role_description'] ?? 'N/A'); ?></td>
                    <td><?php echo number_format($role['user_count']); ?></td>
                    <td class="table-actions-cell">
                        <a href="<?php echo BASE_URL; ?>/admin/roles_view.php?id=<?php echo $role['role_id']; ?>" 
                           class="btn btn-sm btn-primary">View</a>
                        <a href="<?php echo BASE_URL; ?>/admin/roles_edit_detail.php?id=<?php echo $role['role_id']; ?>" 
                           class="btn btn-sm btn-secondary">Role Editor</a>
                        <?php if ($role['user_count'] == 0): ?>
                        <a href="<?php echo BASE_URL; ?>/admin/roles_delete.php?id=<?php echo $role['role_id']; ?>" 
                           class="btn btn-sm btn-danger"
                           onclick="return confirm('Are you sure you want to delete this role?');">Delete</a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php else: ?>
        <div class="table-empty">
            <div class="table-empty-icon">👥</div>
            <div class="table-empty-message">No custom roles found</div>
            <div class="table-empty-submessage">
                <a href="<?php echo BASE_URL; ?>/admin/roles_create.php" class="btn btn-primary">Create First Custom Role</a>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>

