<?php
// pages/admin/manage_users.php
// A page to view and manage all users.

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Ensure user is logged in and has admin role.
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || $_SESSION['user_role'] !== 'admin') {
    header("Location: index.php?page=login");
    exit();
}

// NOTE: You must ensure 'config/database.php' is correctly included and $pdo is available.
require_once 'config/database.php';
$users = [];
$message = '';
$is_error = false;

// Handle messages from other pages (e.g., after a successful registration)
if (isset($_SESSION['message'])) {
    $message = $_SESSION['message'];
    $is_error = $_SESSION['is_error'] ?? false;
    unset($_SESSION['message']);
    unset($_SESSION['is_error']);
}
// --- Pagination & Search/Filter Logic ---
$records_per_page = 10;
$current_page = isset($_GET['p']) && is_numeric($_GET['p']) ? (int)$_GET['p'] : 1;
// CORRECTED: changed $records_per_per_page to $records_per_page
$offset = ($current_page - 1) * $records_per_page;

$search_query = isset($_GET['search']) ? trim($_GET['search']) : '';
// ... rest of the code

$search_query = isset($_GET['search']) ? trim($_GET['search']) : '';
$role_filter = isset($_GET['role']) ? $_GET['role'] : 'all';

$sql_base = "FROM users u";
$params = [];
$where_clauses = [];
$param_count = 1;

// Add search filter
if (!empty($search_query)) {
    $where_clauses[] = "(u.full_name LIKE ? OR u.username LIKE ? OR u.email LIKE ?)";
    $params[] = '%' . $search_query . '%';
    $params[] = '%' . $search_query . '%';
    $params[] = '%' . $search_query . '%';
}

// Add role filter
if ($role_filter !== 'all') {
    $where_clauses[] = "u.role = ?";
    $params[] = $role_filter;
}

// Combine all WHERE clauses
$sql_where = !empty($where_clauses) ? " WHERE " . implode(" AND ", $where_clauses) : "";

try {
    // Get total number of records for pagination
    $sql_count = "SELECT COUNT(*) " . $sql_base . $sql_where;
    $stmt_count = $pdo->prepare($sql_count);
    $stmt_count->execute($params);
    $total_records = $stmt_count->fetchColumn();
    $total_pages = ceil($total_records / $records_per_page);

    // Fetch users for the current page
    $sql_users = "SELECT id, username, full_name, email, role, verified " . $sql_base . $sql_where . " ORDER BY created_at DESC LIMIT ? OFFSET ?";
    
    $stmt_users = $pdo->prepare($sql_users);

    foreach ($params as $param_value) {
        $stmt_users->bindValue($param_count, $param_value, PDO::PARAM_STR);
        $param_count++;
    }

    $stmt_users->bindValue($param_count, $records_per_page, PDO::PARAM_INT);
    $param_count++;
    $stmt_users->bindValue($param_count, $offset, PDO::PARAM_INT);
    
    $stmt_users->execute();
    $users = $stmt_users->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    $message = "Database error fetching users: " . $e->getMessage();
    $is_error = true;
    error_log("Manage Users Fetch Error: " . $e->getMessage());
}

?>

