Sindbad~EG File Manager

Current Path : /home/copmadinaarea/thecopmadinaarea.org/attendance/admin/
Upload File :
Current File : /home/copmadinaarea/thecopmadinaarea.org/attendance/admin/users.php

<?php
require_once '../config/config.php';

// Check if user is logged in and is superuser
if (!isLoggedIn() || !hasRole('superuser')) {
    redirect('login.php');
}

$db = new Database();
$conn = $db->getConnection();

$success_message = '';
$error_message = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validateCSRFToken($_POST['csrf_token'] ?? '')) {
        $error_message = 'Invalid security token. Please try again.';
    } else {
        $action = $_POST['action'] ?? '';
        
        if ($action === 'create' || $action === 'update') {
            $username = sanitizeInput($_POST['username'] ?? '');
            $email = sanitizeInput($_POST['email'] ?? '');
            $full_name = sanitizeInput($_POST['full_name'] ?? '');
            $phone = sanitizeInput($_POST['phone'] ?? '');
            $role = $_POST['role'] ?? 'user';
            $location_id = $_POST['location_id'] ?? null;
            $is_active = isset($_POST['is_active']) ? 1 : 0;
            
            if (empty($username) || empty($email) || empty($full_name)) {
                $error_message = 'Username, email, and full name are required.';
            } else {
                try {
                    if ($action === 'create') {
                        $password = $_POST['password'] ?? '';
                        if (empty($password)) {
                            $error_message = 'Password is required for new users.';
                        } else {
                            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                            
                            $query = "INSERT INTO users (username, email, password, full_name, phone, role, location_id, is_active) 
                                      VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
                            $stmt = $conn->prepare($query);
                            $stmt->execute([$username, $email, $hashed_password, $full_name, $phone, $role, $location_id ?: null, $is_active]);
                            
                            logActivity($_SESSION['user_id'], 'create_user', "Created user: $username");
                            $success_message = 'User created successfully.';
                        }
                    } else {
                        $user_id = (int)$_POST['user_id'];
                        $password = $_POST['password'] ?? '';
                        
                        if (!empty($password)) {
                            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                            $query = "UPDATE users SET username = ?, email = ?, password = ?, full_name = ?, phone = ?, role = ?, location_id = ?, is_active = ? 
                                      WHERE id = ?";
                            $stmt = $conn->prepare($query);
                            $stmt->execute([$username, $email, $hashed_password, $full_name, $phone, $role, $location_id ?: null, $is_active, $user_id]);
                        } else {
                            $query = "UPDATE users SET username = ?, email = ?, full_name = ?, phone = ?, role = ?, location_id = ?, is_active = ? 
                                      WHERE id = ?";
                            $stmt = $conn->prepare($query);
                            $stmt->execute([$username, $email, $full_name, $phone, $role, $location_id ?: null, $is_active, $user_id]);
                        }
                        
                        logActivity($_SESSION['user_id'], 'update_user', "Updated user: $username");
                        $success_message = 'User updated successfully.';
                    }
                } catch (Exception $e) {
                    if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
                        $error_message = 'Username or email already exists.';
                    } else {
                        $error_message = 'An error occurred while saving the user.';
                    }
                }
            }
        } elseif ($action === 'delete') {
            $user_id = (int)$_POST['user_id'];
            
            // Prevent deleting own account
            if ($user_id == $_SESSION['user_id']) {
                $error_message = 'You cannot delete your own account.';
            } else {
                try {
                    $query = "DELETE FROM users WHERE id = ?";
                    $stmt = $conn->prepare($query);
                    $stmt->execute([$user_id]);
                    
                    logActivity($_SESSION['user_id'], 'delete_user', "Deleted user ID: $user_id");
                    $success_message = 'User deleted successfully.';
                } catch (Exception $e) {
                    $error_message = 'Cannot delete user. They may have associated records.';
                }
            }
        }
    }
}

// Get users with location information
$query = "SELECT u.*, l.name as location_name
          FROM users u 
          LEFT JOIN locations l ON u.location_id = l.id
          ORDER BY u.created_at DESC";
