<?php
// Advanced User Management System
include '../includes/auth.php';
include '../includes/db.php';

// Check if user has permission to access user management
$allowed_roles = ['super_admin', 'admin'];
$user_role = $_SESSION['role'] ?? $_SESSION['user_type'] ?? '';

if (!in_array($user_role, $allowed_roles)) {
    header("Location: ../login.php?error=unauthorized");
    exit;
}

$message = '';
$current_user_id = $_SESSION['user_id'] ?? 0;

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_user':
                $message = handleAddUser($pdo, $_POST, $user_role, $current_user_id);
                break;
            case 'edit_user':
                $message = handleEditUser($pdo, $_POST, $user_role, $current_user_id);
                break;
            case 'delete_user':
                $message = handleDeleteUser($pdo, $_POST, $user_role, $current_user_id);
                break;
            case 'add_group':
                $message = handleAddGroup($pdo, $_POST, $current_user_id);
                break;
            case 'manage_group_membership':
                $message = handleGroupMembership($pdo, $_POST, $current_user_id);
                break;
            case 'edit_group':
                $message = handleEditGroup($pdo, $_POST, $current_user_id);
                break;
            case 'add_member_to_group':
                $message = handleAddMemberToGroup($pdo, $_POST, $current_user_id);
                break;
        }
        
        // Redirect to avoid form resubmission
        if (strpos($message, 'success') !== false) {
            header("Location: " . $_SERVER['PHP_SELF'] . "?msg=" . urlencode($message));
            exit;
        }
    }
}

// Handle GET messages
if (isset($_GET['msg'])) {
    $message = $_GET['msg'];
}

function handleAddUser($pdo, $data, $user_role, $current_user_id) {
    try {
        $username = trim($data['username']);
        $password = $data['password'];
        $role = $data['role'];
        $full_name = trim($data['full_name']);
        $email = trim($data['email']);
        $phone = trim($data['phone'] ?? '');
        $group_ids = $data['groups'] ?? [];
        
        // Check role permissions
        $allowed_roles_to_create = getRolesUserCanCreate($user_role);
        if (!in_array($role, $allowed_roles_to_create)) {
            return "error: You don't have permission to create users with role: $role";
        }
        
        // Check if username or email exists
        $check = $pdo->prepare("SELECT id FROM users WHERE username = ? OR EXISTS(SELECT 1 FROM user_profiles WHERE email = ?)");
        $check->execute([$username, $email]);
        if ($check->fetch()) {
            return "error: Username or email already exists";
        }
        
        $pdo->beginTransaction();
        
        // Insert into users table
        $stmt = $pdo->prepare("INSERT INTO users (username, password, role, created_at) VALUES (?, ?, ?, NOW())");
        $stmt->execute([$username, password_hash($password, PASSWORD_DEFAULT), $role]);
        $user_id = $pdo->lastInsertId();
        
        // Insert into user_profiles table
        $profile_stmt = $pdo->prepare("INSERT INTO user_profiles (user_id, full_name, email, phone, created_at) VALUES (?, ?, ?, ?, NOW())");
        $profile_stmt->execute([$user_id, $full_name, $email, $phone]);
        
        // Add to groups if selected
        if (!empty($group_ids)) {
            $group_stmt = $pdo->prepare("INSERT INTO user_group_memberships (user_id, group_id, role_in_group) VALUES (?, ?, 'member')");
            foreach ($group_ids as $group_id) {
                $group_stmt->execute([$user_id, $group_id]);
            }
        }
        
        // Add basic login permission
        $perm_stmt = $pdo->prepare("INSERT INTO user_permissions (user_id, permission, granted_by) VALUES (?, 'login', ?)");
        $perm_stmt->execute([$user_id, $current_user_id]);
        
        $pdo->commit();
        return "success: User created successfully with ID: $user_id";
        
    } catch (Exception $e) {
        $pdo->rollback();
        return "error: " . $e->getMessage();
    }
}

function handleEditUser($pdo, $data, $user_role, $current_user_id) {
    try {
        $user_id = intval($data['user_id']);
        
        // Check if this is just a status toggle
        if (isset($data['toggle_status'])) {
            $is_active = isset($data['is_active']) ? 1 : 0;
            
            // Try to update user_profiles table first
            try {
                $profile_stmt = $pdo->prepare("UPDATE user_profiles SET is_active = ? WHERE user_id = ?");
                $profile_stmt->execute([$is_active, $user_id]);
            } catch (Exception $e) {
                // If user_profiles doesn't exist, update users table directly
                $stmt = $pdo->prepare("UPDATE users SET is_active = ? WHERE id = ?");
                $stmt->execute([$is_active, $user_id]);
            }
            
            return "success: User status updated successfully";
        }
        
        // Full user edit
        $username = trim($data['username']);
        $role = $data['role'];
        $full_name = trim($data['full_name']);
        $email = trim($data['email']);
        $phone = trim($data['phone'] ?? '');
        $is_active = isset($data['is_active']) ? 1 : 0;
        
        // Check role permissions
        $allowed_roles_to_create = getRolesUserCanCreate($user_role);
        if (!in_array($role, $allowed_roles_to_create)) {
            return "error: You don't have permission to assign role: $role";
        }
        
        $pdo->beginTransaction();
        
        // Update users table
        $stmt = $pdo->prepare("UPDATE users SET username = ?, role = ? WHERE id = ?");
        $stmt->execute([$username, $role, $user_id]);
        
        // Update user_profiles table
        try {
            $profile_stmt = $pdo->prepare("UPDATE user_profiles SET full_name = ?, email = ?, phone = ?, is_active = ?, updated_at = NOW() WHERE user_id = ?");
            $profile_stmt->execute([$full_name, $email, $phone, $is_active, $user_id]);
        } catch (Exception $e) {
            // If user_profiles doesn't exist, just update basic info in users table
            $stmt = $pdo->prepare("UPDATE users SET username = ?, role = ?, is_active = ? WHERE id = ?");
            $stmt->execute([$username, $role, $is_active, $user_id]);
        }
        
        $pdo->commit();
        return "success: User updated successfully";
        
    } catch (Exception $e) {
        $pdo->rollback();
        return "error: " . $e->getMessage();
    }
}

