<?php
session_start();
require_once '../config/database.php';

if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] != 'admin') {
    header('Location: ../index.php');
    exit();
}

$admin_id = $_SESSION['user_id'];
$conn = getDBConnection();

// Get user data including profile picture
$user_query = "SELECT profile_picture FROM users WHERE id = ?";
$stmt = $conn->prepare($user_query);
$stmt->bind_param("i", $admin_id);
$stmt->execute();
$user_result = $stmt->get_result();
$user = $user_result->fetch_assoc();
$stmt->close();

// Handle delete user
if (isset($_GET['delete'])) {
    $user_id = intval($_GET['delete']);
    $delete_query = "DELETE FROM users WHERE id = ? AND user_type != 'admin'";
    $stmt = $conn->prepare($delete_query);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->close();
    header('Location: users.php?success=deleted');
    exit();
}

// Get filter
$filter = isset($_GET['filter']) ? $_GET['filter'] : 'all';

// Get all users
$users_query = "SELECT * FROM users";
if ($filter != 'all') {
    $users_query .= " WHERE user_type = ?";
}
$users_query .= " ORDER BY created_at DESC";

if ($filter != 'all') {
    $stmt = $conn->prepare($users_query);
    $stmt->bind_param("s", $filter);
    $stmt->execute();
    $users_result = $stmt->get_result();
} else {
    $users_result = $conn->query($users_query);
}

$users = [];
while ($row = $users_result->fetch_assoc()) {
    $users[] = $row;
}

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Users - CODELAB</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <script src="../assets/js/dark-mode.js" defer></script>
</head>
<body>
    <nav class="navbar">
        <div class="nav-container">
            <div class="nav-brand">
                <?php if (isset($user['profile_picture']) && $user['profile_picture']): ?>
                    <img src="../<?php echo htmlspecialchars($user['profile_picture']); ?>" alt="Profile" class="nav-profile-pic">
                <?php else: ?>
                    <div class="nav-avatar">👨‍💼</div>
                <?php endif; ?>
                <h2>CODELAB ADMIN</h2>
            </div>
            <button class="burger-menu" onclick="toggleMenu()">
                <span></span>
                <span></span>
                <span></span>
            </button>
            <div class="nav-menu" id="nav-menu">
                <a href="dashboard.php" class="nav-link">Dashboard</a>
                <a href="users.php" class="nav-link active">Manage Users</a>
                <a href="subjects.php" class="nav-link">Manage Subjects</a>
                <a href="activities.php" class="nav-link">Manage Activities</a>
                <a href="profile.php" class="nav-link">Profile</a>
                <a href="../auth/logout.php" class="nav-link logout">Logout</a>
            </div>
        </div>
    </nav>

    <div class="main-content">
        <div class="dashboard-header">
            <h1>👥 Manage Users</h1>
        </div>

        <?php if (isset($_GET['success'])): ?>
            <div class="alert alert-success">
                <?php if ($_GET['success'] == 'deleted') echo 'User deleted successfully!'; ?>
            </div>
        <?php endif; ?>

        <!-- Filter -->
        <div class="filter-section">
            <div class="filter-group">
                <label>Filter by Type</label>
                <select onchange="window.location.href='users.php?filter=' + this.value">
                    <option value="all" <?php echo $filter == 'all' ? 'selected' : ''; ?>>All Users</option>
                    <option value="student" <?php echo $filter == 'student' ? 'selected' : ''; ?>>Students</option>
                    <option value="instructor" <?php echo $filter == 'instructor' ? 'selected' : ''; ?>>Instructors</option>
                    <option value="admin" <?php echo $filter == 'admin' ? 'selected' : ''; ?>>Admins</option>
                </select>
            </div>
        </div>

        <!-- Users Table -->
        <div class="dashboard-section full-width">
            <div class="data-table">
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>ID Number</th>
                            <th>Username</th>
                            <th>Full Name</th>
                            <th>Email</th>
                            <th>User Type</th>
                            <th>Created At</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($users as $u): ?>
                            <tr>
                                <td><?php echo $u['id']; ?></td>
                                <td><?php echo htmlspecialchars($u['id_number'] ?? 'N/A'); ?></td>
                                <td><?php echo htmlspecialchars($u['username']); ?></td>
                                <td><?php echo htmlspecialchars($u['full_name']); ?></td>
                                <td><?php echo htmlspecialchars($u['email']); ?></td>
                                <td><?php echo ucfirst($u['user_type']); ?></td>
                                <td><?php echo date('M d, Y', strtotime($u['created_at'])); ?></td>
                                <td>
                                    <?php if ($u['user_type'] != 'admin'): ?>
                                        <a href="?delete=<?php echo $u['id']; ?>"
                                           class="btn btn-small btn-danger"
                                           onclick="return confirm('Are you sure you want to delete this user?')">
                                            Delete
                                        </a>
                                    <?php else: ?>
                                        <span style="color: #999;">Protected</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        function toggleMenu() {
            const navMenu = document.getElementById('nav-menu');
            navMenu.classList.toggle('active');
        }
    </script>
</body>
</html>
