<?php
session_start();
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

// Check if user is logged in and has admin privileges
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    header('Location: login.php');
    exit();
}

// Database connection check
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Handle role actions (Add, Edit, Delete, Toggle Status)
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add_role') {
        $role_name = trim($_POST['role_name']);
        $role_code = strtoupper(trim($_POST['role_code']));
        $description = trim($_POST['description']);
        $is_system = isset($_POST['is_system']) ? 1 : 0;
        
        // Check if role already exists
        $check_sql = "SELECT role_id FROM user_roles WHERE role_name = ? OR role_code = ?";
        $check_stmt = $conn->prepare($check_sql);
        $check_stmt->bind_param('ss', $role_name, $role_code);
        $check_stmt->execute();
        
        if ($check_stmt->get_result()->num_rows > 0) {
            $message = 'Role name or code already exists!';
            $message_type = 'error';
        } else {
            $insert_sql = "INSERT INTO user_roles (role_name, role_code, description, is_system, is_active) VALUES (?, ?, ?, ?, 1)";
            $insert_stmt = $conn->prepare($insert_sql);
            $insert_stmt->bind_param('sssi', $role_name, $role_code, $description, $is_system);
            
            if ($insert_stmt->execute()) {
                $message = 'Role added successfully!';
                $message_type = 'success';
            } else {
                $message = 'Failed to add role!';
                $message_type = 'error';
            }
        }
    }
    
    if ($action === 'edit_role') {
        $role_id = (int)$_POST['role_id'];
        $role_name = trim($_POST['role_name']);
        $description = trim($_POST['description']);
        
        $update_sql = "UPDATE user_roles SET role_name = ?, description = ? WHERE role_id = ? AND is_system = 0";
        $update_stmt = $conn->prepare($update_sql);
        $update_stmt->bind_param('ssi', $role_name, $description, $role_id);
        
        if ($update_stmt->execute()) {
            $message = 'Role updated successfully!';
            $message_type = 'success';
        } else {
            $message = 'Failed to update role!';
            $message_type = 'error';
        }
    }
    
    if ($action === 'toggle_status') {
        $role_id = (int)$_POST['role_id'];
        $new_status = (int)$_POST['new_status'];
        
        // Prevent deactivating system roles
        $update_sql = "UPDATE user_roles SET is_active = ? WHERE role_id = ? AND is_system = 0";
        $update_stmt = $conn->prepare($update_sql);
        $update_stmt->bind_param('ii', $new_status, $role_id);
        
        if ($update_stmt->execute()) {
            $message = 'Role status updated successfully!';
            $message_type = 'success';
        } else {
            $message = 'Failed to update role status!';
            $message_type = 'error';
        }
    }
    
    if ($action === 'delete_role') {
        $role_id = (int)$_POST['role_id'];
        
        // Check if role is assigned to users
        $check_users_sql = "SELECT COUNT(*) as user_count FROM users WHERE role_id = ?";
        $check_users_stmt = $conn->prepare($check_users_sql);
        $check_users_stmt->bind_param('i', $role_id);
        $check_users_stmt->execute();
        $user_count = $check_users_stmt->get_result()->fetch_assoc()['user_count'];
        
        if ($user_count > 0) {
            $message = 'Cannot delete role - it is assigned to ' . $user_count . ' user(s)!';
            $message_type = 'error';
        } else {
            // Delete role permissions first, then role
            $delete_permissions_sql = "DELETE FROM role_permissions WHERE role_id = ?";
            $delete_permissions_stmt = $conn->prepare($delete_permissions_sql);
            $delete_permissions_stmt->bind_param('i', $role_id);
            $delete_permissions_stmt->execute();
            
            $delete_role_sql = "DELETE FROM user_roles WHERE role_id = ? AND is_system = 0";
            $delete_role_stmt = $conn->prepare($delete_role_sql);
            $delete_role_stmt->bind_param('i', $role_id);
            
            if ($delete_role_stmt->execute()) {
                $message = 'Role deleted successfully!';
                $message_type = 'success';
            } else {
                $message = 'Failed to delete role!';
                $message_type = 'error';
            }
        }
    }
}