$stmt = $conn->prepare($query);
$stmt->execute();
$users = $stmt->fetchAll();

// Get locations for dropdown
$location_query = "SELECT id, name, type FROM locations WHERE is_active = 1 ORDER BY type, name";
$location_stmt = $conn->prepare($location_query);
$location_stmt->execute();
$locations = $location_stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Management - Admin Panel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#F59E0B',
                        accent: '#6B7280'
                    }
                }
            }
        }
    </script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .gradient-bg {
            background: linear-gradient(135deg, #3B82F6 0%, #F59E0B 50%, #6B7280 100%);
        }
    </style>
</head>
<body class="bg-gray-50">
    <!-- Include Sidebar -->
    <?php include 'includes/sidebar.php'; ?>

    <!-- Main Content -->
    <div class="md:ml-64">
        <!-- Header -->
        <header class="bg-white shadow-sm border-b">
            <div class="px-6 py-4">
                <div class="flex items-center justify-between">
                    <h1 class="text-2xl font-bold text-gray-900">User Management</h1>
                    <button onclick="showCreateModal()" class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition duration-300">
                        <i class="fas fa-plus mr-2"></i>
                        Create User
                    </button>
                </div>
            </div>
        </header>

        <!-- Content -->
        <main class="p-6">
            <!-- Success/Error Messages -->
            <?php if ($success_message): ?>
                <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-6">
                    <div class="flex items-center">
                        <i class="fas fa-check-circle mr-2"></i>
                        <span><?php echo $success_message; ?></span>
                    </div>
                </div>
            <?php endif; ?>

            <?php if ($error_message): ?>
                <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6">
                    <div class="flex items-center">
                        <i class="fas fa-exclamation-circle mr-2"></i>
                        <span><?php echo $error_message; ?></span>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Users Table -->
            <div class="bg-white rounded-lg shadow overflow-hidden">
                <div class="px-6 py-4 border-b">
                    <h3 class="text-lg font-semibold text-gray-900">
                        <i class="fas fa-users mr-2"></i>
                        System Users (<?php echo count($users); ?>)
                    </h3>
                </div>

                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    User
                                </th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Role
                                </th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Location
                                </th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Contact
                                </th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Last Login
                                </th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Status
                                </th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Actions
                                </th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php foreach ($users as $user): ?>
                                <tr class="hover:bg-gray-50">
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="flex items-center">
                                            <div class="w-10 h-10 bg-primary rounded-full flex items-center justify-center text-white font-bold">
                                                <?php echo strtoupper(substr($user['full_name'], 0, 1)); ?>
                                            </div>
                                            <div class="ml-4">
                                                <div class="text-sm font-medium text-gray-900">
                                                    <?php echo htmlspecialchars($user['full_name']); ?>
                                                </div>
                                                <div class="text-sm text-gray-500">
                                                    @<?php echo htmlspecialchars($user['username']); ?>
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium 
                                            <?php 
                                            switch($user['role']) {
                                                case 'superuser': echo 'bg-red-100 text-red-800'; break;
                                                case 'admin': echo 'bg-blue-100 text-blue-800'; break;
                                                default: echo 'bg-gray-100 text-gray-800';
                                            }
                                            ?>">
                                            <i class="fas <?php 
                                                switch($user['role']) {
                                                    case 'superuser': echo 'fa-crown'; break;
                                                    case 'admin': echo 'fa-user-cog'; break;
                                                    default: echo 'fa-user';
                                                }
                                            ?> mr-1"></i>
                                            <?php echo ucfirst($user['role']); ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                        <?php echo htmlspecialchars($user['location_name'] ?? 'All Locations'); ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="text-sm text-gray-900">
                                            <i class="fas fa-envelope mr-1"></i>
                                            <?php echo htmlspecialchars($user['email']); ?>
                                        </div>
                                        <?php if ($user['phone']): ?>
                                            <div class="text-sm text-gray-500">
                                                <i class="fas fa-phone mr-1"></i>
                                                <?php echo htmlspecialchars($user['phone']); ?>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                        <?php if ($user['last_login']): ?>
                                            <?php echo date('M j, Y', strtotime($user['last_login'])); ?><br>
                                            <span class="text-gray-500"><?php echo date('g:i A', strtotime($user['last_login'])); ?></span>
                                        <?php else: ?>
                                            <span class="text-gray-500">Never</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium <?php echo $user['is_active'] ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'; ?>">
                                            <?php echo $user['is_active'] ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                        <div class="flex space-x-2">
                                            <button onclick="editUser(<?php echo $user['id']; ?>)" 
                                                    class="text-primary hover:text-blue-700">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <?php if ($user['id'] != $_SESSION['user_id']): ?>
                                                <button onclick="deleteUser(<?php echo $user['id']; ?>)" 
                                                        class="text-red-600 hover:text-red-900">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </main>
    </div>

    <!-- Create/Edit User Modal -->
    <div id="userModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden items-center justify-center z-50">
        <div class="bg-white rounded-lg p-6 max-w-lg w-full mx-4">
            <div class="flex items-center justify-between mb-4">
                <h3 id="modalTitle" class="text-lg font-semibold text-gray-900">Create User</h3>
                <button onclick="closeModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <form method="POST" id="userForm">
                <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                <input type="hidden" name="action" id="formAction" value="create">
                <input type="hidden" name="user_id" id="userId">
                
                <div class="space-y-4">
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label for="username" class="block text-sm font-medium text-gray-700 mb-2">
                                Username <span class="text-red-500">*</span>
                            </label>
                            <input type="text" id="username" name="username" required
                                   class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                        </div>
                        
                        <div>
                            <label for="email" class="block text-sm font-medium text-gray-700 mb-2">
                                Email <span class="text-red-500">*</span>
                            </label>
                            <input type="email" id="email" name="email" required
                                   class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                        </div>
                    </div>
                    
                    <div>
                        <label for="full_name" class="block text-sm font-medium text-gray-700 mb-2">
                            Full Name <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="full_name" name="full_name" required
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                    </div>
                    
                    <div>
                        <label for="phone" class="block text-sm font-medium text-gray-700 mb-2">
                            Phone
                        </label>
                        <input type="tel" id="phone" name="phone"
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                    </div>
                    
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label for="role" class="block text-sm font-medium text-gray-700 mb-2">
                                Role
                            </label>
                            <select id="role" name="role" onchange="toggleLocationField()"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                                <option value="user">User</option>
                                <option value="admin">Admin</option>
                                <option value="superuser">Superuser</option>
                            </select>
                        </div>
                        
                        <div id="locationField">
                            <label for="location_id" class="block text-sm font-medium text-gray-700 mb-2">
                                Location
                            </label>
                            <select id="location_id" name="location_id"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                                <option value="">All Locations</option>
                                <?php foreach ($locations as $location): ?>
                                    <option value="<?php echo $location['id']; ?>">
                                        <?php echo htmlspecialchars($location['name']) . ' (' . ucfirst($location['type']) . ')'; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    
                    <div>
                        <label for="password" class="block text-sm font-medium text-gray-700 mb-2">
                            Password <span id="passwordRequired" class="text-red-500">*</span>
                        </label>
                        <input type="password" id="password" name="password"
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                        <p id="passwordHelp" class="text-sm text-gray-500 mt-1">Leave empty to keep current password</p>
                    </div>
                    
                    <div class="flex items-center">
                        <input type="checkbox" id="is_active" name="is_active" checked
                               class="h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded">
                        <label for="is_active" class="ml-2 block text-sm text-gray-700">
                            Active
                        </label>
                    </div>
                </div>
                
                <div class="flex justify-end space-x-4 mt-6">
                    <button type="button" onclick="closeModal()" 
                            class="px-4 py-2 text-gray-600 hover:text-gray-800">
                        Cancel
                    </button>
                    <button type="submit" 
                            class="px-4 py-2 bg-primary text-white rounded hover:bg-blue-700">
                        <span id="submitText">Create User</span>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div id="deleteModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden items-center justify-center z-50">
        <div class="bg-white rounded-lg p-6 max-w-sm mx-auto">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">Confirm Delete</h3>
            <p class="text-gray-600 mb-6">Are you sure you want to delete this user? This action cannot be undone.</p>
            <div class="flex justify-end space-x-4">
                <button onclick="closeDeleteModal()" class="px-4 py-2 text-gray-600 hover:text-gray-800">
                    Cancel
                </button>
                <form method="POST" id="deleteForm" class="inline">
                    <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="user_id" id="deleteId">
                    <button type="submit" class="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700">
                        Delete
                    </button>
                </form>
            </div>
        </div>
    </div>

    <script>
        function showCreateModal() {
            document.getElementById('modalTitle').textContent = 'Create User';
            document.getElementById('formAction').value = 'create';
            document.getElementById('submitText').textContent = 'Create User';
            document.getElementById('userForm').reset();
            document.getElementById('is_active').checked = true;
            document.getElementById('password').required = true;
            document.getElementById('passwordRequired').style.display = 'inline';
            document.getElementById('passwordHelp').style.display = 'none';
            document.getElementById('userModal').classList.remove('hidden');
            document.getElementById('userModal').classList.add('flex');
        }

        function editUser(id) {
            // Fetch user data via AJAX
            fetch('get_user_details.php?id=' + id)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const user = data.user;
                        
                        // Populate form fields
                        document.getElementById('modalTitle').textContent = 'Edit User';
                        document.getElementById('formAction').value = 'update';
                        document.getElementById('submitText').textContent = 'Update User';
                        document.getElementById('userId').value = user.id;
                        document.getElementById('username').value = user.username;
                        document.getElementById('email').value = user.email;
                        document.getElementById('full_name').value = user.full_name;
                        document.getElementById('phone').value = user.phone || '';
                        document.getElementById('role').value = user.role;
                        document.getElementById('location_id').value = user.location_id || '';
                        document.getElementById('is_active').checked = user.is_active == 1;
                        
                        // Password is optional for updates
                        document.getElementById('password').required = false;
                        document.getElementById('passwordRequired').style.display = 'none';
                        document.getElementById('passwordHelp').style.display = 'block';
                        
                        // Handle location field visibility
                        toggleLocationField();
                        
                        // Show modal
                        document.getElementById('userModal').classList.remove('hidden');
                        document.getElementById('userModal').classList.add('flex');
                    } else {
                        alert('Error loading user data: ' + data.message);
                    }
                })
                .catch(error => {
                    alert('Error loading user data');
                    console.error('Error:', error);
                });
        }

        function deleteUser(id) {
            document.getElementById('deleteId').value = id;
            document.getElementById('deleteModal').classList.remove('hidden');
            document.getElementById('deleteModal').classList.add('flex');
        }

        function toggleLocationField() {
            const role = document.getElementById('role').value;
            const locationField = document.getElementById('locationField');
            
            if (role === 'admin') {
                locationField.style.display = 'block';
            } else {
                locationField.style.display = 'block'; // Keep visible but optional
                if (role === 'superuser') {
                    document.getElementById('location_id').value = '';
                }
            }
        }

        function closeModal() {
            document.getElementById('userModal').classList.add('hidden');
            document.getElementById('userModal').classList.remove('flex');
        }

        function closeDeleteModal() {
            document.getElementById('deleteModal').classList.add('hidden');
            document.getElementById('deleteModal').classList.remove('flex');
        }

        // Close modals when clicking outside
        document.getElementById('userModal').addEventListener('click', function(e) {
            if (e.target === this) closeModal();
        });

        document.getElementById('deleteModal').addEventListener('click', function(e) {
            if (e.target === this) closeDeleteModal();
        });
    </script>
</body>
</html>

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists