<?php
/**
 * Admin Users Management
 * GHAMECC Choir Management Platform
 */

// Include authentication functions
require_once '../includes/auth.php';
require_once '../config/database.php';

// Require login
requireLogin();

// Get user information
$userId = $_SESSION['user_id'];
$userFullName = $_SESSION['full_name'] ?? $_SESSION['email'] ?? 'User';
$userRole = $_SESSION['role'] ?? '';
$userDioceseId = $_SESSION['diocese_id'] ?? null;
$userCircuitId = $_SESSION['circuit_id'] ?? null;
$userSocietyId = $_SESSION['society_id'] ?? null;

// Set base path for includes
$basePath = '..';

// Define role hierarchies and permissions
$diocesanRoles = ['diocesan_chairman', 'diocesan_secretary', 'diocesan_music_director', 'diocesan_treasurer'];
$circuitRoles = ['circuit_chairman', 'circuit_secretary', 'circuit_music_director', 'circuit_treasurer'];
$societyRoles = ['society_secretary', 'society_treasurer', 'choirmaster'];

// Determine which roles the current user can create
$allowedRolesToCreate = [];

if ($userRole === 'admin') {
    // Admin can create any role
    $allowedRolesToCreate = array_merge(['admin'], $diocesanRoles, $circuitRoles, $societyRoles);
} elseif (in_array($userRole, $diocesanRoles) && $userDioceseId) {
    // Diocesan officers can create circuit roles for their diocese
    $allowedRolesToCreate = array_merge($circuitRoles, $societyRoles);
} elseif (in_array($userRole, $circuitRoles) && $userCircuitId) {
    // Circuit officers can create society roles for their circuit
    $allowedRolesToCreate = $societyRoles;
}

// Check if user has permission to access this page
$canAccessUserManagement = !empty($allowedRolesToCreate);
if (!$canAccessUserManagement) {
    header("Location: /ghameccapp/access-denied.php");
    exit;
}

// Get entity information if available
$userDioceseName = '';
$userCircuitName = '';
$userSocietyName = '';

if ($userDioceseId) {
    $diocese = fetchRow("SELECT name FROM dioceses WHERE id = ?", [$userDioceseId]);
    if ($diocese) {
        $userDioceseName = $diocese['name'];
    }
}

if ($userCircuitId) {
    $circuit = fetchRow("SELECT name FROM circuits WHERE id = ?", [$userCircuitId]);
    if ($circuit) {
        $userCircuitName = $circuit['name'];
    }
}

if ($userSocietyId) {
    $society = fetchRow("SELECT name FROM societies WHERE id = ?", [$userSocietyId]);
    if ($society) {
        $userSocietyName = $society['name'];
    }
}

// Process form submissions
$message = '';
$messageType = '';