<div class="w-full max-w-7xl mx-auto p-6 bg-white rounded-lg shadow-xl">
    <div class="flex flex-col sm:flex-row justify-between items-center mb-6 pb-4 border-b border-gray-200">
        <h1 class="text-3xl font-extrabold text-gray-900 mb-2 sm:mb-0">Manage Users</h1>
        
        <div class="relative inline-block text-left group pb-2 -mb-2">
            <button type="button" class="inline-flex items-center justify-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                <i class="fas fa-plus-circle mr-2"></i> Add New User <i class="fas fa-caret-down ml-2"></i>
            </button>
            
            <div class="absolute right-0 mt-2 w-56 origin-top-right bg-white border border-gray-200 rounded-md shadow-lg ring-1 ring-black ring-opacity-5 z-10 hidden group-hover:block" style="min-width: 15rem;">
                <div class="py-1">
                    <a href="index.php?page=register_user&role=admin" class="flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 hover:text-blue-600">
                        <i class="fas fa-user-shield mr-3 w-4"></i> Register Admin
                    </a>
                    <a href="index.php?page=register_user&role=instructor" class="flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 hover:text-blue-600">
                        <i class="fas fa-chalkboard-teacher mr-3 w-4"></i> Register Instructor
                    </a>
                    <a href="index.php?page=register_user&role=student" class="flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 hover:text-blue-600">
                        <i class="fas fa-user-graduate mr-3 w-4"></i> Register Student
                    </a>
                </div>
            </div>
        </div>
        </div> <?php if (!empty($message)): ?>
        <div class="mb-4 p-4 rounded-md text-sm <?php echo $is_error ? 'bg-red-100 text-red-700' : 'bg-green-100 text-green-700'; ?>">
            <?= $message; ?>

        </div>
    <?php endif; ?>

    <div class="flex flex-col md:flex-row justify-between items-center mb-6 space-y-4 md:space-y-0 md:space-x-4">
        <form action="index.php" method="GET" class="flex-grow flex items-center space-x-2 w-full md:w-auto">
            <input type="hidden" name="page" value="manage_users">
            <input type="text" name="search" placeholder="Search by name, username, or email..." value="<?php echo htmlspecialchars($search_query); ?>" class="flex-grow p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            <button type="submit" class="bg-gray-200 text-gray-700 px-4 py-2 rounded-md hover:bg-gray-300 transition duration-300">
                <i class="fas fa-search"></i>
            </button>
        </form>
        <div class="w-full md:w-auto">
            <select name="role" onchange="window.location.href='index.php?page=manage_users&role='+this.value+'&search=<?php echo urlencode($search_query); ?>'" class="block w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                <option value="all" <?php echo $role_filter === 'all' ? 'selected' : ''; ?>>All Roles</option>
                <option value="admin" <?php echo $role_filter === 'admin' ? 'selected' : ''; ?>>Admins</option>
                <option value="instructor" <?php echo $role_filter === 'instructor' ? 'selected' : ''; ?>>Instructors</option>
                <option value="student" <?php echo $role_filter === 'student' ? 'selected' : ''; ?>>Students</option>
            </select>
        </div>
    </div>

    <?php if (!empty($users)): ?>
        <div class="overflow-x-auto bg-white rounded-lg shadow-sm">
            <table class="min-w-full leading-normal">
                <thead>
                    <tr class="bg-gray-100 text-left text-gray-600 uppercase text-sm leading-normal">
                        <th class="py-3 px-6 text-left">Full Name</th>
                        <th class="py-3 px-6 text-left">Username</th>
                        <th class="py-3 px-6 text-left">Email</th>
                        <th class="py-3 px-6 text-left">Role</th>
                        <th class="py-3 px-6 text-center">Actions</th>
                    </tr>
                </thead>
                <tbody class="text-gray-600 text-sm font-light">
                    <?php foreach ($users as $user): ?>
                        <tr class="border-b border-gray-200 hover:bg-gray-50">
                            <td class="py-3 px-6 text-left whitespace-nowrap">
                                <span class="font-medium text-gray-800"><?php echo htmlspecialchars($user['full_name']); ?></span>
                            </td>
                            <td class="py-3 px-6 text-left"><?php echo htmlspecialchars($user['username']); ?></td>
                            <td class="py-3 px-6 text-left"><?php echo htmlspecialchars($user['email']); ?></td>
                            <td class="py-3 px-6 text-left">
                                <span class="capitalize py-1 px-3 rounded-full text-xs font-semibold bg-gray-200 text-gray-800">
                                    <?php echo htmlspecialchars($user['role']); ?>
                                </span>
                            </td>
                            <td class="py-3 px-6 text-center">
                                <div class="flex item-center justify-center space-x-2">
                                    <a href="index.php?page=edit_user&user_id=<?php echo htmlspecialchars($user['id']); ?>" class="w-8 h-8 rounded-full bg-yellow-100 text-yellow-600 flex items-center justify-center hover:bg-yellow-200 transition duration-300" title="Edit User">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="index.php?page=delete_user&user_id=<?php echo htmlspecialchars($user['id']); ?>" onclick="return confirm('Are you sure you want to delete this user? This action is permanent.');" class="w-8 h-8 rounded-full bg-red-100 text-red-600 flex items-center justify-center hover:bg-red-200 transition duration-300" title="Delete User">
                                        <i class="fas fa-trash-alt"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <?php if ($total_pages > 1): ?>
            <div class="flex justify-center mt-6 space-x-2">
                <?php if ($current_page > 1): ?>
                    <a href="index.php?page=manage_users&p=<?php echo $current_page - 1; ?>&search=<?php echo urlencode($search_query); ?>&role=<?php echo urlencode($role_filter); ?>" class="bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300">Previous</a>
                <?php endif; ?>

                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <a href="index.php?page=manage_users&p=<?php echo $i; ?>&search=<?php echo urlencode($search_query); ?>&role=<?php echo urlencode($role_filter); ?>" class="px-4 py-2 rounded-lg <?php echo ($i === $current_page) ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-700 hover:bg-gray-300'; ?>">
                        <?php echo $i; ?>
                    </a>
                <?php endfor; ?>

                <?php if ($current_page < $total_pages): ?>
                    <a href="index.php?page=manage_users&p=<?php echo $current_page + 1; ?>&search=<?php echo urlencode($search_query); ?>&role=<?php echo urlencode($role_filter); ?>" class="bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300">Next</a>
                <?php endif; ?>
            </div>
        <?php endif; ?>

    <?php else: ?>
        <div class="mb-6 p-4 rounded-md text-center text-lg bg-gray-50 text-gray-700 border border-gray-200">
            No users found.
        </div>
    <?php endif; ?>
</div>