<?php

session_start();

if (!isset($_SESSION['user_id'])) {

    header('Location: index.php');

    exit;

}



require_once 'config.php';



// Check if user is admin

if ($_SESSION['role'] !== 'admin') {

    header('Location: dashboard.php?error=unauthorized');

    exit;

} 



$conn = getDBConnection();



// Handle form submissions

$message = '';

$messageType = '';



// Add/Edit User

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (isset($_POST['action']) && $_POST['action'] === 'add_user') {

        $username = trim((string) ($_POST['username'] ?? ''));

        $password = $_POST['password'] ?? '';

        $full_name = trim((string) ($_POST['full_name'] ?? ''));

        $email = trim((string) ($_POST['email'] ?? ''));

        $phone = trim((string) ($_POST['phone'] ?? ''));

        $role = trim((string) ($_POST['role'] ?? ''));



        if (empty($username) || empty($password) || empty($full_name) || empty($email) || empty($role)) {

            $message = 'Please fill all required fields';

            $messageType = 'danger';

        } else {

            // Check if username exists

            $checkStmt = $conn->prepare("SELECT id FROM users WHERE username = ?");

            $checkStmt->bind_param('s', $username);

            $checkStmt->execute();

            $check = $checkStmt->get_result();

            $checkStmt->close();

            if ($check->num_rows > 0) {

                $message = 'Username already exists';

                $messageType = 'danger';

            } else {

                $hashed_password = password_hash($password, PASSWORD_BCRYPT);

                

                $stmt = $conn->prepare("INSERT INTO users (username, password, full_name, email, phone, role) VALUES (?, ?, ?, ?, ?, ?)");

                $stmt->bind_param("ssssss", $username, $hashed_password, $full_name, $email, $phone, $role);

                

                if ($stmt->execute()) {

                    $message = 'User added successfully';

                    $messageType = 'success';

                    

                    // Log activity

                    logActivity($conn, $_SESSION['user_id'], 'Add User', "Added new user: $username ($role)");

                } else {

                    $message = 'Failed to add user: ' . $stmt->error;

                    $messageType = 'danger';

                }

                $stmt->close();

            }

        }

    }

    

    elseif (isset($_POST['action']) && $_POST['action'] === 'edit_user') {

        $user_id = intval($_POST['user_id'] ?? 0);

        $full_name = trim((string) ($_POST['full_name'] ?? ''));

        $email = trim((string) ($_POST['email'] ?? ''));

        $phone = trim((string) ($_POST['phone'] ?? ''));

        $role = trim((string) ($_POST['role'] ?? ''));

        $is_active = isset($_POST['is_active']) ? 1 : 0;

        

        $stmt = $conn->prepare("UPDATE users SET full_name = ?, email = ?, phone = ?, role = ?, is_active = ? WHERE id = ?");

        $stmt->bind_param("ssssii", $full_name, $email, $phone, $role, $is_active, $user_id);

        

        if ($stmt->execute()) {

            $message = 'User updated successfully';

            $messageType = 'success';

            

            // Log activity

            logActivity($conn, $_SESSION['user_id'], 'Edit User', "Edited user ID: $user_id");

        } else {

            $message = 'Failed to update user: ' . $stmt->error;

            $messageType = 'danger';

        }

        $stmt->close();

    }

    

    elseif (isset($_POST['action']) && $_POST['action'] === 'reset_password') {

        $user_id = intval($_POST['user_id'] ?? 0);

        $new_password = $_POST['new_password'] ?? '';

        

        if (empty($new_password)) {

            $message = 'Please enter a new password';

            $messageType = 'danger';

        } else {

            $hashed_password = password_hash($new_password, PASSWORD_BCRYPT);

            $stmt = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");

            $stmt->bind_param("si", $hashed_password, $user_id);

            

            if ($stmt->execute()) {

                $message = 'Password reset successfully';

                $messageType = 'success';

                

                // Log activity

                logActivity($conn, $_SESSION['user_id'], 'Reset Password', "Reset password for user ID: $user_id");

            } else {

                $message = 'Failed to reset password: ' . $stmt->error;

                $messageType = 'danger';

            }

            $stmt->close();

        }

    }

}



// Handle GET actions