// Handle user creation/update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'create' || $_POST['action'] === 'update') {
        $username = trim($_POST['username']);
        $fullName = trim($_POST['full_name']);
        $email = trim($_POST['email']);
        $role = trim($_POST['role']);
        $status = trim($_POST['status']);
        $password = isset($_POST['password']) ? trim($_POST['password']) : '';
        $userId = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
        
        // Validate input
        if (empty($username) || empty($fullName) || empty($email) || empty($role) || empty($status)) {
            $message = 'All fields are required.';
            $messageType = 'danger';
        } elseif (!in_array($role, $allowedRolesToCreate)) {
            $message = 'You do not have permission to create this role.';
            $messageType = 'danger';
        } else {
            // Connect to database
            global $conn;
            
            if ($_POST['action'] === 'create') {
                // Check if username already exists
                $stmt = $conn->prepare("SELECT id FROM users WHERE username = ?");
                $stmt->bind_param("s", $username);
                $stmt->execute();
                $result = $stmt->get_result();
                
                if ($result->num_rows > 0) {
                    $message = 'Username already exists.';
                    $messageType = 'danger';
                } else {
                    // Check if email already exists
                    $stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
                    $stmt->bind_param("s", $email);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    
                    if ($result->num_rows > 0) {
                        $message = 'Email address already exists. Please use a different email.';
                        $messageType = 'danger';
                    } else {
                        // Hash password
                        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                        
                        // Get circuit ID - either from form or from session for circuit officers
                        $circuitId = null;
                        $societyId = null;
                        if (in_array($userRole, $circuitRoles)) {
                            $circuitId = $userCircuitId; // Use circuit officer's circuit
                            if (isset($_POST['society'])) {
                                $societyId = (int)$_POST['society'];
                            }
                        } elseif (isset($_POST['circuit'])) {
                            $circuitId = (int)$_POST['circuit'];
                        }
                        
                        // Debug - log the connection and query details
                        error_log("Database connection status: " . ($conn ? "Connected" : "Not connected"));
                        error_log("Attempting to insert user: " . $username . " with role: " . $role);
                        
                        // Get role_id from role_key
                        $roleStmt = $conn->prepare("SELECT id FROM roles WHERE role_key = ?");
                        if ($roleStmt === false) {
                            $message = 'Error preparing role statement: ' . $conn->error;
                            $messageType = 'danger';
                            error_log("SQL Error: " . $conn->error);
                        } else {
                            $roleStmt->bind_param("s", $role);
                            $roleStmt->execute();
                            $roleResult = $roleStmt->get_result();
                            
                            if ($roleResult->num_rows > 0) {
                                $roleRow = $roleResult->fetch_assoc();
                                $roleId = $roleRow['id'];
                                $roleStmt->close();
                                
                                // Insert new user with role_id instead of role_key
                                $stmt = $conn->prepare("INSERT INTO users (username, password, full_name, email, role_id, status, created_by, circuit_id, society_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                                if ($stmt === false) {
                                    $message = 'Error preparing statement: ' . $conn->error;
                                    $messageType = 'danger';
                                    error_log("SQL Error: " . $conn->error);
                                } else {
                                    // Make sure created_by is a valid user ID (current logged-in user)
                                    $createdBy = $_SESSION['user_id'] ?? null;
                                    
                                    // Debug log
                                    error_log("Using created_by: " . $createdBy);
                                    
                                    $stmt->bind_param("ssssissii", $username, $hashedPassword, $fullName, $email, $roleId, $status, $createdBy, $circuitId, $societyId);
                                    
                                    try {
                                        if ($stmt->execute()) {
                                            $message = 'User created successfully.';
                                            $messageType = 'success';
                                        } else {
                                            $message = 'Error creating user: ' . $conn->error;
                                            $messageType = 'danger';
                                            error_log("SQL Error: " . $conn->error);
                                        }
                                    } catch (mysqli_sql_exception $e) {
                                        // Check for duplicate email error
                                        if (strpos($e->getMessage(), 'Duplicate entry') !== false && strpos($e->getMessage(), 'email') !== false) {
                                            $message = 'This email address is already in use. Please use a different email.';
                                        } else {
                                            $message = 'Error creating user: ' . $e->getMessage();
                                        }
                                        $messageType = 'danger';
                                        error_log("SQL Exception: " . $e->getMessage());
                                    }
                                    $stmt->close();
                                }
                            } else {
                                $message = 'Invalid role.';
                                $messageType = 'danger';
                            }
                        }
                    }
                }
            } else if ($_POST['action'] === 'update' && $userId > 0) {
                // Update existing user
                
                // Get role_id from role_key
                $role = trim($_POST['role']);
                $roleStmt = $conn->prepare("SELECT id FROM roles WHERE role_key = ?");
                if ($roleStmt === false) {
                    $message = 'Error preparing role statement: ' . $conn->error;
                    $messageType = 'danger';
                    error_log("SQL Error: " . $conn->error);
                } else {
                    $roleStmt->bind_param("s", $role);
                    $roleStmt->execute();
                    $roleResult = $roleStmt->get_result();
                    
                    if ($roleResult->num_rows > 0) {
                        $roleRow = $roleResult->fetch_assoc();
                        $roleId = $roleRow['id'];
                        $roleStmt->close();
                        
                        // Get circuit ID and society ID
                        $circuitId = isset($_POST['circuit']) ? (int)$_POST['circuit'] : null;
                        $societyId = isset($_POST['society']) ? (int)$_POST['society'] : null;
                        
                        if (in_array($userRole, $circuitRoles)) {
                            $circuitId = $userCircuitId; // Use circuit officer's circuit
                        }
                
                        if (!empty($password)) {
                            // Update with password
                            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                            $stmt = $conn->prepare("UPDATE users SET username = ?, password = ?, full_name = ?, email = ?, role_id = ?, status = ?, circuit_id = ?, society_id = ? WHERE id = ?");
                            $stmt->bind_param("ssssssiis", $username, $hashedPassword, $fullName, $email, $roleId, $status, $circuitId, $societyId, $userId);
                        } else {
                            // Update without password
                            $stmt = $conn->prepare("UPDATE users SET username = ?, full_name = ?, email = ?, role_id = ?, status = ?, circuit_id = ?, society_id = ? WHERE id = ?");
                            $stmt->bind_param("sssssiis", $username, $fullName, $email, $roleId, $status, $circuitId, $societyId, $userId);
                        }
                        
                        if ($stmt->execute()) {
                            $message = 'User updated successfully.';
                            $messageType = 'success';
                        } else {
                            $message = 'Error updating user: ' . $conn->error;
                            $messageType = 'danger';
                            error_log("SQL Error: " . $conn->error);
                        }
                        $stmt->close();
                    } else {
                        $message = 'Invalid role.';
                        $messageType = 'danger';
                    }
                }
            } else if ($_POST['action'] === 'delete' && isset($_POST['user_id'])) {
                $userIdToDelete = (int)$_POST['user_id'];
                
                // Don't allow deleting yourself
                if ($userIdToDelete === $userId) {
                    $message = 'You cannot delete your own account.';
                    $messageType = 'danger';
                } else {
                    // Connect to database
                    global $conn;
                    
                    // Delete user
                    $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
                    $stmt->bind_param("i", $userIdToDelete);
                    
                    if ($stmt->execute()) {
                        $message = 'User deleted successfully.';
                        $messageType = 'success';
                    } else {
                        $message = 'Error deleting user: ' . $conn->error;
                        $messageType = 'danger';
                        error_log("SQL Error: " . $conn->error);
                    }
                    
                    $stmt->close();
                }
            }
        }
    }
}