function handleDeleteUser($pdo, $data, $user_role, $current_user_id) {
    try {
        $user_id = intval($data['user_id']);
        
        // Prevent deleting self or super_admin (unless current user is super_admin)
        if ($user_id == $current_user_id) {
            return "error: You cannot delete your own account";
        }
        
        // Check target user role
        $target_user = $pdo->prepare("SELECT role FROM users WHERE id = ?");
        $target_user->execute([$user_id]);
        $target_role = $target_user->fetchColumn();
        
        if ($target_role === 'super_admin' && $user_role !== 'super_admin') {
            return "error: You cannot delete super admin accounts";
        }
        
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        
        return "success: User deleted successfully";
        
    } catch (Exception $e) {
        return "error: " . $e->getMessage();
    }
}

function handleAddGroup($pdo, $data, $current_user_id) {
    try {
        $name = trim($data['group_name']);
        $description = trim($data['group_description'] ?? '');
        $color = $data['group_color'] ?? '#007bff';
        
        $stmt = $pdo->prepare("INSERT INTO user_groups (name, description, color, created_by) VALUES (?, ?, ?, ?)");
        $stmt->execute([$name, $description, $color, $current_user_id]);
        
        return "success: Group created successfully";
        
    } catch (Exception $e) {
        return "error: " . $e->getMessage();
    }
}

function handleGroupMembership($pdo, $data, $current_user_id) {
    try {
        $user_id = intval($data['user_id']);
        $group_id = intval($data['group_id']);
        $action = $data['membership_action']; // 'add' or 'remove'
        
        if ($action === 'add') {
            $stmt = $pdo->prepare("INSERT IGNORE INTO user_group_memberships (user_id, group_id, role_in_group) VALUES (?, ?, 'member')");
            $stmt->execute([$user_id, $group_id]);
            return "success: User added to group";
        } else {
            $stmt = $pdo->prepare("DELETE FROM user_group_memberships WHERE user_id = ? AND group_id = ?");
            $stmt->execute([$user_id, $group_id]);
            return "success: User removed from group";
        }
        
    } catch (Exception $e) {
        return "error: " . $e->getMessage();
    }
}

function handleEditGroup($pdo, $data, $current_user_id) {
    try {
        $group_id = intval($data['group_id']);
        $name = trim($data['group_name']);
        $description = trim($data['group_description'] ?? '');
        $color = $data['group_color'] ?? '#007bff';
        
        $stmt = $pdo->prepare("UPDATE user_groups SET name = ?, description = ?, color = ? WHERE id = ?");
        $stmt->execute([$name, $description, $color, $group_id]);
        
        return "success: Group updated successfully";
        
    } catch (Exception $e) {
        return "error: " . $e->getMessage();
    }
}

function handleAddMemberToGroup($pdo, $data, $current_user_id) {
    try {
        $user_id = intval($data['user_id']);
        $group_id = intval($data['group_id']);
        $role_in_group = $data['role_in_group'] ?? 'member';
        
        // Check if user is already in group
        $check = $pdo->prepare("SELECT id FROM user_group_memberships WHERE user_id = ? AND group_id = ?");
        $check->execute([$user_id, $group_id]);
        if ($check->fetch()) {
            return "error: User is already a member of this group";
        }
        
        // Check what columns exist in the table
        $columns = $pdo->query("SHOW COLUMNS FROM user_group_memberships")->fetchAll(PDO::FETCH_COLUMN);
        
        // Build query based on available columns
        $insertColumns = "user_id, group_id, role_in_group";
        $insertValues = "?, ?, ?";
        $params = [$user_id, $group_id, $role_in_group];
        
        // Add added_by if column exists
        if (in_array('added_by', $columns)) {
            $insertColumns .= ", added_by";
            $insertValues .= ", ?";
            $params[] = $current_user_id;
        }
        
        // Add timestamp column if any exists
        if (in_array('created_at', $columns)) {
            $insertColumns .= ", created_at";
            $insertValues .= ", NOW()";
        } elseif (in_array('joined_at', $columns)) {
            $insertColumns .= ", joined_at";
            $insertValues .= ", NOW()";
        } elseif (in_array('added_at', $columns)) {
            $insertColumns .= ", added_at";
            $insertValues .= ", NOW()";
        }
        
        $stmt = $pdo->prepare("INSERT INTO user_group_memberships ($insertColumns) VALUES ($insertValues)");
        $result = $stmt->execute($params);
        
        if ($result) {
            return "success: Member added successfully";
        } else {
            return "error: Failed to add member to group";
        }
        
    } catch (Exception $e) {
        // If the table doesn't exist, try to create it with basic structure
        if (strpos($e->getMessage(), "doesn't exist") !== false) {
            try {
                $pdo->exec("
                    CREATE TABLE user_group_memberships (
                        id INT AUTO_INCREMENT PRIMARY KEY,
                        user_id INT NOT NULL,
                        group_id INT NOT NULL,
                        role_in_group VARCHAR(50) DEFAULT 'member',
                        added_by INT NULL,
                        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                        UNIQUE KEY unique_membership (user_id, group_id),
                        KEY idx_user_id (user_id),
                        KEY idx_group_id (group_id)
                    )
                ");
                
                // Retry the insert
                $stmt = $pdo->prepare("INSERT INTO user_group_memberships (user_id, group_id, role_in_group, added_by, created_at) VALUES (?, ?, ?, ?, NOW())");
                $result = $stmt->execute([$user_id, $group_id, $role_in_group, $current_user_id]);
                
                if ($result) {
                    return "success: Member added successfully (table created)";
                }
            } catch (Exception $e2) {
                return "error: Could not create membership table: " . $e2->getMessage();
            }
        }
        return "error: " . $e->getMessage();
    }
}

function getRolesUserCanCreate($user_role) {
    switch ($user_role) {
        case 'super_admin':
            return ['super_admin', 'admin', 'judge', 'head_judge', 'office', 'media', 'participant'];
        case 'admin':
            return ['judge', 'head_judge', 'office', 'media', 'participant'];
        case 'office':
            return ['media', 'participant'];
        default:
            return ['participant'];
    }
}

// Fetch data for display
try {
    // Get all users with profiles - try robust query first
    try {
        $users_query = "
            SELECT u.id, u.username, u.role, u.created_at, u.last_login,
                   p.full_name, p.email, p.phone, p.is_active,
                   GROUP_CONCAT(CONCAT(g.name, ':', g.color) SEPARATOR '|') as groups
            FROM users u
            LEFT JOIN user_profiles p ON u.id = p.user_id
            LEFT JOIN user_group_memberships ugm ON u.id = ugm.user_id
            LEFT JOIN user_groups g ON ugm.group_id = g.id
            GROUP BY u.id
            ORDER BY u.created_at DESC
        ";
        $users = $pdo->query($users_query)->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        // Fallback query without group information if tables don't exist
        $users_query = "
            SELECT u.id, u.username, u.role, u.created_at, u.last_login,
                   p.full_name, p.email, p.phone, p.is_active,
                   '' as groups
            FROM users u
            LEFT JOIN user_profiles p ON u.id = p.user_id
            ORDER BY u.created_at DESC
        ";
        $users = $pdo->query($users_query)->fetchAll(PDO::FETCH_ASSOC);
    }
    
    // Get all groups
    $groups = $pdo->query("
        SELECT g.*, u.username as created_by_name,
               COUNT(ugm.user_id) as member_count
        FROM user_groups g
        LEFT JOIN users u ON g.created_by = u.id
        LEFT JOIN user_group_memberships ugm ON g.id = ugm.group_id
        GROUP BY g.id
        ORDER BY g.name
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    // Get role statistics
    $role_stats = $pdo->query("
        SELECT role, COUNT(*) as count
        FROM users
        GROUP BY role
        ORDER BY count DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    $users = [];
    $groups = [];
    $role_stats = [];
    if (!$message) {
        $message = "error: Database error: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Management - Style Score Admin</title>
    <?php include_once '../includes/stylesheets.php'; ?>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
    
    <div class="container py-4">
        <div class="row">
            <div class="col-12">
                <!-- Header -->
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <div>
                        <h2 class="mb-1">
                            <i class="fas fa-users-cog text-primary me-2"></i>User Management
                        </h2>
                        <p class="text-muted mb-0">Manage users, roles and groups</p>
                    </div>
                    <span class="badge bg-primary fs-6">Your Role: <?= ucfirst(str_replace('_', ' ', $user_role)) ?></span>
                </div>

                <!-- Messages -->
                <?php if ($message): ?>
                    <?php
                    $msg_type = strpos($message, 'success:') === 0 ? 'success' : 'danger';
                    $msg_text = substr($message, strpos($message, ':') + 1);
                    ?>
                    <div class="alert alert-<?= $msg_type ?> alert-dismissible fade show">
                        <i class="fas fa-<?= $msg_type === 'success' ? 'check-circle' : 'exclamation-triangle' ?> me-2"></i>
                        <?= htmlspecialchars(trim($msg_text)) ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <!-- Statistics Cards -->
                <div class="row g-3 mb-4">
                    <div class="col-lg-3 col-md-6">
                        <div class="card border-primary">
                            <div class="card-body text-center">
                                <i class="fas fa-users fa-2x text-primary mb-2"></i>
                                <h4 class="mb-1"><?= count($users) ?></h4>
                                <p class="text-muted mb-0">Total Users</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-md-6">
                        <div class="card border-success">
                            <div class="card-body text-center">
                                <i class="fas fa-layer-group fa-2x text-success mb-2"></i>
                                <h4 class="mb-1"><?= count($groups) ?></h4>
                                <p class="text-muted mb-0">Active Groups</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-md-6">
                        <div class="card border-info">
                            <div class="card-body text-center">
                                <i class="fas fa-user-check fa-2x text-info mb-2"></i>
                                <h4 class="mb-1"><?= count(array_filter($users, function($u) { return $u['is_active']; })) ?></h4>
                                <p class="text-muted mb-0">Active Users</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-md-6">
                        <div class="card border-warning">
                            <div class="card-body text-center">
                                <i class="fas fa-user-tag fa-2x text-warning mb-2"></i>
                                <h4 class="mb-1"><?= count($role_stats) ?></h4>
                                <p class="text-muted mb-0">Different Roles</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Main Content Tabs -->
                <div class="card">
                    <div class="card-header p-0">
                        <ul class="nav nav-tabs card-header-tabs" id="managementTabs" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="users-tab" data-bs-toggle="tab" data-bs-target="#users" type="button" role="tab">
                                    <i class="fas fa-users me-2"></i>Users
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="groups-tab" data-bs-toggle="tab" data-bs-target="#groups" type="button" role="tab">
                                    <i class="fas fa-layer-group me-2"></i>Groups
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="roles-tab" data-bs-toggle="tab" data-bs-target="#roles" type="button" role="tab">
                                    <i class="fas fa-user-tag me-2"></i>Roles & Permissions
                                </button>
                            </li>
                        </ul>
                    </div>
                    
                    <div class="card-body">
                        <div class="tab-content" id="managementTabsContent">
                        <!-- Users Tab -->
                        <div class="tab-pane fade show active" id="users" role="tabpanel">
                            <div class="d-flex justify-content-between align-items-center mb-4">
                                <h5 class="mb-0">User Management</h5>
                                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addUserModal">
                                    <i class="fas fa-plus me-2"></i>Add New User
                                </button>
                            </div>
                            
                            <div class="table-responsive">
                                <table class="table table-hover align-middle">
                                    <thead class="table-light">
                                        <tr>
                                            <th>User</th>
                                            <th>Contact</th>
                                            <th>Role</th>
                                            <th>Groups</th>
                                            <th>Status</th>
                                            <th>Created</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($users as $user): ?>
                                        <tr>
                                            <td>
                                                <div class="d-flex align-items-center">
                                                    <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 40px; height: 40px;">
                                                        <strong><?= strtoupper(substr($user['full_name'] ?: $user['username'], 0, 2)) ?></strong>
                                                    </div>
                                                    <div>
                                                        <h6 class="mb-0"><?= htmlspecialchars($user['full_name'] ?: $user['username']) ?></h6>
                                                        <small class="text-muted">@<?= htmlspecialchars($user['username']) ?></small>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                <?php if ($user['email']): ?>
                                                    <div><i class="fas fa-envelope me-1"></i><?= htmlspecialchars($user['email']) ?></div>
                                                <?php endif; ?>
                                                <?php if ($user['phone']): ?>
                                                    <div><i class="fas fa-phone me-1"></i><?= htmlspecialchars($user['phone']) ?></div>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?= getRoleColor($user['role']) ?>">
                                                    <?= ucfirst(str_replace('_', ' ', $user['role'])) ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php if ($user['groups']): ?>
                                                    <?php 
                                                    $groups_data = explode('|', $user['groups']);
                                                    foreach ($groups_data as $group_data):
                                                        if (strpos($group_data, ':') !== false):
                                                            list($group_name, $group_color) = explode(':', $group_data);
                                                    ?>
                                                        <span class="badge me-1" style="background-color: <?= htmlspecialchars($group_color) ?>">
                                                            <?= htmlspecialchars($group_name) ?>
                                                        </span>
                                                    <?php 
                                                        endif;
                                                    endforeach; 
                                                    ?>
                                                <?php else: ?>
                                                    <span class="text-muted">No groups</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <i class="fas fa-circle <?= $user['is_active'] ? 'text-success' : 'text-danger' ?>"></i>
                                                <?= $user['is_active'] ? 'Active' : 'Inactive' ?>
                                            </td>
                                            <td>
                                                <small><?= date('M j, Y', strtotime($user['created_at'])) ?></small>
                                            </td>
                                            <td>
                                                <div class="btn-group btn-group-sm">
                                                    <button class="btn btn-outline-primary" onclick="editUser(<?= $user['id'] ?>)">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <button class="btn btn-outline-info" onclick="viewUser(<?= $user['id'] ?>)">
                                                        <i class="fas fa-eye"></i>
                                                    </button>
                                                    <button class="btn btn-outline-<?= $user['is_active'] ? 'warning' : 'success' ?>" onclick="toggleUserStatus(<?= $user['id'] ?>, <?= $user['is_active'] ? 0 : 1 ?>)" title="<?= $user['is_active'] ? 'Deactivate' : 'Activate' ?> User">
                                                        <i class="fas fa-<?= $user['is_active'] ? 'user-slash' : 'user-check' ?>"></i>
                                                    </button>
                                                    <?php if ($user['id'] != $current_user_id): ?>
                                                    <button class="btn btn-outline-danger" onclick="deleteUser(<?= $user['id'] ?>)">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        
                        <!-- Groups Tab -->
                        <div class="tab-pane fade" id="groups" role="tabpanel">
                            <div class="d-flex justify-content-between align-items-center mb-4">
                                <h5 class="mb-0">Group Management</h5>
                                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addGroupModal">
                                    <i class="fas fa-plus me-2"></i>Create New Group
                                </button>
                            </div>
                            
                            <div class="row g-4">
                                <?php foreach ($groups as $group): ?>
                                <div class="col-lg-4 col-md-6">
                                    <div class="card h-100 border">
                                        <div class="card-header d-flex justify-content-between align-items-center">
                                            <h6 class="mb-0">
                                                <i class="fas fa-layer-group me-2 text-primary"></i><?= htmlspecialchars($group['name']) ?>
                                            </h6>
                                            <span class="badge bg-secondary"><?= $group['member_count'] ?> members</span>
                                        </div>
                                        <div class="card-body">
                                            <p class="card-text text-muted"><?= htmlspecialchars($group['description'] ?: 'No description') ?></p>
                                            <div class="d-flex justify-content-between align-items-center">
                                                <small class="text-muted">
                                                    Created by: <?= htmlspecialchars($group['created_by_name'] ?: 'Unknown') ?>
                                                </small>
                                                <div class="btn-group btn-group-sm">
                                                    <button class="btn btn-outline-primary" onclick="editGroup(<?= $group['id'] ?>)">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <button class="btn btn-outline-info" onclick="viewGroupMembers(<?= $group['id'] ?>)">
                                                        <i class="fas fa-users"></i>
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        
                        <!-- Roles Tab -->
                        <div class="tab-pane fade" id="roles" role="tabpanel">
                            <h5 class="mb-4">Role Statistics & Permissions</h5>
                            
                            <div class="row g-4">
                                <?php foreach ($role_stats as $role_stat): ?>
                                <div class="col-lg-3 col-md-6">
                                    <div class="card text-center">
                                        <div class="card-body">
                                            <i class="fas fa-user-tag fa-2x text-<?= getRoleColor($role_stat['role']) ?> mb-3"></i>
                                            <h4><?= $role_stat['count'] ?></h4>
                                            <p class="card-text"><?= ucfirst(str_replace('_', ' ', $role_stat['role'])) ?></p>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            
                            <div class="mt-5">
                                <h6>Role Hierarchy & Permissions</h6>
                                <div class="table-responsive">
                                    <table class="table table-sm">
                                        <thead>
                                            <tr>
                                                <th>Role</th>
                                                <th>Can Create</th>
                                                <th>Permissions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr>
                                                <td><span class="badge bg-danger">Super Admin</span></td>
                                                <td>All roles</td>
                                                <td>Full system access, user management, system settings</td>
                                            </tr>
                                            <tr>
                                                <td><span class="badge bg-warning">Admin</span></td>
                                                <td>Judge, Office, Media, Participant</td>
                                                <td>User management, event management, reports</td>
                                            </tr>
                                            <tr>
                                                <td><span class="badge bg-success">Head Judge</span></td>
                                                <td>-</td>
                                                <td>Judge management, score override, judge reports</td>
                                            </tr>
                                            <tr>
                                                <td><span class="badge bg-primary">Judge</span></td>
                                                <td>-</td>
                                                <td>Score entry, assigned events only</td>
                                            </tr>
                                            <tr>
                                                <td><span class="badge bg-info">Office</span></td>
                                                <td>Media, Participant</td>
                                                <td>Event coordination, participant management</td>
                                            </tr>
                                            <tr>
                                                <td><span class="badge bg-secondary">Media</span></td>
                                                <td>-</td>
                                                <td>Photo/video access, media management</td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add User Modal -->
    <div class="modal fade" id="addUserModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-user-plus me-2"></i>Add New User
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="post" id="addUserForm">
                    <input type="hidden" name="action" value="add_user">
                    <div class="modal-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Full Name *</label>
                                <input type="text" class="form-control" name="full_name" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Username *</label>
                                <input type="text" class="form-control" name="username" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Email</label>
                                <input type="email" class="form-control" name="email">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Phone</label>
                                <input type="text" class="form-control" name="phone">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Password *</label>
                                <input type="password" class="form-control" name="password" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Role *</label>
                                <select class="form-select" name="role" required>
                                    <?php foreach (getRolesUserCanCreate($user_role) as $role): ?>
                                    <option value="<?= $role ?>"><?= ucfirst(str_replace('_', ' ', $role)) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-12">
                                <label class="form-label">Groups</label>
                                <div class="row">
                                    <?php foreach ($groups as $group): ?>
                                    <div class="col-md-6">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="groups[]" value="<?= $group['id'] ?>" id="group_<?= $group['id'] ?>">
                                            <label class="form-check-label" for="group_<?= $group['id'] ?>">
                                                <span class="badge" style="background-color: <?= htmlspecialchars($group['color']) ?>">
                                                    <?= htmlspecialchars($group['name']) ?>
                                                </span>
                                            </label>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-plus me-2"></i>Create User
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Group Modal -->
    <div class="modal fade" id="addGroupModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-layer-group me-2"></i>Create New Group
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="post">
                    <input type="hidden" name="action" value="add_group">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Group Name *</label>
                            <input type="text" class="form-control" name="group_name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Description</label>
                            <textarea class="form-control" name="group_description" rows="3"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Color</label>
                            <input type="color" class="form-control form-control-color" name="group_color" value="#007bff">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-plus me-2"></i>Create Group
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit User Modal -->
    <div class="modal fade" id="editUserModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-user-edit me-2"></i>Edit User
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="post" id="editUserForm">
                    <input type="hidden" name="action" value="edit_user">
                    <input type="hidden" name="user_id" id="edit_user_id">
                    <div class="modal-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Full Name *</label>
                                <input type="text" class="form-control" name="full_name" id="edit_full_name" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Username *</label>
                                <input type="text" class="form-control" name="username" id="edit_username" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Email</label>
                                <input type="email" class="form-control" name="email" id="edit_email">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Phone</label>
                                <input type="text" class="form-control" name="phone" id="edit_phone">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Role *</label>
                                <select class="form-select" name="role" id="edit_role" required>
                                    <?php foreach (getRolesUserCanCreate($user_role) as $role): ?>
                                    <option value="<?= $role ?>"><?= ucfirst(str_replace('_', ' ', $role)) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <div class="form-check mt-4">
                                    <input class="form-check-input" type="checkbox" name="is_active" id="edit_is_active">
                                    <label class="form-check-label" for="edit_is_active">
                                        Active User
                                    </label>
                                </div>
                            </div>
                            <div class="col-12">
                                <label class="form-label">Notes</label>
                                <textarea class="form-control" name="notes" id="edit_notes" rows="3" placeholder="Internal notes about this user..."></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save me-2"></i>Save Changes
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- View User Details Modal -->
    <div class="modal fade" id="viewUserModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-user me-2"></i>User Details
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="userDetailsContent">
                        <div class="text-center">
                            <div class="spinner-border text-primary"></div>
                            <p class="mt-2">Loading user details...</p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" onclick="editCurrentUser()">
                        <i class="fas fa-edit me-2"></i>Edit User
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Group Members Modal -->
    <div class="modal fade" id="groupMembersModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-users me-2"></i>Group Members
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="groupMembersContent">
                        <div class="text-center">
                            <div class="spinner-border text-primary"></div>
                            <p class="mt-2">Loading group members...</p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" onclick="showAddMemberForm()">
                        <i class="fas fa-user-plus me-2"></i>Add Member
                    </button>
                </div>
            </div>
        </div>
    </div>

    <    <!-- Edit Group Modal -->
    <div class="modal fade" id="editGroupModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-edit me-2"></i>Edit Group
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="post" id="editGroupForm">
                    <input type="hidden" name="action" value="edit_group">
                    <input type="hidden" name="group_id" id="edit_group_id">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Group Name *</label>
                            <input type="text" class="form-control" name="group_name" id="edit_group_name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Description</label>
                            <textarea class="form-control" name="group_description" id="edit_group_description" rows="3"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Color</label>
                            <input type="color" class="form-control form-control-color" name="group_color" id="edit_group_color">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save me-2"></i>Update Group
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Member to Group Modal -->
    <div class="modal fade" id="addMemberModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-user-plus me-2"></i>Add Member to Group
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="post" id="addMemberForm">
                    <input type="hidden" name="action" value="add_member_to_group">
                    <input type="hidden" name="group_id" id="add_member_group_id">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Select User *</label>
                            <select class="form-select" name="user_id" id="add_member_user_id" required>
                                <option value="">Choose user...</option>
                                <?php foreach ($users as $user): ?>
                                <option value="<?= $user['id'] ?>"><?= htmlspecialchars($user['full_name'] ?: $user['username']) ?> (@<?= htmlspecialchars($user['username']) ?>)</option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Role in Group</label>
                            <select class="form-select" name="role_in_group">
                                <option value="member">Member</option>
                                <option value="admin">Admin</option>
                                <option value="moderator">Moderator</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-plus me-2"></i>Add Member
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        let currentUserId = null;
        let currentGroupId = null;
        
        function editUser(userId) {
            currentUserId = userId;
            
            // Fetch user data
            fetch(`api/user_management_api.php?action=get_user&id=${userId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const user = data.user;
                        
                        // Populate form fields
                        document.getElementById('edit_user_id').value = user.id;
                        document.getElementById('edit_full_name').value = user.full_name || '';
                        document.getElementById('edit_username').value = user.username;
                        document.getElementById('edit_email').value = user.email || '';
                        document.getElementById('edit_phone').value = user.phone || '';
                        document.getElementById('edit_role').value = user.role;
                        document.getElementById('edit_is_active').checked = user.is_active == 1;
                        document.getElementById('edit_notes').value = user.notes || '';
                        
                        // Show modal
                        const modal = new bootstrap.Modal(document.getElementById('editUserModal'));
                        modal.show();
                    } else {
                        showNotification('Error loading user data: ' + data.message, 'error');
                    }
                })
                .catch(error => {
                    showNotification('Network error: ' + error.message, 'error');
                });
        }
        
        function viewUser(userId) {
            currentUserId = userId;
            
            // Show modal first
            const modal = new bootstrap.Modal(document.getElementById('viewUserModal'));
            modal.show();
            
            // Fetch user data
            fetch(`api/user_management_api.php?action=get_user&id=${userId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const user = data.user;
                        
                        const content = `
                            <div class="row g-4">
                                <div class="col-md-4 text-center">
                                    <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center mx-auto mb-3" style="width: 80px; height: 80px; font-size: 1.5rem;">
                                        <strong>${(user.full_name || user.username).substring(0, 2).toUpperCase()}</strong>
                                    </div>
                                    <h5>${user.full_name || user.username}</h5>
                                    <span class="badge bg-${getRoleColor(user.role)} mb-2">${user.role.replace('_', ' ').toUpperCase()}</span>
                                    <div>
                                        <i class="fas fa-circle ${user.is_active == 1 ? 'text-success' : 'text-danger'}"></i>
                                        ${user.is_active == 1 ? 'Active' : 'Inactive'}
                                    </div>
                                </div>
                                <div class="col-md-8">
                                    <table class="table table-borderless">
                                        <tr><th>Username:</th><td>@${user.username}</td></tr>
                                        <tr><th>Email:</th><td>${user.email || 'Not provided'}</td></tr>
                                        <tr><th>Phone:</th><td>${user.phone || 'Not provided'}</td></tr>
                                        <tr><th>Groups:</th><td>${user.group_names ? user.group_names.split(',').map(g => `<span class="badge bg-secondary me-1">${g}</span>`).join('') : 'No groups'}</td></tr>
                                        <tr><th>Created:</th><td>${new Date(user.created_at).toLocaleDateString()}</td></tr>
                                        <tr><th>Last Login:</th><td>${user.last_login ? new Date(user.last_login).toLocaleDateString() : 'Never'}</td></tr>
                                    </table>
                                    ${user.notes ? `<div class="mt-3"><strong>Notes:</strong><p class="text-muted">${user.notes}</p></div>` : ''}
                                </div>
                            </div>
                        `;
                        
                        document.getElementById('userDetailsContent').innerHTML = content;
                    } else {
                        document.getElementById('userDetailsContent').innerHTML = 
                            `<div class="alert alert-danger">Error loading user data: ${data.message}</div>`;
                    }
                })
                .catch(error => {
                    document.getElementById('userDetailsContent').innerHTML = 
                        `<div class="alert alert-danger">Network error: ${error.message}</div>`;
                });
        }
        
        function deleteUser(userId) {
            if (confirm('Are you sure you want to delete this user? This action cannot be undone.')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="delete_user">
                    <input type="hidden" name="user_id" value="${userId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
        
        function toggleUserStatus(userId, newStatus) {
            const statusText = newStatus ? 'activate' : 'deactivate';
            if (confirm(`Are you sure you want to ${statusText} this user?`)) {
                // Create a simple form submission for status toggle
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="edit_user">
                    <input type="hidden" name="user_id" value="${userId}">
                    <input type="hidden" name="toggle_status" value="1">
                    <input type="hidden" name="is_active" value="${newStatus ? '1' : ''}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
        
        function editGroup(groupId) {
            // Fetch group data and populate the edit form
            fetch(`api/user_management_api.php?action=get_group&id=${groupId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const group = data.group;
                        
                        // Populate form fields
                        document.getElementById('edit_group_id').value = group.id;
                        document.getElementById('edit_group_name').value = group.name;
                        document.getElementById('edit_group_description').value = group.description || '';
                        document.getElementById('edit_group_color').value = group.color || '#007bff';
                        
                        // Show modal
                        const modal = new bootstrap.Modal(document.getElementById('editGroupModal'));
                        modal.show();
                    } else {
                        // Fallback if API doesn't exist - use inline data
                        const groupData = <?= json_encode($groups) ?>;
                        const group = groupData.find(g => g.id == groupId);
                        
                        if (group) {
                            document.getElementById('edit_group_id').value = group.id;
                            document.getElementById('edit_group_name').value = group.name;
                            document.getElementById('edit_group_description').value = group.description || '';
                            document.getElementById('edit_group_color').value = group.color || '#007bff';
                            
                            const modal = new bootstrap.Modal(document.getElementById('editGroupModal'));
                            modal.show();
                        }
                    }
                })
                .catch(error => {
                    // Fallback to inline data
                    const groupData = <?= json_encode($groups) ?>;
                    const group = groupData.find(g => g.id == groupId);
                    
                    if (group) {
                        document.getElementById('edit_group_id').value = group.id;
                        document.getElementById('edit_group_name').value = group.name;
                        document.getElementById('edit_group_description').value = group.description || '';
                        document.getElementById('edit_group_color').value = group.color || '#007bff';
                        
                        const modal = new bootstrap.Modal(document.getElementById('editGroupModal'));
                        modal.show();
                    }
                });
        }
        
        function viewGroupMembers(groupId) {
            currentGroupId = groupId;
            
            // Show modal first
            const modal = new bootstrap.Modal(document.getElementById('groupMembersModal'));
            modal.show();
            
            // Fetch group members
            fetch(`api/user_management_api.php?action=get_group_members&group_id=${groupId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const members = data.members;
                        
                        let content = '<div class="table-responsive"><table class="table table-hover"><thead><tr><th>User</th><th>Role in Group</th><th>Joined</th><th>Actions</th></tr></thead><tbody>';
                        
                        members.forEach(member => {
                            content += `
                                <tr>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 32px; height: 32px; font-size: 0.8rem;">
                                                <strong>${(member.full_name || member.username).substring(0, 2).toUpperCase()}</strong>
                                            </div>
                                            <div>
                                                <h6 class="mb-0">${member.full_name || member.username}</h6>
                                                <small class="text-muted">@${member.username}</small>
                                            </div>
                                        </div>
                                    </td>
                                    <td><span class="badge bg-info">${member.role_in_group}</span></td>
                                    <td><small>${new Date(member.joined_at).toLocaleDateString()}</small></td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-danger" onclick="removeFromGroup(${member.id}, ${groupId})">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    </td>
                                </tr>
                            `;
                        });
                        
                        content += '</tbody></table></div>';
                        
                        if (members.length === 0) {
                            content = '<div class="text-center text-muted py-4"><i class="fas fa-users display-4 opacity-25"></i><h6 class="mt-3">No members in this group</h6></div>';
                        }
                        
                        document.getElementById('groupMembersContent').innerHTML = content;
                    } else {
                        document.getElementById('groupMembersContent').innerHTML = 
                            `<div class="alert alert-danger">Error loading group members: ${data.message}</div>`;
                    }
                })
                .catch(error => {
                    document.getElementById('groupMembersContent').innerHTML = 
                        `<div class="alert alert-danger">Network error: ${error.message}</div>`;
                });
        }
        
        function editCurrentUser() {
            if (currentUserId) {
                const modal = bootstrap.Modal.getInstance(document.getElementById('viewUserModal'));
                modal.hide();
                editUser(currentUserId);
            }
        }
        
        function showAddMemberForm() {
            if (currentGroupId) {
                document.getElementById('add_member_group_id').value = currentGroupId;
                
                // Reset the form
                document.getElementById('add_member_user_id').value = '';
                document.querySelector('select[name="role_in_group"]').value = 'member';
                
                // Close group members modal and show add member modal
                const groupModal = bootstrap.Modal.getInstance(document.getElementById('groupMembersModal'));
                if (groupModal) {
                    groupModal.hide();
                }
                
                setTimeout(() => {
                    const addModal = new bootstrap.Modal(document.getElementById('addMemberModal'));
                    addModal.show();
                }, 300);
            }
        }
        
        function removeFromGroup(userId, groupId) {
            if (confirm('Remove this user from the group?')) {
                const formData = new FormData();
                formData.append('action', 'manage_group_membership');
                formData.append('user_id', userId);
                formData.append('group_id', groupId);
                formData.append('membership_action', 'remove');
                
                fetch('user_management.php', {
                    method: 'POST',
                    body: formData
                })
                .then(() => {
                    // Refresh group members
                    viewGroupMembers(groupId);
                    showNotification('User removed from group', 'success');
                })
                .catch(error => {
                    showNotification('Error removing user: ' + error.message, 'error');
                });
            }
        }
        
        function getRoleColor(role) {
            const colors = {
                'super_admin': 'danger',
                'admin': 'warning', 
                'head_judge': 'success',
                'judge': 'primary',
                'office': 'info',
                'media': 'secondary',
                'participant': 'light'
            };
            return colors[role] || 'light';
        }
        
        function showNotification(message, type) {
            const notification = document.createElement('div');
            notification.className = `alert alert-${type === 'success' ? 'success' : 'danger'} alert-dismissible fade show position-fixed`;
            notification.style.top = '20px';
            notification.style.right = '20px';
            notification.style.zIndex = '9999';
            notification.style.minWidth = '300px';
            
            notification.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            document.body.appendChild(notification);
            
            setTimeout(() => {
                if (notification.parentElement) {
                    notification.remove();
                }
            }, 5000);
        }
        
        // Generate username from full name
        document.querySelector('input[name="full_name"]').addEventListener('input', function(e) {
            const fullName = e.target.value;
            const username = fullName.toLowerCase().replace(/[^a-z0-9]/g, '_').replace(/_+/g, '_').replace(/^_|_$/g, '');
            document.querySelector('input[name="username"]').value = username;
        });
        
        // Handle add member form submission
        document.getElementById('addMemberForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            
            // Add some debugging
            console.log('Form data:', Object.fromEntries(formData));
            console.log('Current group ID:', currentGroupId);
            
            fetch('user_management.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(data => {
                console.log('Server response:', data);
                
                // Check if response contains success message
                if (data.includes('success:')) {
                    showNotification('Member added successfully', 'success');
                    // Close modal and refresh group members
                    const modal = bootstrap.Modal.getInstance(document.getElementById('addMemberModal'));
                    modal.hide();
                    
                    // Force page reload to ensure we see the changes
                    setTimeout(() => {
                        location.reload();
                    }, 1000);
                    
                    // Also try to refresh group members if modal is open
                    if (currentGroupId) {
                        setTimeout(() => {
                            viewGroupMembers(currentGroupId);
                        }, 500);
                    }
                } else if (data.includes('error:')) {
                    const errorMsg = data.split('error: ')[1] || 'Unknown error';
                    showNotification('Error: ' + errorMsg, 'error');
                } else {
                    console.log('Unexpected response format:', data);
                    showNotification('Unexpected response from server', 'error');
                }
            })
            .catch(error => {
                console.error('Network error:', error);
                showNotification('Network error: ' + error.message, 'error');
            });
        });
        
        // Clean URL after showing message
        if (window.location.search.includes('msg=')) {
            const cleanUrl = window.location.pathname;
            window.history.replaceState({}, document.title, cleanUrl);
        }
    </script>
</body>
</html>

<?php
function getRoleColor($role) {
    switch ($role) {
        case 'super_admin': return 'danger';
        case 'admin': return 'warning';
        case 'head_judge': return 'success';
        case 'judge': return 'primary';
        case 'office': return 'info';
        case 'media': return 'secondary';
        case 'participant': return 'light';
        default: return 'light';
    }
}
?>