if (isset($_GET['action']) && $_GET['action'] === 'delete_user' && isset($_GET['id'])) {

    $user_id = intval($_GET['id']);

    

    // Don't allow deleting yourself

    if ($user_id == $_SESSION['user_id']) {

        $message = 'You cannot delete your own account';

        $messageType = 'danger';

    } else {

        // Remove child records that reference this user before deleting the user row

        foreach (['user_activities', 'internal_messages'] as $_childTable) {

            $chk = $conn->query("SHOW TABLES LIKE '{$_childTable}'");

            if ($chk && $chk->num_rows > 0) {

                $col = $_childTable === 'internal_messages' ? 'sender_id' : 'user_id';

                $del = $conn->prepare("DELETE FROM {$_childTable} WHERE {$col} = ?");

                if ($del) { $del->bind_param('i', $user_id); $del->execute(); $del->close(); }

                // internal_messages can also reference as recipient

                if ($_childTable === 'internal_messages') {

                    $del2 = $conn->prepare("DELETE FROM internal_messages WHERE recipient_id = ?");

                    if ($del2) { $del2->bind_param('i', $user_id); $del2->execute(); $del2->close(); }

                }

            }

        }



        $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");

        $stmt->bind_param("i", $user_id);



        if ($stmt->execute()) {

            $message = 'User deleted successfully';

            $messageType = 'success';



            // Log activity

            logActivity($conn, $_SESSION['user_id'], 'Delete User', "Deleted user ID: $user_id");

        } else {

            $message = 'Failed to delete user: ' . $stmt->error;

            $messageType = 'danger';

        }

        $stmt->close();

    }

}



// Get all users

$users = [];

$result = $conn->query("SELECT * FROM users ORDER BY id DESC");

if ($result) {

    while ($row = $result->fetch_assoc()) {

        $users[] = $row;

    }

}



// Get recent activities

$activities = [];

$result = $conn->query("SELECT ua.*, u.full_name FROM user_activities ua JOIN users u ON ua.user_id = u.id ORDER BY ua.created_at DESC LIMIT 20");

if ($result) {

    while ($row = $result->fetch_assoc()) {

        $activities[] = $row;

    }

}





?>



<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>User Management - EduTrack PRO</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <link rel="stylesheet" href="css/style.css">

</head>

