<?php
session_start();
include_once('includes/config.php');
include_once('includes/quick-menu.php');
if (!isset($_SESSION['uid'])) {
    header('location:logout.php');
    exit();
}

// Only admin can access role management
if ($_SESSION['usertype'] != 'admin') {
    header('location:dashboard.php');
    exit();
}

$currentUserId = $_SESSION['uid'];

// Handle role form submissions
if ($_POST) {
    $action = $_POST['action'];
    $roleName = mysqli_real_escape_string($con, $_POST['roleName']);
    $roleCode = mysqli_real_escape_string($con, strtolower(str_replace(' ', '_', $_POST['roleCode'])));
    $description = mysqli_real_escape_string($con, $_POST['description']);
    $status = mysqli_real_escape_string($con, $_POST['status']);
    $permissions = isset($_POST['permissions']) ? $_POST['permissions'] : [];
    
    if ($action == 'create') {
        // Check if role code already exists
        $checkQuery = "SELECT ID FROM tblroles WHERE RoleCode = '$roleCode'";
        $checkResult = mysqli_query($con, $checkQuery);
        
        if (mysqli_num_rows($checkResult) > 0) {
            $error = "Role code already exists!";
        } else {
            $insertQuery = "INSERT INTO tblroles (RoleName, RoleCode, Description, Status, CreatedBy, CreatedDate) 
                           VALUES ('$roleName', '$roleCode', '$description', '$status', $currentUserId, NOW())";
            
            if (mysqli_query($con, $insertQuery)) {
                $roleId = mysqli_insert_id($con);
                
                // Insert permissions
                foreach ($permissions as $permissionId) {
                    $permId = (int)$permissionId;
                    $permQuery = "INSERT INTO tblrolepermissions (RoleID, PermissionID) VALUES ($roleId, $permId)";
                    mysqli_query($con, $permQuery);
                }
                
                $success = "Role created successfully!";
            } else {
                $error = "Error creating role: " . mysqli_error($con);
            }
        }
    } elseif ($action == 'update') {
        $roleId = (int)$_POST['roleId'];
        
        if ($roleId <= 0) {
            $error = "Invalid role ID for update.";
        } else {
            // Check if role code already exists for other roles
            $checkQuery = "SELECT ID FROM tblroles WHERE RoleCode = '$roleCode' AND ID != $roleId";
            $checkResult = mysqli_query($con, $checkQuery);
            
            if (mysqli_num_rows($checkResult) > 0) {
                $error = "Role code already exists!";
            } else {
                $updateQuery = "UPDATE tblroles SET 
                               RoleName = '$roleName',
                               RoleCode = '$roleCode',
                               Description = '$description',
                               Status = '$status',
                               UpdatedBy = $currentUserId,
                               UpdatedDate = NOW()
                               WHERE ID = $roleId";
                
                if (mysqli_query($con, $updateQuery)) {
                    // Delete existing permissions
                    mysqli_query($con, "DELETE FROM tblrolepermissions WHERE RoleID = $roleId");
                    
                    // Insert new permissions
                    foreach ($permissions as $permissionId) {
                        $permId = (int)$permissionId;
                        $permQuery = "INSERT INTO tblrolepermissions (RoleID, PermissionID) VALUES ($roleId, $permId)";
                        mysqli_query($con, $permQuery);
                    }
                    
                    $success = "Role updated successfully!";
                } else {
                    $error = "Error updating role: " . mysqli_error($con);
                }
            }
        }
    }
}

// Handle delete action
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $roleId = (int)$_GET['delete'];
    
    // Check if role is assigned to any users
    $checkUsersQuery = "SELECT COUNT(*) as user_count FROM tblusers WHERE RoleID = $roleId";
    $checkUsersResult = mysqli_query($con, $checkUsersQuery);
    $userCount = mysqli_fetch_assoc($checkUsersResult)['user_count'];
    
    if ($userCount > 0) {
        $error = "Cannot delete role! It is assigned to $userCount user(s). Please reassign users first.";
    } else {
        $deleteQuery = "DELETE FROM tblroles WHERE ID = $roleId";
        
        if (mysqli_query($con, $deleteQuery)) {
            $success = "Role deleted successfully!";
        } else {
            $error = "Error deleting role: " . mysqli_error($con);
        }
    }
}