// Fetch all roles with user counts
$roles_sql = "SELECT ur.*, 
              COUNT(u.user_id) as user_count,
              COUNT(rp.permission_id) as permission_count
              FROM user_roles ur
              LEFT JOIN users u ON ur.role_id = u.role_id AND u.status = 'ACTIVE'
              LEFT JOIN role_permissions rp ON ur.role_id = rp.role_id
              GROUP BY ur.role_id, ur.role_name, ur.role_code, ur.description, ur.is_system, ur.is_active, ur.created_at
              ORDER BY ur.is_system DESC, ur.role_name";
$roles_result = $conn->query($roles_sql);

// Get menu items for permission assignment
$menu_sql = "SELECT menu_id, menu_name, parent_id, menu_icon FROM menu_items WHERE is_active = 1 ORDER BY parent_id, menu_order";
$menu_result = $conn->query($menu_sql);
$menu_items = [];
while ($row = $menu_result->fetch_assoc()) {
    $menu_items[] = $row;
}

$conn->close();
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'User Roles Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <style>
        .role-card {
            transition: all 0.3s ease;
            border-left: 4px solid transparent;
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
        }
        
        .role-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        }
        
        .role-card.system-role {
            border-left-color: #667eea;
            background: linear-gradient(135deg, #f0f2ff 0%, #e6e9ff 100%);
        }
        
        .role-card.custom-role {
            border-left-color: #0ab39c;
            background: linear-gradient(135deg, #f0fffe 0%, #e6fffc 100%);
        }
        
        .role-card.inactive-role {
            border-left-color: #f06548;
            background: linear-gradient(135deg, #fff5f5 0%, #ffe6e6 100%);
            opacity: 0.7;
        }
        
        .role-actions {
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .role-card:hover .role-actions {
            opacity: 1;
        }
        
        .stat-card {
            border-radius: 15px;
            border: none;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .stat-number {
            font-size: 2.5rem;
            font-weight: 700;
        }
        
        .badge-role-system {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .badge-role-custom {
            background: linear-gradient(135deg, #0ab39c 0%, #06b6d4 100%);
            color: white;
        }
        
        .permissions-preview {
            max-height: 150px;
            overflow-y: auto;
        }
        
        .permission-badge {
            font-size: 0.75rem;
            padding: 0.25rem 0.5rem;
            margin: 0.1rem;
            border-radius: 10px;
        }
        
        .section-title {
            font-size: 1.25rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1.5rem;
            position: relative;
            padding-left: 20px;
        }
        
        .section-title::before {
            content: '';
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 4px;
            height: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 2px;
        }
        
        .modal .form-floating label {
            color: #6c757d;
        }
        
        .btn-gradient {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            color: white;
            border-radius: 8px;
            padding: 0.5rem 1rem;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .btn-gradient:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
            color: white;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">User Roles Management</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="#!">Administration</a></li>
                                        <li class="breadcrumb-item active">User Roles</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <?php
                        $total_roles = 0;
                        $system_roles = 0;
                        $custom_roles = 0;
                        $active_roles = 0;
                        
                        $roles_result->data_seek(0); // Reset result pointer
                        while ($role = $roles_result->fetch_assoc()) {
                            $total_roles++;
                            if ($role['is_system']) $system_roles++;
                            else $custom_roles++;
                            if ($role['is_active']) $active_roles++;
                        }
                        ?>
                        
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="card stat-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <i class="ri-group-line display-6"></i>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <h4 class="stat-number mb-0"><?php echo $total_roles; ?></h4>
                                            <p class="text-white-50 mb-0">Total Roles</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="card" style="background: linear-gradient(135deg, #0ab39c 0%, #06b6d4 100%); color: white;">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <i class="ri-shield-check-line display-6"></i>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <h4 class="stat-number mb-0"><?php echo $system_roles; ?></h4>
                                            <p class="text-white-50 mb-0">System Roles</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="card" style="background: linear-gradient(135deg, #3577f1 0%, #7c3aed 100%); color: white;">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <i class="ri-user-settings-line display-6"></i>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <h4 class="stat-number mb-0"><?php echo $custom_roles; ?></h4>
                                            <p class="text-white-50 mb-0">Custom Roles</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="card" style="background: linear-gradient(135deg, #299cdb 0%, #06b6d4 100%); color: white;">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <i class="ri-check-double-line display-6"></i>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <h4 class="stat-number mb-0"><?php echo $active_roles; ?></h4>
                                            <p class="text-white-50 mb-0">Active Roles</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Main Content -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h4 class="section-title mb-0">👥 System Roles</h4>
                                    <div class="d-flex gap-2">
                                        <button class="btn btn-gradient" data-bs-toggle="modal" data-bs-target="#addRoleModal">
                                            <i class="ri-add-line me-1"></i> Add New Role
                                        </button>
                                        <a href="role_permissions.php" class="btn btn-outline-primary">
                                            <i class="ri-settings-3-line me-1"></i> Manage Permissions
                                        </a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    
                                    <?php if ($message): ?>
                                    <div class="alert alert-<?php echo $message_type === 'success' ? 'success' : 'danger'; ?> alert-dismissible fade show" role="alert">
                                        <i class="ri-<?php echo $message_type === 'success' ? 'check-double' : 'error-warning'; ?>-line me-1"></i>
                                        <?php echo $message; ?>
                                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                    </div>
                                    <?php endif; ?>

                                    <div class="row">
                                        <?php
                                        $roles_result->data_seek(0); // Reset result pointer
                                        while ($role = $roles_result->fetch_assoc()):
                                            $card_class = 'role-card ';
                                            if (!$role['is_active']) {
                                                $card_class .= 'inactive-role';
                                            } elseif ($role['is_system']) {
                                                $card_class .= 'system-role';
                                            } else {
                                                $card_class .= 'custom-role';
                                            }
                                        ?>
                                        <div class="col-xl-4 col-lg-6 mb-4">
                                            <div class="card <?php echo $card_class; ?>">
                                                <div class="card-body">
                                                    <div class="d-flex justify-content-between align-items-start mb-3">
                                                        <div class="flex-grow-1">
                                                            <h5 class="card-title mb-2">
                                                                <?php echo htmlspecialchars($role['role_name']); ?>
                                                                <?php if ($role['is_system']): ?>
                                                                <span class="badge badge-role-system ms-2">System</span>
                                                                <?php else: ?>
                                                                <span class="badge badge-role-custom ms-2">Custom</span>
                                                                <?php endif; ?>
                                                            </h5>
                                                            <p class="text-muted mb-1">
                                                                <i class="ri-key-line me-1"></i> 
                                                                Code: <strong><?php echo htmlspecialchars($role['role_code']); ?></strong>
                                                            </p>
                                                            <p class="card-text mb-3">
                                                                <?php echo htmlspecialchars($role['description'] ?: 'No description available.'); ?>
                                                            </p>
                                                        </div>
                                                        <div class="role-actions">
                                                            <div class="dropdown">
                                                                <button class="btn btn-sm btn-light" data-bs-toggle="dropdown">
                                                                    <i class="ri-more-2-line"></i>
                                                                </button>
                                                                <ul class="dropdown-menu">
                                                                    <?php if (!$role['is_system']): ?>
                                                                    <li><a class="dropdown-item" href="#" onclick="editRole(<?php echo $role['role_id']; ?>, '<?php echo addslashes($role['role_name']); ?>', '<?php echo addslashes($role['description']); ?>')">
                                                                        <i class="ri-edit-line me-2"></i>Edit Role
                                                                    </a></li>
                                                                    <li><a class="dropdown-item" href="#" onclick="toggleRoleStatus(<?php echo $role['role_id']; ?>, <?php echo $role['is_active'] ? 0 : 1; ?>)">
                                                                        <i class="ri-<?php echo $role['is_active'] ? 'pause' : 'play'; ?>-line me-2"></i>
                                                                        <?php echo $role['is_active'] ? 'Deactivate' : 'Activate'; ?>
                                                                    </a></li>
                                                                    <?php if ($role['user_count'] == 0): ?>
                                                                    <li><hr class="dropdown-divider"></li>
                                                                    <li><a class="dropdown-item text-danger" href="#" onclick="deleteRole(<?php echo $role['role_id']; ?>, '<?php echo addslashes($role['role_name']); ?>')">
                                                                        <i class="ri-delete-bin-line me-2"></i>Delete Role
                                                                    </a></li>
                                                                    <?php endif; ?>
                                                                    <?php endif; ?>
                                                                    <li><a class="dropdown-item" href="role_permissions.php?role_id=<?php echo $role['role_id']; ?>">
                                                                        <i class="ri-settings-3-line me-2"></i>Manage Permissions
                                                                    </a></li>
                                                                </ul>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <!-- Role Statistics -->
                                                    <div class="row g-2 mb-3">
                                                        <div class="col-6">
                                                            <div class="p-2 bg-light rounded text-center">
                                                                <div class="fw-bold text-primary"><?php echo $role['user_count']; ?></div>
                                                                <small class="text-muted">Users</small>
                                                            </div>
                                                        </div>
                                                        <div class="col-6">
                                                            <div class="p-2 bg-light rounded text-center">
                                                                <div class="fw-bold text-success"><?php echo $role['permission_count']; ?></div>
                                                                <small class="text-muted">Permissions</small>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <!-- Status Badge -->
                                                    <div class="d-flex justify-content-between align-items-center">
                                                        <span class="badge <?php echo $role['is_active'] ? 'bg-success' : 'bg-danger'; ?>">
                                                            <i class="ri-<?php echo $role['is_active'] ? 'check' : 'close'; ?>-line me-1"></i>
                                                            <?php echo $role['is_active'] ? 'Active' : 'Inactive'; ?>
                                                        </span>
                                                        <small class="text-muted">
                                                            Created: <?php echo date('M j, Y', strtotime($role['created_at'])); ?>
                                                        </small>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <?php endwhile; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Add Role Modal -->
    <div class="modal fade" id="addRoleModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <form method="POST" id="addRoleForm">
                    <input type="hidden" name="action" value="add_role">
                    <div class="modal-header">
                        <h5 class="modal-title">
                            <i class="ri-add-line me-2"></i>Add New User Role
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <div class="form-floating">
                                    <input type="text" class="form-control" id="role_name" name="role_name" placeholder="Role Name" required>
                                    <label for="role_name">Role Name</label>
                                </div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <div class="form-floating">
                                    <input type="text" class="form-control" id="role_code" name="role_code" placeholder="Role Code" required>
                                    <label for="role_code">Role Code (e.g., ENT_NURSE)</label>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <div class="form-floating">
                                <textarea class="form-control" id="description" name="description" placeholder="Description" style="height: 100px;"></textarea>
                                <label for="description">Role Description</label>
                            </div>
                        </div>
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="is_system" name="is_system">
                                <label class="form-check-label" for="is_system">
                                    System Role (Protected from deletion)
                                </label>
                            </div>
                        </div>
                        <div class="alert alert-info">
                            <i class="ri-information-line me-2"></i>
                            <strong>Note:</strong> After creating the role, you can assign specific permissions by clicking "Manage Permissions".
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-gradient">
                            <i class="ri-save-line me-1"></i> Create Role
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit Role Modal -->
    <div class="modal fade" id="editRoleModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST" id="editRoleForm">
                    <input type="hidden" name="action" value="edit_role">
                    <input type="hidden" name="role_id" id="edit_role_id">
                    <div class="modal-header">
                        <h5 class="modal-title">
                            <i class="ri-edit-line me-2"></i>Edit User Role
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <div class="form-floating">
                                <input type="text" class="form-control" id="edit_role_name" name="role_name" placeholder="Role Name" required>
                                <label for="edit_role_name">Role Name</label>
                            </div>
                        </div>
                        <div class="mb-3">
                            <div class="form-floating">
                                <textarea class="form-control" id="edit_description" name="description" placeholder="Description" style="height: 100px;"></textarea>
                                <label for="edit_description">Role Description</label>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-gradient">
                            <i class="ri-save-line me-1"></i> Update Role
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Hidden forms for actions -->
    <form id="statusForm" method="POST" style="display: none;">
        <input type="hidden" name="action" value="toggle_status">
        <input type="hidden" name="role_id" id="status_role_id">
        <input type="hidden" name="new_status" id="new_status">
    </form>
    
    <form id="deleteForm" method="POST" style="display: none;">
        <input type="hidden" name="action" value="delete_role">
        <input type="hidden" name="role_id" id="delete_role_id">
    </form>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>
    
    <script>
    // Auto-generate role code from role name
    document.getElementById('role_name').addEventListener('input', function() {
        const roleName = this.value.trim();
        const roleCode = roleName.toUpperCase()
            .replace(/\s+/g, '_')
            .replace(/[^A-Z0-9_]/g, '');
        document.getElementById('role_code').value = roleCode;
    });
    
    // Edit role function
    function editRole(roleId, roleName, description) {
        document.getElementById('edit_role_id').value = roleId;
        document.getElementById('edit_role_name').value = roleName;
        document.getElementById('edit_description').value = description;
        
        const editModal = new bootstrap.Modal(document.getElementById('editRoleModal'));
        editModal.show();
    }
    
    // Toggle role status
    function toggleRoleStatus(roleId, newStatus) {
        const statusText = newStatus ? 'activate' : 'deactivate';
        
        Swal.fire({
            title: 'Are you sure?',
            text: `Do you want to ${statusText} this role?`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#667eea',
            cancelButtonColor: '#f06548',
            confirmButtonText: `Yes, ${statusText} it!`,
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                document.getElementById('status_role_id').value = roleId;
                document.getElementById('new_status').value = newStatus;
                document.getElementById('statusForm').submit();
            }
        });
    }
    
    // Delete role function
    function deleteRole(roleId, roleName) {
        Swal.fire({
            title: 'Delete Role?',
            html: `Are you sure you want to delete the role <strong>${roleName}</strong>?<br><br>
                   <div class="alert alert-danger mb-0">
                   <i class="ri-error-warning-line me-1"></i>
                   This action cannot be undone!
                   </div>`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#f06548',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, delete it!',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                document.getElementById('delete_role_id').value = roleId;
                document.getElementById('deleteForm').submit();
            }
        });
    }
    
    // Form validation
    document.getElementById('addRoleForm').addEventListener('submit', function(e) {
        const roleName = document.getElementById('role_name').value.trim();
        const roleCode = document.getElementById('role_code').value.trim();
        
        if (!roleName || !roleCode) {
            e.preventDefault();
            Swal.fire({
                title: 'Validation Error',
                text: 'Please fill in all required fields.',
                icon: 'error',
                confirmButtonColor: '#667eea'
            });
            return false;
        }
        
        if (roleCode.length < 3) {
            e.preventDefault();
            Swal.fire({
                title: 'Validation Error',
                text: 'Role code must be at least 3 characters long.',
                icon: 'error',
                confirmButtonColor: '#667eea'
            });
            return false;
        }
    });
    
    // Success/Error messages
    <?php if ($message && $message_type === 'success'): ?>
    Swal.fire({
        title: 'Success!',
        text: '<?php echo addslashes($message); ?>',
        icon: 'success',
        confirmButtonColor: '#0ab39c'
    });
    <?php elseif ($message && $message_type === 'error'): ?>
    Swal.fire({
        title: 'Error!',
        text: '<?php echo addslashes($message); ?>',
        icon: 'error',
        confirmButtonColor: '#f06548'
    });
    <?php endif; ?>
    </script>

</body>
</html>