<body>

    <div class="wrapper">

        <!-- Sidebar -->

        <nav id="sidebar" class="sidebar">

        <?php echo buildSidebar(basename($_SERVER['PHP_SELF'])); ?>

        </nav>



        <!-- Main Content -->

        <div class="main-content">

            <!-- Header -->

            <header class="header">

                <button class="btn-toggle" id="sidebarToggle">

                    <i class="fas fa-bars"></i>

                </button>

                <div class="header-right">

                    <span class="badge bg-primary me-3">Role: <?php echo htmlspecialchars(ucfirst((string) ($_SESSION['role'] ?? ''))); ?></span>

                    <div class="dropdown">

                        <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">

                            <i class="fas fa-user-circle me-2"></i><?php echo htmlspecialchars((string) ($_SESSION['full_name'] ?? '')); ?>

                        </button>

                        <ul class="dropdown-menu dropdown-menu-end">

                            <li><a class="dropdown-item" href="profile.php"><i class="fas fa-user me-2"></i>Profile</a></li>

                            <li><a class="dropdown-item" href="settings.php"><i class="fas fa-cog me-2"></i>Settings</a></li>

                            <li><hr class="dropdown-divider"></li>

                            <li><a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>

                        </ul>

                    </div>

                </div>

            </header>



            <!-- Page Content -->

            <main class="content">

                <div class="content-header">

                    <div class="d-flex justify-content-between align-items-center">

                        <div>

                            <h2><i class="fas fa-users-cog me-2"></i>User Management</h2>

                            <p>Manage system users and roles</p>

                        </div>

                        <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>



                <!-- Alert Message -->

                <?php if ($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"></button>

                </div>

                <?php endif; ?>



                <!-- Users Tabs -->

                <ul class="nav nav-tabs" id="userTabs" role="tablist">

                    <li class="nav-item">

                        <button class="nav-link active" id="users-tab" data-bs-toggle="tab" data-bs-target="#users" type="button">

                            <i class="fas fa-users me-2"></i>All Users

                        </button>

                    </li>

                    <li class="nav-item">

                        <button class="nav-link" id="activities-tab" data-bs-toggle="tab" data-bs-target="#activities" type="button">

                            <i class="fas fa-history me-2"></i>Activity Log

                        </button>

                    </li>

                </ul>



                <div class="tab-content" id="userTabsContent">

                    <!-- Users Tab -->

                    <div class="tab-pane fade show active" id="users" role="tabpanel">

                        <div class="card">

                            <div class="card-header">

                                <h5><i class="fas fa-list me-2"></i>System Users</h5>

                            </div>

                            <div class="card-body">

                                <div class="table-responsive">

                                    <table class="table table-hover">

                                        <thead>

                                            <tr>

                                                <th>Username</th>

                                                <th>Full Name</th>

                                                <th>Phone</th>

                                                <th>Role</th>

                                                <th>Status</th>

                                                <th>Last Login</th>

                                                <th>Actions</th>

                                            </tr>

                                        </thead>

                                        <tbody>

                                            <?php foreach ($users as $user): ?>

                                            <tr>

                                                <td><?php echo htmlspecialchars($user['username']); ?></td>

                                                <td><?php echo htmlspecialchars($user['full_name']); ?></td>

                                              

                                                <td><?php echo htmlspecialchars($user['phone'] ?: '-'); ?></td>

                                                <td>

                                                    <span class="badge bg-<?php 

                                                        echo $user['role'] === 'admin' ? 'danger' : 

                                                            ($user['role'] === 'headteacher' ? 'primary' : 

                                                            ($user['role'] === 'accountant' ? 'success' : 

                                                            ($user['role'] === 'cashier' ? 'warning' : 'info'))); 

                                                    ?>">

                                                        <?php echo ucfirst($user['role']); ?>

                                                    </span>

                                                </td>

                                                <td>

                                                    <span class="badge bg-<?php echo $user['is_active'] ? 'success' : 'secondary'; ?>">

                                                        <?php echo $user['is_active'] ? 'Active' : 'Inactive'; ?>

                                                    </span>

                                                </td>

                                                <td><?php echo $user['last_login'] ? date('d M Y H:i', strtotime($user['last_login'])) : 'Never'; ?></td>

                                                <td>

                                                    <div class="action-buttons">

                                                        <button class="action-btn edit" onclick="editUser(<?php echo $user['id']; ?>)" title="Edit">

                                                            <i class="fas fa-edit"></i>

                                                        </button>

                                                        <button class="action-btn" onclick="resetPassword(<?php echo $user['id']; ?>)" title="Reset Password" style="background: rgba(52, 152, 219, 0.15); color: #3498db;">

                                                            <i class="fas fa-key"></i>

                                                        </button>

                                                        <?php if ($user['id'] != $_SESSION['user_id']): ?>

                                                        <a href="user_management.php?action=delete_user&id=<?php echo $user['id']; ?>" 

                                                           class="action-btn delete" 

                                                           title="Delete" 

                                                           onclick="return confirm('Are you sure you want to delete this user?');">

                                                            <i class="fas fa-trash"></i>

                                                        </a>

                                                        <?php endif; ?>

                                                    </div>

                                                </td>

                                            </tr>

                                            <?php endforeach; ?>

                                        </tbody>

                                    </table>

                                </div>

                            </div>

                        </div>

                    </div>



                    <!-- Activities Tab -->

                    <div class="tab-pane fade" id="activities" role="tabpanel">

                        <div class="card">

                            <div class="card-header">

                                <h5><i class="fas fa-history me-2"></i>User Activity Log</h5>

                            </div>

                            <div class="card-body">

                                <div class="table-responsive">

                                    <table class="table table-hover">

                                        <thead>

                                            <tr>

                                                <th>Date/Time</th>

                                                <th>User</th>

                                                <th>Action</th>

                                                <th>Description</th>

                                                <th>IP Address</th>

                                            </tr>

                                        </thead>

                                        <tbody>

                                            <?php if (empty($activities)): ?>

                                                <tr>

                                                    <td colspan="5" class="text-center py-4">

                                                        <div class="empty-state">

                                                            <i class="fas fa-history"></i>

                                                            <h4>No Activities</h4>

                                                            <p>User activities will appear here</p>

                                                        </div>

                                                    </td>

                                                </tr>

                                            <?php else: ?>

                                                <?php foreach ($activities as $activity): ?>

                                                <tr>

                                                    <td><?php echo date('d M Y H:i:s', strtotime($activity['created_at'])); ?></td>

                                                    <td><?php echo htmlspecialchars($activity['full_name']); ?></td>

                                                    <td><span class="badge bg-primary"><?php echo htmlspecialchars($activity['action']); ?></span></td>

                                                    <td><?php echo htmlspecialchars($activity['description']); ?></td>

                                                    <td><?php echo htmlspecialchars($activity['ip_address'] ?: '-'); ?></td>

                                                </tr>

                                                <?php endforeach; ?>

                                            <?php endif; ?>

                                        </tbody>

                                    </table>

                                </div>

                            </div>

                        </div>

                    </div>

                </div>

            </main>



            <!-- Footer -->

            <footer class="footer">

                <p>&copy; 2024 EduTrack PRO. All rights reserved.</p>

            </footer>

        </div>

    </div>



    <!-- Add User Modal -->

    <div class="modal fade" id="addUserModal" 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 New User</h5>

                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>

                </div>

                <form method="POST" action="user_management.php">

                    <input type="hidden" name="action" value="add_user">

                    <div class="modal-body">

                        <div class="mb-3">

                            <label class="form-label">Username *</label>

                            <input type="text" class="form-control" name="username" required>

                        </div>

                        <div class="mb-3">

                            <label class="form-label">Password *</label>

                            <input type="password" class="form-control" name="password" required>

                        </div>

                        <div class="mb-3">

                            <label class="form-label">Full Name *</label>

                            <input type="text" class="form-control" name="full_name" required>

                        </div>

                        <div class="mb-3">

                            <label class="form-label">Email *</label>

                            <input type="email" class="form-control" name="email" required>

                        </div>

                        <div class="mb-3">

                            <label class="form-label">Phone</label>

                            <input type="tel" class="form-control" name="phone">

                        </div>

                        <div class="mb-3">

                            <label class="form-label">Role *</label>

                            <select class="form-select" name="role" required>

                                <option value="">Select Role</option>

                                <option value="admin">Admin</option>

                                <option value="headteacher">Head Teacher/Mistress</option>

                                <option value="accountant">Accountant</option>

                                <option value="cashier">Cashier</option>

                                <option value="registrar">Registrar</option>

                                 <option value="supervisor">Supervisor</option>

                                  <option value="director">Director</option>

                                   <option value="tutor">Tutor</option>
                                   <option value="nurse">Nurse</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">Add User</button>

                    </div>

                </form>

            </div>

        </div>

    </div>



    <!-- Edit User Modal -->

    <div class="modal fade" id="editUserModal" tabindex="-1">

        <div class="modal-dialog">

            <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" action="user_management.php" id="editUserForm">

                    <input type="hidden" name="action" value="edit_user">

                    <input type="hidden" name="user_id" id="edit_user_id">

                    <div class="modal-body" id="editUserContent">

                        <!-- Loaded via AJAX -->

                        <p class="text-center">Loading...</p>

                    </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>



    <!-- Reset Password Modal -->

    <div class="modal fade" id="resetPasswordModal" tabindex="-1">

        <div class="modal-dialog">

            <div class="modal-content">

                <div class="modal-header">

                    <h5 class="modal-title"><i class="fas fa-key me-2"></i>Reset Password</h5>

                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>

                </div>

                <form method="POST" action="user_management.php">

                    <input type="hidden" name="action" value="reset_password">

                    <input type="hidden" name="user_id" id="reset_user_id">

                    <div class="modal-body">

                        <div class="mb-3">

                            <label class="form-label">New Password</label>

                            <input type="password" class="form-control" name="new_password" required>

                        </div>

                        <div class="mb-3">

                            <label class="form-label">Confirm Password</label>

                            <input type="password" class="form-control" id="confirm_password" required>

                        </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-warning">Reset Password</button>

                    </div>

                </form>

            </div>

        </div>

    </div>



    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>

    <script src="js/main.js"></script>

    <script>

        function editUser(id) {

            $('#edit_user_id').val(id);

            $('#editUserModal').modal('show');

            

            $.ajax({

                url: 'ajax/users.php?action=edit&id=' + id,

                type: 'GET',

                success: function(response) {

                    $('#editUserContent').html(response);

                },

                error: function() {

                    $('#editUserContent').html('<p class="text-danger">Failed to load user data</p>');

                }

            });

        }

        

        function resetPassword(id) {

            $('#reset_user_id').val(id);

            $('#resetPasswordModal').modal('show');

        }

        

        // Password confirmation validation

        $('#resetPasswordModal form').on('submit', function(e) {

            const password = $('input[name="new_password"]').val();

            const confirm = $('#confirm_password').val();

            

            if (password !== confirm) {

                e.preventDefault();

                alert('Passwords do not match!');

            }

        });

    </script>

</body>

</html>