// Get all roles with permission and user counts
$rolesQuery = "SELECT r.*, 
               COUNT(DISTINCT rp.PermissionID) as permission_count,
               COUNT(DISTINCT u.ID) as user_count
               FROM tblroles r
               LEFT JOIN tblrolepermissions rp ON r.ID = rp.RoleID
               LEFT JOIN tblusers u ON r.ID = u.RoleID
               GROUP BY r.ID
               ORDER BY r.CreatedDate DESC";
$rolesResult = mysqli_query($con, $rolesQuery);

$roles = [];
$roleStats = ['total' => 0, 'active' => 0, 'inactive' => 0];

if ($rolesResult) {
    while ($role = mysqli_fetch_assoc($rolesResult)) {
        $roles[] = $role;
    }
    
    // Calculate statistics
    foreach ($roles as $role) {
        $roleStats['total']++;
        if ($role['Status'] == 'Active') {
            $roleStats['active']++;
        } else {
            $roleStats['inactive']++;
        }
    }
}

// Get all permissions grouped by category
$permissionsQuery = "SELECT * FROM tblpermissions ORDER BY Category, PermissionName";
$permissionsResult = mysqli_query($con, $permissionsQuery);
$permissionsByCategory = [];

if ($permissionsResult) {
    while ($perm = mysqli_fetch_assoc($permissionsResult)) {
        $category = $perm['Category'] ?: 'Other';
        if (!isset($permissionsByCategory[$category])) {
            $permissionsByCategory[$category] = [];
        }
        $permissionsByCategory[$category][] = $perm;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>HNF Resorts | Role Management</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    <link href="css/modern-messagebox.css" rel="stylesheet">
    <?php renderQuickMenuCSS(); ?>
    <style>
        /* Full-height layout */
        html, body, #wrapper, #content-wrapper, #content {
            height: 100%;
        }

        /* Compact global paddings */
        .container-fluid {
            padding: 8px 10px;
        }

        .role-card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.1);
            transition: all 0.2s ease;
            border: 1px solid #e8e8e8;
            margin-bottom: 8px;
            overflow: hidden;
        }
        
        .role-card:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        .role-card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 8px 10px;
            position: relative;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .role-card-header.inactive {
            background: linear-gradient(135deg, #6c757d 0%, #5a6268 100%);
        }
        
        .role-avatar {
            width: 32px;
            height: 32px;
            background: rgba(255,255,255,0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.9rem;
            border: 1px solid rgba(255,255,255,0.3);
            flex-shrink: 0;
        }
        
        .role-header-info {
            flex: 1;
            min-width: 0;
        }
        
        .role-name {
            font-size: 0.9rem;
            font-weight: 600;
            margin-bottom: 2px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .role-status-badge {
            background: rgba(255,255,255,0.2);
            padding: 1px 6px;
            border-radius: 10px;
            font-size: 0.65rem;
            display: inline-block;
        }
        
        .role-card-body {
            padding: 8px 10px;
        }
        
        .role-info {
            margin-bottom: 6px;
        }
        
        .info-item {
            display: flex;
            align-items: center;
            margin-bottom: 4px;
            font-size: 0.78rem;
        }
        
        .info-item i {
            width: 14px;
            color: #6c757d;
            margin-right: 8px;
            font-size: 0.75rem;
        }
        
        .info-item .value {
            color: #495057;
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .role-actions {
            border-top: 1px solid #f0f0f0;
            padding: 6px 8px;
            background: #fafafa;
            display: flex;
            gap: 6px;
        }
        
        .edit-btn {
            background: linear-gradient(135deg, #ffc107 0%, #e0a800 100%);
            color: white;
            border: none;
            border-radius: 6px;
            padding: 6px 10px;
            font-weight: 600;
            font-size: 0.78rem;
            transition: all 0.2s ease;
            flex: 1;
            text-decoration: none;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            cursor: pointer;
        }
        
        .edit-btn:hover {
            filter: brightness(0.95);
            color: white;
            text-decoration: none;
            transform: translateY(-1px);
        }
        
        .delete-btn {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            color: white;
            border: none;
            border-radius: 6px;
            padding: 6px 8px;
            font-size: 0.78rem;
            transition: all 0.2s ease;
            text-decoration: none;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }
        
        .delete-btn:hover {
            filter: brightness(0.95);
            color: white;
            text-decoration: none;
            transform: translateY(-1px);
        }
        
        .search-box {
            background: white;
            border-radius: 8px;
            padding: 8px 10px;
            margin-bottom: 10px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.1);
        }
        
        .search-input {
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            padding: 6px 30px 6px 10px;
            font-size: 0.85rem;
            transition: all 0.2s ease;
        }
        
        .search-input:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 2px rgba(102,126,234,0.25);
        }
        
        .search-icon {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
            font-size: 0.85rem;
        }
        
        /* Tighter grid gutters */
        #rolesGrid {
            margin-left: -6px;
            margin-right: -6px;
        }
        #rolesGrid > .col-6 {
            padding-left: 6px;
            padding-right: 6px;
        }

        /* Modal enhancements */
        .modal-content {
            border-radius: 8px;
            border: none;
            box-shadow: 0 8px 25px rgba(0,0,0,0.2);
        }
        
        .modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 8px 8px 0 0;
            padding: 12px 16px;
        }
        
        .modal-title {
            font-weight: 600;
            font-size: 1rem;
        }
        
        .form-control {
            border-radius: 4px;
            border: 1px solid #e9ecef;
            padding: 8px 12px;
            font-size: 0.9rem;
            transition: all 0.3s ease;
        }
        
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 2px rgba(102,126,234,0.1);
        }

        /* Permissions section */
        .permissions-section {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            padding: 10px;
            background: #f8f9fa;
        }

        .permission-category {
            margin-bottom: 12px;
        }

        .category-title {
            font-weight: 600;
            font-size: 0.85rem;
            color: #667eea;
            margin-bottom: 6px;
            padding: 4px 8px;
            background: white;
            border-radius: 4px;
            border-left: 3px solid #667eea;
        }

        .permission-item {
            display: flex;
            align-items: center;
            padding: 4px 8px;
            margin-bottom: 3px;
        }

        .permission-item input[type="checkbox"] {
            margin-right: 8px;
        }

        .permission-item label {
            margin-bottom: 0;
            font-size: 0.8rem;
            cursor: pointer;
        }

        .permission-count {
            background: #667eea;
            color: white;
            padding: 2px 6px;
            border-radius: 10px;
            font-size: 0.7rem;
            margin-left: 6px;
        }

        @media (max-width: 768px) {
            .role-card-body {
                padding: 6px 8px;
            }
            
            .role-actions {
                padding: 4px 6px;
                gap: 4px;
            }
            
            .edit-btn {
                padding: 4px 8px;
                font-size: 0.7rem;
            }
            
            .delete-btn {
                padding: 4px 6px;
                font-size: 0.7rem;
            }
            
            .role-name {
                font-size: 0.85rem;
            }
            
            .info-item {
                font-size: 0.75rem;
                margin-bottom: 2px;
            }

            .permissions-section {
                max-height: 200px;
            }
        }
    </style>