// Get all users
$users = [];
global $conn;

// Filter users based on role level
$whereClause = "";
$params = [];
$types = "";

if ($userRole === 'admin') {
    // Admin can see all users
    $whereClause = "";
} elseif (in_array($userRole, $diocesanRoles) && $userDioceseId) {
    // Diocesan officers can see users from their diocese, circuits, and societies
    $whereClause = "WHERE u.diocese_id = ? OR EXISTS (
                    SELECT 1 FROM circuits c 
                    WHERE c.diocese_id = ? AND u.circuit_id = c.id
                ) OR EXISTS (
                    SELECT 1 FROM societies s 
                    JOIN circuits c ON s.circuit_id = c.id 
                    WHERE c.diocese_id = ? AND u.society_id = s.id
                )";
    $params = [$userDioceseId, $userDioceseId, $userDioceseId];
    $types = "iii";
} elseif (in_array($userRole, $circuitRoles) && $userCircuitId) {
    // Circuit officers can see users from their circuit and societies
    $whereClause = "WHERE u.circuit_id = ? OR EXISTS (
                    SELECT 1 FROM societies s 
                    WHERE s.circuit_id = ? AND u.society_id = s.id
                )";
    $params = [$userCircuitId, $userCircuitId];
    $types = "ii";
} elseif (in_array($userRole, $societyRoles) && $userSocietyId) {
    // Society officers can see users from their society only
    $whereClause = "WHERE u.society_id = ?";
    $params = [$userSocietyId];
    $types = "i";
}

// Build and execute the query
$query = "SELECT u.id, u.username, u.full_name, u.email, u.role_id, u.status, u.created_at, 
         u.circuit_id, u.society_id, u.diocese_id 
         FROM users u $whereClause ORDER BY u.id";

if (!empty($params)) {
    $stmt = $conn->prepare($query);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
    $users = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
} else {
    $users = fetchRows($query);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Management - GHAMECC Choir Management</title>
    
    <?php include '../includes/favicon.php'; ?>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
    <!-- Custom CSS -->
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <!-- Navigation -->
    <?php include '../includes/navbar.php'; ?>
    
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <?php include '../includes/sidebar.php'; ?>
            
            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">User Management</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addUserModal">
                            <i class="fas fa-user-plus me-2"></i>Add New User
                        </button>
                    </div>
                </div>
                
                <?php if (!empty($message)): ?>
                <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
                    <?php echo $message; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php endif; ?>
                
                <!-- Users Table -->
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Users</h6>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered" id="usersTable" width="100%" cellspacing="0">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Username</th>
                                        <th>Full Name</th>
                                        <th>Email</th>
                                        <th>Role</th>
                                        <th>Status</th>
                                        <th>Created</th>
                                        <th>Circuit/Society</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($users as $user): ?>
                                    <tr>
                                        <td><?php echo $user['id']; ?></td>
                                        <td><?php echo htmlspecialchars($user['username']); ?></td>
                                        <td><?php echo htmlspecialchars($user['full_name']); ?></td>
                                        <td><?php echo htmlspecialchars($user['email']); ?></td>
                                        <td>
                                            <?php 
                                            $roleStmt = $conn->prepare("SELECT role_key FROM roles WHERE id = ?");
                                            $roleStmt->bind_param("i", $user['role_id']);
                                            $roleStmt->execute();
                                            $roleResult = $roleStmt->get_result();
                                            $roleRow = $roleResult->fetch_assoc();
                                            echo htmlspecialchars($roleRow['role_key']); 
                                            ?>
                                        </td>
                                        <td>
                                            <span class="badge bg-<?php echo $user['status'] === 'active' ? 'success' : 'danger'; ?>">
                                                <?php echo htmlspecialchars($user['status']); ?>
                                            </span>
                                        </td>
                                        <td><?php echo htmlspecialchars($user['created_at']); ?></td>
                                        <td>
                                            <?php 
                                            if ($user['circuit_id']) {
                                                $circuitStmt = $conn->prepare("SELECT name FROM circuits WHERE id = ?");
                                                $circuitStmt->bind_param("i", $user['circuit_id']);
                                                $circuitStmt->execute();
                                                $circuitResult = $circuitStmt->get_result();
                                                $circuitRow = $circuitResult->fetch_assoc();
                                                echo htmlspecialchars($circuitRow['name']);
                                            } elseif ($user['society_id']) {
                                                $societyStmt = $conn->prepare("SELECT name FROM societies WHERE id = ?");
                                                $societyStmt->bind_param("i", $user['society_id']);
                                                $societyStmt->execute();
                                                $societyResult = $societyStmt->get_result();
                                                $societyRow = $societyResult->fetch_assoc();
                                                echo htmlspecialchars($societyRow['name']);
                                            } else {
                                                echo 'N/A';
                                            }
                                            ?>
                                        </td>
                                        <td>
                                            <button type="button" class="btn btn-sm btn-primary edit-user" 
                                                    data-id="<?php echo $user['id']; ?>"
                                                    data-username="<?php echo htmlspecialchars($user['username']); ?>"
                                                    data-fullname="<?php echo htmlspecialchars($user['full_name']); ?>"
                                                    data-email="<?php echo htmlspecialchars($user['email']); ?>"
                                                    data-role="<?php echo htmlspecialchars($roleRow['role_key']); ?>"
                                                    data-status="<?php echo htmlspecialchars($user['status']); ?>"
                                                    data-bs-toggle="modal" data-bs-target="#editUserModal">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <?php if ($user['id'] !== $userId): ?>
                                            <button type="button" class="btn btn-sm btn-danger delete-user"
                                                    data-id="<?php echo $user['id']; ?>"
                                                    data-username="<?php echo htmlspecialchars($user['username']); ?>"
                                                    data-bs-toggle="modal" data-bs-target="#deleteUserModal">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>
    
    <!-- Add User Modal -->
    <div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="addUserModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addUserModalLabel">Add New User</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post" action="">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="create">
                        
                        <div class="mb-3">
                            <label for="username" class="form-label">Username</label>
                            <input type="text" class="form-control" id="username" name="username" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="password" class="form-label">Password</label>
                            <input type="password" class="form-control" id="password" name="password" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="full_name" class="form-label">Full Name</label>
                            <input type="text" class="form-control" id="full_name" name="full_name" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="email" class="form-label">Email</label>
                            <input type="email" class="form-control" id="email" name="email" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="role" class="form-label">Role</label>
                            <select class="form-select" id="role" name="role" required>
                                <?php foreach ($allowedRolesToCreate as $role): ?>
                                <option value="<?php echo $role; ?>"><?php echo ucfirst(str_replace('_', ' ', $role)); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <?php if (in_array($userRole, $circuitRoles)): ?>
                        <!-- For circuit roles, show society selection -->
                        <div class="mb-3">
                            <label for="society" class="form-label">Society</label>
                            <select class="form-select" id="society" name="society" required>
                                <?php 
                                $societies = fetchRows("SELECT id, name FROM societies WHERE circuit_id = ? ORDER BY name", [$userCircuitId]); 
                                foreach ($societies as $society): 
                                ?>
                                <option value="<?php echo $society['id']; ?>"><?php echo htmlspecialchars($society['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <!-- Hidden circuit field with the circuit officer's circuit -->
                        <input type="hidden" name="circuit" value="<?php echo $userCircuitId; ?>">
                        <?php else: ?>
                        <div class="mb-3">
                            <label for="circuit" class="form-label">Circuit</label>
                            <select class="form-select" id="circuit" name="circuit" required>
                                <?php $circuits = fetchRows("SELECT id, name FROM circuits ORDER BY name"); ?>
                                <?php foreach ($circuits as $circuit): ?>
                                <option value="<?php echo $circuit['id']; ?>"><?php echo $circuit['name']; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <?php endif; ?>
                        
                        <div class="mb-3">
                            <label for="status" class="form-label">Status</label>
                            <select class="form-select" id="status" name="status" required>
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                                <option value="suspended">Suspended</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">Create User</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Edit User Modal -->
    <div class="modal fade" id="editUserModal" tabindex="-1" aria-labelledby="editUserModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editUserModalLabel">Edit User</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post" action="">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="update">
                        <input type="hidden" name="user_id" id="edit_user_id">
                        
                        <div class="mb-3">
                            <label for="edit_username" class="form-label">Username</label>
                            <input type="text" class="form-control" id="edit_username" name="username" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="edit_password" class="form-label">Password (leave blank to keep current)</label>
                            <input type="password" class="form-control" id="edit_password" name="password">
                        </div>
                        
                        <div class="mb-3">
                            <label for="edit_full_name" class="form-label">Full Name</label>
                            <input type="text" class="form-control" id="edit_full_name" name="full_name" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="edit_email" class="form-label">Email</label>
                            <input type="email" class="form-control" id="edit_email" name="email" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="edit_role" class="form-label">Role</label>
                            <select class="form-select" id="edit_role" name="role" required>
                                <?php foreach ($allowedRolesToCreate as $role): ?>
                                <option value="<?php echo $role; ?>"><?php echo ucfirst(str_replace('_', ' ', $role)); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <?php if (in_array($userRole, $circuitRoles)): ?>
                        <!-- For circuit roles, show society selection -->
                        <div class="mb-3">
                            <label for="edit_society" class="form-label">Society</label>
                            <select class="form-select" id="edit_society" name="society" required>
                                <?php 
                                $societies = fetchRows("SELECT id, name FROM societies WHERE circuit_id = ? ORDER BY name", [$userCircuitId]); 
                                foreach ($societies as $society): 
                                ?>
                                <option value="<?php echo $society['id']; ?>"><?php echo htmlspecialchars($society['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <!-- Hidden circuit field with the circuit officer's circuit -->
                        <input type="hidden" name="circuit" value="<?php echo $userCircuitId; ?>">
                        <?php else: ?>
                        <div class="mb-3">
                            <label for="edit_circuit" class="form-label">Circuit</label>
                            <select class="form-select" id="edit_circuit" name="circuit" required>
                                <?php $circuits = fetchRows("SELECT id, name FROM circuits ORDER BY name"); ?>
                                <?php foreach ($circuits as $circuit): ?>
                                <option value="<?php echo $circuit['id']; ?>"><?php echo $circuit['name']; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <?php endif; ?>
                        
                        <div class="mb-3">
                            <label for="edit_status" class="form-label">Status</label>
                            <select class="form-select" id="edit_status" name="status" required>
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                                <option value="suspended">Suspended</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">Update User</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Delete User Modal -->
    <div class="modal fade" id="deleteUserModal" tabindex="-1" aria-labelledby="deleteUserModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteUserModalLabel">Confirm Delete</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete user <span id="delete_username"></span>?</p>
                    <p class="text-danger">This action cannot be undone.</p>
                </div>
                <div class="modal-footer">
                    <form method="post" action="">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="user_id" id="delete_user_id">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-danger">Delete User</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Bootstrap JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize DataTable
            $('#usersTable').DataTable();
            
            // Handle edit user modal
            $('.edit-user').click(function() {
                const id = $(this).data('id');
                const username = $(this).data('username');
                const fullName = $(this).data('fullname');
                const email = $(this).data('email');
                const role = $(this).data('role');
                const status = $(this).data('status');
                
                $('#edit_user_id').val(id);
                $('#edit_username').val(username);
                $('#edit_full_name').val(fullName);
                $('#edit_email').val(email);
                $('#edit_role').val(role);
                $('#edit_status').val(status);
            });
            
            // Handle delete user modal
            $('.delete-user').click(function() {
                const id = $(this).data('id');
                const username = $(this).data('username');
                
                $('#delete_user_id').val(id);
                $('#delete_username').text(username);
            });
        });
    </script>
</body>
</html>