</head>
<body id="page-top">
    <div id="wrapper">
        <?php include_once('includes/sidebar.php');?>
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <?php include_once('includes/topbar.php');?>
                
                <!-- Begin Page Content -->
                <div class="container-fluid">
                    
                    <!-- Alert Messages -->
                    <?php if (isset($success)): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle mr-2"></i><?php echo $success; ?>
                        <button type="button" class="close" data-dismiss="alert">
                            <span>&times;</span>
                        </button>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (isset($error)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-circle mr-2"></i><?php echo $error; ?>
                        <button type="button" class="close" data-dismiss="alert">
                            <span>&times;</span>
                        </button>
                    </div>
                    <?php endif; ?>

                    <?php renderQuickMenu("Role Management", "Manage roles and permissions"); ?>
                    
                    <div class="d-flex justify-content-end mb-3">
                        <button class="btn btn-light btn-sm" onclick="openRoleModal()">
                            <i class="fas fa-plus mr-1"></i>Add Role
                        </button>
                    </div>

                    <!-- Role Statistics -->
                    <div class="row mb-3">
                        <div class="col-4">
                            <div class="text-center">
                                <div class="h5 mb-0 text-primary"><?php echo $roleStats['total']; ?></div>
                                <small class="text-muted">Total Roles</small>
                            </div>
                        </div>
                        <div class="col-4">
                            <div class="text-center">
                                <div class="h5 mb-0 text-success"><?php echo $roleStats['active']; ?></div>
                                <small class="text-muted">Active</small>
                            </div>
                        </div>
                        <div class="col-4">
                            <div class="text-center">
                                <div class="h5 mb-0 text-secondary"><?php echo $roleStats['inactive']; ?></div>
                                <small class="text-muted">Inactive</small>
                            </div>
                        </div>
                    </div>

                    <!-- Search Box -->
                    <div class="search-box">
                        <div class="position-relative">
                            <input type="text" class="form-control search-input" id="roleSearch" placeholder="Search roles...">
                            <i class="fas fa-search search-icon"></i>
                        </div>
                    </div>

                    <!-- Filter Buttons -->
                    <div class="mb-3">
                        <div class="btn-group btn-group-sm w-100">
                            <button class="btn btn-outline-primary active" onclick="filterRoles('all')">All</button>
                            <button class="btn btn-outline-success" onclick="filterRoles('active')">Active</button>
                            <button class="btn btn-outline-secondary" onclick="filterRoles('inactive')">Inactive</button>
                        </div>
                    </div>

                    <!-- Roles Grid -->
                    <div class="row" id="rolesGrid">
                        <?php foreach($roles as $role): ?>
                        <div class="col-6 role-item" data-status="<?php echo strtolower($role['Status']); ?>">
                            <div class="role-card">
                                <div class="role-card-header <?php echo strtolower($role['Status']); ?>">
                                    <div class="role-avatar">
                                        <i class="fas fa-shield-alt"></i>
                                    </div>
                                    <div class="role-header-info">
                                        <div class="role-name"><?php echo htmlspecialchars($role['RoleName']); ?></div>
                                        <div class="role-status-badge"><?php echo ucfirst($role['Status']); ?></div>
                                    </div>
                                </div>
                                <div class="role-card-body">
                                    <div class="role-info">
                                        <div class="info-item">
                                            <i class="fas fa-code"></i>
                                            <span class="value"><?php echo htmlspecialchars($role['RoleCode']); ?></span>
                                        </div>
                                        <?php if (!empty($role['Description'])): ?>
                                        <div class="info-item">
                                            <i class="fas fa-info-circle"></i>
                                            <span class="value"><?php echo htmlspecialchars($role['Description']); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        <div class="info-item">
                                            <i class="fas fa-key"></i>
                                            <span class="value"><?php echo $role['permission_count']; ?> Permission(s)</span>
                                        </div>
                                        <div class="info-item">
                                            <i class="fas fa-users"></i>
                                            <span class="value"><?php echo $role['user_count']; ?> User(s)</span>
                                        </div>
                                        <div class="info-item">
                                            <i class="fas fa-calendar"></i>
                                            <span class="value">Created: <?php echo date('M d, Y', strtotime($role['CreatedDate'])); ?></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="role-actions">
                                    <button class="edit-btn" onclick="editRole(<?php echo $role['ID']; ?>)">
                                        <i class="fas fa-edit"></i>
                                        <span class="btn-text">Edit</span>
                                    </button>
                                    <button class="delete-btn" onclick="deleteRole(<?php echo $role['ID']; ?>, '<?php echo htmlspecialchars($role['RoleName']); ?>', <?php echo $role['user_count']; ?>)">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <?php if (empty($roles)): ?>
                    <div class="text-center py-5">
                        <i class="fas fa-shield-alt fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted">No roles found</h5>
                        <p class="text-muted">Click "Add Role" to create your first role</p>
                    </div>
                    <?php endif; ?>

                </div>
            </div>
            <?php include_once('includes/footer.php');?>
        </div>
    </div>

    <!-- Role Modal -->
    <div class="modal fade" id="roleModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="roleModalLabel">
                        <i class="fas fa-shield-alt mr-2"></i>Add New Role
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <form method="POST" id="roleForm">
                    <div class="modal-body">
                        <input type="hidden" name="action" id="formAction" value="create">
                        <input type="hidden" name="roleId" id="roleId">
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="roleName">Role Name <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="roleName" name="roleName" 
                                           placeholder="Enter role name" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="roleCode">Role Code <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="roleCode" name="roleCode" 
                                           placeholder="Enter role code" required>
                                    <small class="form-text text-muted">Lowercase, underscore separated (e.g., manager, super_admin)</small>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="description">Description</label>
                            <textarea class="form-control" id="description" name="description" 
                                      rows="2" placeholder="Enter role description"></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label for="status">Status <span class="text-danger">*</span></label>
                            <select class="form-control" id="status" name="status" required>
                                <option value="Active">Active</option>
                                <option value="Inactive">Inactive</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label>
                                Permissions 
                                <span class="permission-count" id="selectedCount">0 selected</span>
                            </label>
                            <div class="mb-2">
                                <button type="button" class="btn btn-sm btn-outline-primary" onclick="selectAllPermissions()">
                                    <i class="fas fa-check-double"></i> Select All
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="deselectAllPermissions()">
                                    <i class="fas fa-times"></i> Deselect All
                                </button>
                            </div>
                            <div class="permissions-section">
                                <?php foreach ($permissionsByCategory as $category => $permissions): ?>
                                <div class="permission-category">
                                    <div class="category-title">
                                        <i class="fas fa-folder-open mr-1"></i><?php echo htmlspecialchars($category); ?>
                                        (<?php echo count($permissions); ?>)
                                    </div>
                                    <?php foreach ($permissions as $perm): ?>
                                    <div class="permission-item">
                                        <input type="checkbox" 
                                               name="permissions[]" 
                                               value="<?php echo $perm['ID']; ?>" 
                                               id="perm_<?php echo $perm['ID']; ?>"
                                               onchange="updatePermissionCount()">
                                        <label for="perm_<?php echo $perm['ID']; ?>">
                                            <?php echo htmlspecialchars($perm['PermissionName']); ?>
                                            <small class="text-muted">- <?php echo htmlspecialchars($perm['Description']); ?></small>
                                        </label>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary" id="submitBtn">
                            <i class="fas fa-save mr-1"></i>Save Role
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Bootstrap core JavaScript-->
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="js/sb-admin-2.min.js"></script>
    <script src="js/modern-messagebox.js"></script>
    <script src="js/messagebox-wrapper.js"></script>
    <?php renderQuickMenuScript(); ?>

    <script>
        $(document).ready(function() {
            // Hide sidebar on load
            $('body').addClass('sidebar-toggled');
            $('.sidebar').addClass('toggled');
            if ($('.sidebar').hasClass('toggled')) {
                $('.sidebar .collapse').collapse('hide');
            }

            // Add animation on page load
            $('.role-card').each(function(index) {
                $(this).css('opacity', '0').css('transform', 'translateY(30px)');
                $(this).delay(index * 50).animate({
                    opacity: 1
                }, 400, function() {
                    $(this).css('transform', 'translateY(0)');
                });
            });
            
            // Search functionality
            $('#roleSearch').on('keyup', function() {
                const searchTerm = $(this).val().toLowerCase();
                
                $('.role-item').each(function() {
                    const roleName = $(this).find('.role-name').text().toLowerCase();
                    const roleCode = $(this).find('.fa-code').parent().find('.value').text().toLowerCase();
                    const description = $(this).find('.fa-info-circle').parent().find('.value').text().toLowerCase();
                    
                    if (roleName.includes(searchTerm) || roleCode.includes(searchTerm) || description.includes(searchTerm)) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                });
            });

            // Auto-generate role code from role name
            $('#roleName').on('input', function() {
                if ($('#formAction').val() === 'create') {
                    const roleCode = $(this).val().toLowerCase().replace(/\s+/g, '_').replace(/[^a-z0-9_]/g, '');
                    $('#roleCode').val(roleCode);
                }
            });
        });

        function openRoleModal() {
            clearRoleForm();
            $('#roleModal').modal('show');
        }

        function clearRoleForm() {
            document.getElementById('roleForm').reset();
            document.getElementById('formAction').value = 'create';
            document.getElementById('roleId').value = '';
            document.getElementById('roleModalLabel').innerHTML = '<i class="fas fa-shield-alt mr-2"></i>Add New Role';
            document.getElementById('submitBtn').innerHTML = '<i class="fas fa-save mr-1"></i>Save Role';
            $('input[name="permissions[]"]').prop('checked', false);
            updatePermissionCount();
        }

        async function editRole(roleId) {
            try {
                const response = await fetch('api/get-role.php?id=' + roleId);
                const data = await response.json();
                if (data.success) {
                    const role = data.role;
                    const permissions = data.permissions || [];
                    
                    document.getElementById('formAction').value = 'update';
                    document.getElementById('roleId').value = role.ID;
                    document.getElementById('roleName').value = role.RoleName;
                    document.getElementById('roleCode').value = role.RoleCode;
                    document.getElementById('description').value = role.Description || '';
                    document.getElementById('status').value = role.Status;
                    
                    // Uncheck all permissions first
                    $('input[name="permissions[]"]').prop('checked', false);
                    
                    // Check the role's permissions
                    permissions.forEach(permId => {
                        $('#perm_' + permId).prop('checked', true);
                    });
                    
                    updatePermissionCount();
                    
                    document.getElementById('roleModalLabel').innerHTML = '<i class="fas fa-shield-alt mr-2"></i>Edit Role';
                    document.getElementById('submitBtn').innerHTML = '<i class="fas fa-save mr-1"></i>Update Role';
                    
                    $('#roleModal').modal('show');
                } else {
                    await MsgBox.alert('Error fetching role data: ' + data.message);
                }
            } catch (error) {
                console.error('Error:', error);
                await MsgBox.alert('Error fetching role data');
            }
        }

        async function deleteRole(roleId, roleName, userCount) {
            if (userCount > 0) {
                await MsgBox.alert(`Cannot delete role "${roleName}"! It is assigned to ${userCount} user(s). Please reassign users first.`);
                return;
            }
            
            const result = await MsgBox.confirm(`Are you sure you want to delete role "${roleName}"?`);
            if (result) {
                window.location.href = 'role-management.php?delete=' + roleId;
            }
        }

        function filterRoles(status) {
            // Update active button
            $('.btn-group .btn').removeClass('active');
            event.target.classList.add('active');
            
            // Show/hide roles based on status
            $('.role-item').each(function() {
                if (status === 'all') {
                    $(this).show();
                } else {
                    const itemStatus = $(this).data('status');
                    if (itemStatus === status) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                }
            });
        }

        function selectAllPermissions() {
            $('input[name="permissions[]"]').prop('checked', true);
            updatePermissionCount();
        }

        function deselectAllPermissions() {
            $('input[name="permissions[]"]').prop('checked', false);
            updatePermissionCount();
        }

        function updatePermissionCount() {
            const count = $('input[name="permissions[]"]:checked').length;
            $('#selectedCount').text(count + ' selected');
        }

        // Auto-dismiss alerts after 5 seconds
        setTimeout(function() {
            $('.alert').fadeOut();
        }, 5000);
    </script>
</body>
</html>
